Programs & Examples On #Android build

For questions related to the build process of Android Applications, for all build tools.

What is the difference between compileSdkVersion and targetSdkVersion?

Late to the game.. and there are several great answers above-- essentially, that the compileSdkVersion is the version of the API the app is compiled against, while the targetSdkVersion indicates the version that the app was tested against.

I'd like to supplement those answers with the following notes:

  1. That targetSdkVersion impacts the way in which permissions are requested:
  • If the device is running Android 6.0 (API level 23) or higher, and the app's targetSdkVersion is 23 or higher, the app requests permissions from the user at run-time.
  • If the device is running Android 5.1 (API level 22) or lower, or the app's targetSdkVersion is 22 or lower, the system asks the user to grant the permissions when the user installs the app.
  1. If the compileSdkVersion is higher than the version declared by your app's targetSdkVersion, the system may enable compatibility behaviors to ensure that your app continues to work the way you expect. (ref)

  2. With each new Android release...

  • targetSdkVersion should be incremented to match the latest API level, then thoroughly test your application on the corresponding platform version
  • compileSdkVersion, on the other hand, does not need to be changed unless you're adding features exclusive to the new platform version
  • As a result, while targetSdkVersion is often (initially) less than than the compileSdkVersion, it's not uncommon to see a well-maintained/established app with targetSdkVersion > compileSdkVersion

Android Studio: Plugin with id 'android-library' not found

Just for the record (took me quite a while) before Grzegorzs answer worked for me I had to install "android support repository" through the SDK Manager!

Install it and add the following code above apply plugin: 'android-library' in the build.gradle of actionbarsherlock folder!

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.+'
    }
}

How to install Android SDK Build Tools on the command line?

However, it is too slow on running

Yes, I've had the same problem. Some of the file downloads are extremely slow (or at least they have been in the last couple of days). If you want to download everything there's not a lot you can do about that.

The result is that nothing in folder build-tools, and I want is aapt and apkbuilder, since I want to build apk from command line without ant.

Did you let it run to completion?

One thing you can do is filter the packages that are being downloaded using the -t switch.

For example:

tools/android update sdk --no-ui -t platform-tool

When I tried this the other day I got version 18.0.0 of the build tools installed. For some reason the latest version 18.0.1 is not included by this filter and the only way to get it was to install everything with the --all switch.

Installation failed with message Invalid File

This happened with me when I copied a project code from one laptop to another one and tried running the project. What fixed this for me was:

  1. Delete the project's build folder
  2. Clean Project
  3. Build project
  4. Run

Gradle, Android and the ANDROID_HOME SDK location

I have the same problem, seems the sample code can not find the android environment, instead to try to fix that I just remove the sample code from settings.gradle and then the installation goes fine.

after that just import the project in eclipse and that's all :)

failed to find target with hash string android-23

Update: Does not apply to the Android Studio released after this answer (April 2016)

Note: I think this might be a bug in Android Studio.

enter image description here

  1. Go to Project Structure
  2. Select App Module
  3. Under the first tab "Properties" change the Compile SDK Version to API XX from Google API xx (e.g. API 23 instead of Google API 23)
  4. Press OK
  5. Wait for the completion of on going process, in my case I did not get an error at this point.

Now revert Compiled Sdk Version back to Google API xx.

If this not work, then:

  1. With Google API (Google API xx instead of API xx), lower the build tool version (e.g. Google API 23 and build tool version 23.0.1)
  2. Press Ok and wait for completion of on going process
  3. Revert back your build tool version to what it was before you changed
  4. Press Ok
  5. Wait for the completion of process.
  6. Done!

Multiple Order By with LINQ

You can use the ThenBy and ThenByDescending extension methods:

foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

SELECT
 *,
 CASE
  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;


 gid | datepose | pvc | modifiedpvc 
-----+----------+-----+-------------
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

How to convert int to NSString?

int i = 25;
NSString *myString = [NSString stringWithFormat:@"%d",i];

This is one of many ways.

Why does "npm install" rewrite package-lock.json?

Use the npm ci command instead of npm install.

"ci" stands for "continuous integration".

It will install the project dependencies based on the package-lock.json file instead of the lenient package.json file dependencies.

It will produce identical builds to your team mates and it is also much faster.

You can read more about it in this blog post: https://blog.npmjs.org/post/171556855892/introducing-npm-ci-for-faster-more-reliable

Using Panel or PlaceHolder

The Placeholder does not render any tags for itself, so it is great for grouping content without the overhead of outer HTML tags.

The Panel does have outer HTML tags but does have some cool extra properties.

  • BackImageUrl: Gets/Sets the background image's URL for the panel

  • HorizontalAlign: Gets/Sets the
    horizontal alignment of the parent's contents

  • Wrap: Gets/Sets whether the
    panel's content wraps

There is a good article at startvbnet here.

best OCR (Optical character recognition) example in android

Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.

Let me explain using step-by-step guidance.

First, download the source code from https://github.com/rmtheis/tess-two.

Import all three projects. After importing you will get an error. To solve the error you have to create a res folder in the tess-two project

enter image description here

First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"

After doing this in all three project the error should be gone.

Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.

Now you just need to import it into your workspace, but first you have to download android-ndk from this site:

http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file

Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable

Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture

enter image description here

done it

Now open cmd and go to on D:\Android Workspace\tess-two like below

enter image description here

If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:

Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest

enter image description here

Import test-two in this and run OCRTest and run it; you will get the best example of OCR.

How to change port for jenkins window service when 8080 is being used

Start Jenkins from cmd line with this command :

java -jar jenkins.war --httpPort=8081

How do I make a stored procedure in MS Access?

If you mean the type of procedure you find in SQL Server, prior to 2010, you can't. If you want a query that accepts a parameter, you can use the query design window:

 PARAMETERS SomeParam Text(10);
 SELECT Field FROM Table
 WHERE OtherField=SomeParam

You can also say:

CREATE PROCEDURE ProcedureName
   (Parameter1 datatype, Parameter2 datatype) AS
   SQLStatement

From: http://msdn.microsoft.com/en-us/library/aa139977(office.10).aspx#acadvsql_procs

Note that the procedure contains only one statement.

Sending multipart/formdata with jQuery.ajax

I just built this function based on some info I read.

Use it like using .serialize(), instead just put .serializefiles();.
Working here in my tests.

//USAGE: $("#form").serializefiles();
(function($) {
$.fn.serializefiles = function() {
    var obj = $(this);
    /* ADD FILE TO PARAM AJAX */
    var formData = new FormData();
    $.each($(obj).find("input[type='file']"), function(i, tag) {
        $.each($(tag)[0].files, function(i, file) {
            formData.append(tag.name, file);
        });
    });
    var params = $(obj).serializeArray();
    $.each(params, function (i, val) {
        formData.append(val.name, val.value);
    });
    return formData;
};
})(jQuery);

What in layman's terms is a Recursive Function using PHP

Here is a practical example (there are several good ones already). I just wanted to add one that is useful to almost any developer.

At some point, developers will need to parse an object as with a response from an API or some type of object or array.

This function is initially called to parse an object which may just contain parameters, but what if the object also contains other objects or arrays? This will need to be addressed, and for the most part the basic function already does this, so the function just calls itself again (after confirming that the key or value is either an object or an array) and parses this new object or array. Ultimately what is returned is a string that creates each parameter on a line by itself for readability, but you could just as easily log the values to a log file or insert into a DB or whatever.

I added the $prefix parameter to use the parent element to help describe the end variable so that we can see what the value pertains to. It doesn't include things like null values, but this can be amended from this example.

If you have the object:

$apiReturn = new stdClass();
$apiReturn->shippingInfo = new stdClass();
$apiReturn->shippingInfo->fName = "Bill";
$apiReturn->shippingInfo->lName = "Test";
$apiReturn->shippingInfo->address1 = "22 S. Deleware St.";
$apiReturn->shippingInfo->city = "Chandler";
$apiReturn->shippingInfo->state = "AZ";
$apiReturn->shippingInfo->zip = 85225;
$apiReturn->phone = "602-312-4455";
$apiReturn->transactionDetails = array(
    "totalAmt" => "100.00",
     "currency" => "USD",
     "tax" => "5.00",
     "shipping" => "5.00"
);
$apiReturn->item = new stdClass();
$apiReturn->item->name = "T-shirt";
$apiReturn->item->color = "blue";
$apiReturn->item->itemQty = 1;

and use:

var_dump($apiReturn);

it will return:

object(stdClass)#1 (4) { ["shippingInfo"]=> object(stdClass)#2 (6) { ["fName"]=> string(4) "Bill" ["lName"]=> string(4) "Test" ["address1"]=> string(18) "22 S. Deleware St." ["city"]=> string(8) "Chandler" ["state"]=> string(2) "AZ" ["zip"]=> int(85225) } ["phone"]=> string(12) "602-312-4455" ["transactionDetails"]=> array(4) { ["totalAmt"]=> string(6) "100.00" ["currency"]=> string(3) "USD" ["tax"]=> string(4) "5.00" ["shipping"]=> string(4) "5.00" } ["item"]=> object(stdClass)#3 (3) { ["name"]=> string(7) "T-shirt" ["color"]=> string(4) "blue" ["itemQty"]=> int(1) } }

and here is the code to parse it into a string with a line break for each parameter:

function parseObj($obj, $prefix = ''){
    $stringRtrn = '';
    foreach($obj as $key=>$value){
        if($prefix){
            switch ($key) {
                case is_array($key):
                    foreach($key as $k=>$v){
                        $stringRtrn .= parseObj($key, $obj);
                    }
                    break;
                case is_object($key):
                    $stringRtrn .= parseObj($key, $obj);
                    break;
                default:
                    switch ($value) {
                        case is_array($value):
                            $stringRtrn .= parseObj($value, $key);
                            break;
                        case is_object($value):
                            $stringRtrn .= parseObj($value, $key);
                            break;
                        default:
                            $stringRtrn .= $prefix ."_". $key ." = ". $value ."<br>";
                            break;
                    }
                    break;
            }
        } else { // end if($prefix)
            switch($key){
                case is_array($key):
                    $stringRtrn .= parseObj($key, $obj);
                    break;
                case is_object($key):

                    $stringRtrn .= parseObj($key, $obj);
                    break;
                default:
                    switch ($value) {
                        case is_array($value):
                            $stringRtrn .= parseObj($value, $key);
                            break;
                        case is_object($value):
                            $stringRtrn .= parseObj($value, $key);
                            break;                      
                        default:
                            $stringRtrn .= $key ." = ". $value ."<br>";
                            break;
                    } // end inner switch 
            } // end outer switch
        } // end else
    } // end foreach($obj as $key=>$value)
    return $stringRtrn;
} // END parseObj()

This will return the object as follows:

shippingInfo_fName = Bill
shippingInfo_lName = Test
shippingInfo_address1 = 22 S. Deleware St.
shippingInfo_city = Chandler
shippingInfo_state = AZ
shippingInfo_zip = 85225
phone = 602-312-4455
transactionDetails_totalAmt = 100.00
transactionDetails_currency = USD
transactionDetails_tax = 5.00
transactionDetails_shipping = 5.00
item_name = T-shirt
item_color = blue
item_itemQty = 1

I did the nested switch statements to avoid confusion with if . . . ifelse . . . else, but it was almost as long. If it helps, just ask for the if conditionals and I can paste them for those who need it.

display HTML page after loading complete

put an overlay on the page

#loading-mask {
    background-color: white;
    height: 100%;
    left: 0;
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 9999;
}

and then delete that element in a window.onload handler or, hide it

window.onload=function() {
    document.getElementById('loading-mask').style.display='none';
}

Of course you should use your javascript library (jquery,prototype..) specific onload handler if you are using a library.

Plotting lines connecting points

I think you're going to need separate lines for each segment:

import numpy as np
import matplotlib.pyplot as plt

x, y = np.random.random(size=(2,10))

for i in range(0, len(x), 2):
    plt.plot(x[i:i+2], y[i:i+2], 'ro-')

plt.show()

(The numpy import is just to set up some random 2x10 sample data)

enter image description here

Using Excel as front end to Access database (with VBA)

You could try something like XLLoop. This lets you implement excel functions (UDFs) on an external server (server implementations in many different languages are provided).

For example you could use a MySQL database and Apache web server and then write the functions in PHP to serve up the data to your users.

BTW, I work on the project so let me know if you have any questions.

bash shell nested for loop

One one line (semi-colons necessary):

for i in 0 1 2 3 4 5 6 7 8 9; do for j in 0 1 2 3 4 5 6 7 8 9; do echo "$i$j"; done; done

Formatted for legibility (no semi-colons needed):

for i in 0 1 2 3 4 5 6 7 8 9
do
    for j in 0 1 2 3 4 5 6 7 8 9
    do 
        echo "$i$j"
    done
done

There are different views on how the shell code should be laid out over multiple lines; that's about what I normally use, unless I put the next operation on the same line as the do (saving two lines here).

Failed to install Python Cryptography package with PIP and setup.py

I had a similar issue, and found I was simply missing a dependency (libssl-dev, for me). As referenced in https://cryptography.io/en/latest/installation/, ensure that all dependencies are met:

On Windows

If you’re on Windows you’ll need to make sure you have OpenSSL installed. There are pre-compiled binaries available. If your installation is in an unusual location set the LIB and INCLUDE environment variables to include the corresponding locations. For example:

C:\> \path\to\vcvarsall.bat x86_amd64
C:\> set LIB=C:\OpenSSL-1.0.1f-64bit\lib;%LIB%
C:\> set INCLUDE=C:\OpenSSL-1.0.1f-64bit\include;%INCLUDE%
C:\> pip install cryptography

Building cryptography on Linux

cryptography should build very easily on Linux provided you have a C compiler, headers for Python (if you’re not using pypy), and headers for the OpenSSL and libffi libraries available on your system.

For Debian and Ubuntu, the following command will ensure that the required dependencies are installed:

sudo apt-get install build-essential libssl-dev libffi-dev python-dev

For Fedora and RHEL-derivatives, the following command will ensure that the required dependencies are installed:

sudo yum install gcc libffi-devel python-devel OpenSSL-devel

You should now be able to build and install cryptography with the usual.

pip install cryptography

Execute jQuery function after another function completes

You can use below code

$.when( Typer() ).done(function() {
       playBGM();
});

How do I resolve "HTTP Error 500.19 - Internal Server Error" on IIS7.0

I have just one more thing to say about this. With the same HTTP Error code, you can still have several different errors, as one of them has been posted here at the original question's description. For example: after I've edited the Web.Config file of an ASP.NET project, I had

Error Code 0x8007000d

"Only one <configSections> element allowed. It must be the first child element of the root <configuration> element "

As it says, you must NOT insert your own XML stuff before the <configSections> part of the Web.Config file. After I've inserted my snippet after the end tag of <configSections>, it worked just fine.

How to remove undefined and null values from an object using lodash?

For those of you getting here looking to remove from an array of objects and using lodash you can do something like this:


 const objects = [{ a: 'string', b: false, c: 'string', d: undefined }]
 const result = objects.map(({ a, b, c, d }) => _.pickBy({ a,b,c,d }, _.identity))

 // [{ a: 'string', c: 'string' }]

Note: You don't have to destruct if you don't want to.

Python - Get Yesterday's date as a string in YYYY-MM-DD format

Calling .isoformat() on a date object will give you YYYY-MM-DD

from datetime import date, timedelta
(date.today() - timedelta(1)).isoformat()

PHP Fatal error when trying to access phpmyadmin mb_detect_encoding

After reading about the extension_dir = "ext" i added the line to php.ini but didnt work, then started to look apache error log and saw the PHP was in fact unable to find the dll's in the specified directory "ext". I commented the extension_dir line, restarted Apache and looked the error log again, saw that PHP was now looking the dll's in C:/PHP/ext (by default i guess), but since im using other folders, that's not the correct path, so i uncommented the extension_dir line and wrote this:

extension_dir = "C:/Apache24/PHP/ext" 

In my configuration that is the correct path to dll's.

and of course, uncommented:

extension=php_mbstring.dll
extension=php_mysql.dll
extension=php_mysqli.dll

Restarted the Apache server and internet browser and now phpMyAdmin works with my mySQL login.

So, dll's incorrect path and dll's needed commented in php.ini were the problem.

Remember to restart Apache and internet browser after editing config files.

System spec: Windows 7 HB 64bit httpd-2.4.4-win32-ssl_0.9.8.zip php-5.4.16-Win32-VC9-x86.zip phpMyAdmin-4.0.4.1-all-languages.zip mysql-installer-community-5.6.11.0.msi

Hope this help. Thx for your comments too.

Get the size of a 2D array

Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:

array.length * array[0].length

PostgreSQL how to see which queries have run

I found the log file at /usr/local/var/log/postgres.log on a mac installation from brew.

How to install Google Play Services in a Genymotion VM (with no drag and drop support)?

With adb, you can install GApps and ARM Support zips without a drag & drop. emuking from XDA Developers has instructions for it:

I used 4.2.2, which is acceptable for my testing purposes. I then extracted both zip's "/system/..." folders to a folder on my desktop. In cmd prompt I used the following commands (step 1 is optional and for verification that adb is working):

  1. adb devices
  2. adb remount
  3. adb push "C:\Users\John\Desktop\GenyF_cked\system" /system

You'll have to change the folder name in "adb push" line to where you actually extracted both zip files. After doing it, I recommend you to "adb reboot" the device.

How do I get the web page contents from a WebView?

I know this is a late answer, but I found this question because I had the same problem. I think I found the answer in this post on lexandera.com. The code below is basically a cut-and-paste from the site. It seems to do the trick.

final Context myApp = this;

/* An instance of this class will be registered as a JavaScript interface */
class MyJavaScriptInterface
{
    @JavascriptInterface
    @SuppressWarnings("unused")
    public void processHTML(String html)
    {
        // process the html as needed by the app
    }
}

final WebView browser = (WebView)findViewById(R.id.browser);
/* JavaScript must be enabled if you want it to work, obviously */
browser.getSettings().setJavaScriptEnabled(true);

/* Register a new JavaScript interface called HTMLOUT */
browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");

/* WebViewClient must be set BEFORE calling loadUrl! */
browser.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url)
    {
        /* This call inject JavaScript into the page which just finished loading. */
        browser.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
    }
});

/* load a web page */
browser.loadUrl("http://lexandera.com/files/jsexamples/gethtml.html");

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

On Windows 10 - this is a workaround and does not fix the root issue however, if you just need to install something and move on; Execute the following at the command prompt, powershell or dockerfile:

pip config set global.trusted_host "pypi.org files.pythonhosted.org"

Retrofit 2 - Dynamic URL

step -*1 

movie_list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/selectableItemBackground"
    android:clickable="true"
    android:focusable="true"

    android:orientation="horizontal"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/row_padding_vertical"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingBottom="@dimen/row_padding_vertical">

    <ImageView
        android:id="@+id/ivImage"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_marginRight="10dp"
        android:src="@mipmap/ic_launcher" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:text="Hello"
            android:textColor="@color/title"
            android:textSize="16dp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/genre"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/title"
            android:text="realName" />
    </LinearLayout>

    <TextView
        android:id="@+id/year"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Team"
        android:textColor="@color/year" />

</LinearLayout>                                                                                                            

Api.java                                                                                  
import org.json.JSONObject;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;

public interface  Api {

    String BASE_URL = "https://simplifiedcoding.net/demos/";

    @GET("marvel")
    Call<List<Hero>> getHeroes();

    @FormUrlEncoded
    @POST("/login")
    public void login(@Field("username") String username, @Field("password") String password, Callback<List<Hero>> callback);

}


MoviesAdapter.java                                                                                       import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import java.util.List;

public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {

    private List<Hero> moviesList;

    Context context;


    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView title, year, genre;
        public ImageView ivImage;

        public MyViewHolder(View view) {
            super(view);
            title = (TextView) view.findViewById(R.id.title);
            genre = (TextView) view.findViewById(R.id.genre);
            year = (TextView) view.findViewById(R.id.year);
            ivImage =  view.findViewById(R.id.ivImage);
            ivImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Toast.makeText(context, "-" + moviesList.get(getAdapterPosition()).getName(), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }


    public MoviesAdapter(List<Hero> moviesList,Context context) {
        this.moviesList = moviesList;
        this.context = context;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.movie_list_row, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Hero movie = moviesList.get(position);
        holder.title.setText(movie.getName());
        holder.genre.setText(movie.getRealname());
        holder.year.setText(movie.getTeam());

        Picasso.get().load("http://i.imgur.com/DvpvklR.png").into(holder.ivImage);
    }

    @Override
    public int getItemCount() {
        return moviesList.size();
    }
}                                                                                                                                                        main activity                                                                                                               import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    private List<Hero> movieList = new ArrayList<>();
    private RecyclerView recyclerView;
    private MoviesAdapter mAdapter;

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

        recyclerView=findViewById(R.id.recycler_view);
        mAdapter = new MoviesAdapter(movieList,MainActivity.this);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);
        //calling the method to display the heroes
        getHeroes();

    }


    private void getHeroes() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiInterface.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create()) //Here we are using the GsonConverterFactory to directly convert json data to object
                .build();

        ApiInterface api = retrofit.create(ApiInterface.class);

        Call<List<Hero>> call = api.getHeroes();

        call.enqueue(new Callback<List<Hero>>() {
            @Override
            public void onResponse(Call<List<Hero>> call, Response<List<Hero>> response) {
                List<Hero> heroList = response.body();

                //Creating an String array for the ListView
                String[] heroes = new String[heroList.size()];

                //looping through all the heroes and inserting the names inside the string array
                for (int i = 0; i < heroList.size(); i++) {
                    //heroes[i] = heroList.get(i).getName();
                    movieList.add(new Hero( heroList.get(i).getName(), heroList.get(i).getRealname(), heroList.get(i).getTeam()));
                }
                mAdapter.notifyDataSetChanged();

            }

            @Override
            public void onFailure(Call<List<Hero>> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

}
Hero.java
package com.example.owner.apipractice;
public class Hero {

    private String name;
    private String realname;
    private String team;

    public Hero(String name, String realname, String team) {
        this.name = name;
        this.realname = realname;
        this.team = team;
    }

    private String firstappearance;
    private String createdby;
    private String publisher;
    private String imageurl;
    private String bio;


    public Hero(String name, String realname, String team, String firstappearance, String createdby, String publisher, String imageurl, String bio) {
        this.name = name;
        this.realname = realname;
        this.team = team;
        this.firstappearance = firstappearance;
        this.createdby = createdby;
        this.publisher = publisher;
        this.imageurl = imageurl;
        this.bio = bio;
    }

    public String getName() {
        return name;
    }

    public String getRealname() {
        return realname;
    }

    public String getTeam() {
        return team;
    }

    public String getFirstappearance() {
        return firstappearance;
    }

    public String getCreatedby() {
        return createdby;
    }

    public String getPublisher() {
        return publisher;
    }

    public String getImageurl() {
        return imageurl;
    }

    public String getBio() {
        return bio;
    }
}

How can I use an array of function pointers?

Can use it in the way like this:

//! Define:
#define F_NUM 3
int (*pFunctions[F_NUM])(void * arg);

//! Initialise:
int someFunction(void * arg) {
    int a= *((int*)arg);
    return a*a;
}

pFunctions[0]= someFunction;

//! Use:
int someMethod(int idx, void * arg, int * result) {
    int done= 0;
    if (idx < F_NUM && pFunctions[idx] != NULL) {
        *result= pFunctions[idx](arg);
        done= 1;
    }
    return done;
}

int x= 2;
int z= 0;
someMethod(0, (void*)&x, &z);
assert(z == 4);

Setting java locale settings

On linux, create file in /etc/default/locale with the following contents

LANG=en.utf8

and then use the source command to export this variable by running

source /etc/default/locale

The source command sets the variable permanently.

Netbeans 8.0.2 The module has not been deployed

Maybe because you may need to create Db Resource and Pool manually on the Glassfish server like this,

In Netbeans -> Projects, Open Server Resources -> glassfish-resources.xml We have to create JDBC Resource and JDBC Connection Pool Manually on Glassfish. I am using my values here, don't use them, see your .xml !

Value of jndi-name is your JDBC Resource and Value of pool-name is your JDBC Connection Pool.

Open Browser for Glassfish Admin, https://localhost:4848/

Go to, JDBC Connection Pool -> New: 1) Pool Name: mysql_customersdb_rootPool 2) Resource Type: javax.sql.ConnectionPoolDataSource 3) Database Driver Vendor: MySql

Press Next,

URL: jdbc:mysql://localhost:3306/customersdb?zeroDateTimeBehavior=convertToNull Url: jdbc:mysql://localhost:3306/customersdb?zeroDateTimeBehavior=convertToNull User: root Password: root

JDBC Resources -> New

JNDI Name: CustomersDS Pool Name: mysql_customersdb_rootPool

Press Ok.

Right Click your Project and Press Run :)

How to keep a git branch in sync with master

The accepted answer via git merge will get the job done but leaves a messy commit hisotry, correct way should be 'rebase' via the following steps(assuming you want to keep your feature branch in sycn with develop before you do the final push before PR).

1 git fetch from your feature branch (make sure the feature branch you are working on is update to date)

2 git rebase origin/develop

3 if any conflict shall arise, resolve them one by one

4 use git rebase --continue once all conflicts are dealt with

5 git push --force

Why can't I use background image and color together?

background:url(directoryName/imageName.extention) bottom left no-repeat; 
background-color: red;

How can I combine two HashMap objects containing the same types?

You could use Collection.addAll() for other types, e.g. List, Set, etc. For Map, you can use putAll.

Cannot execute script: Insufficient memory to continue the execution of the program

You can also simply increase the Minimum memory per query value in server properties. To edit this setting, right click on server name and select Properties > Memory tab.

I encountered this error trying to execute a 30MB SQL script in SSMS 2012. After increasing the value from 1024MB to 2048MB I was able to run the script.

(This is the same answer I provided here)

Purge Kafka Topic

Thomas' advice is great but unfortunately zkCli in old versions of Zookeeper (for example 3.3.6) do not seem to support rmr. For example compare the command line implementation in modern Zookeeper with version 3.3.

If you are faced with an old version of Zookeeper one solution is to use a client library such as zc.zk for Python. For people not familiar with Python you need to install it using pip or easy_install. Then start a Python shell (python) and you can do:

import zc.zk
zk = zc.zk.ZooKeeper('localhost:2181')
zk.delete_recursive('brokers/MyTopic') 

or even

zk.delete_recursive('brokers')

if you want to remove all the topics from Kafka.

How do I translate an ISO 8601 datetime string into a Python datetime object?

Here is a super simple way to do these kind of conversions. No parsing, or extra libraries required. It is clean, simple, and fast.

import datetime
import time

################################################
#
# Takes the time (in seconds),
#   and returns a string of the time in ISO8601 format.
# Note: Timezone is UTC
#
################################################

def TimeToISO8601(seconds):
   strKv = datetime.datetime.fromtimestamp(seconds).strftime('%Y-%m-%d')
   strKv = strKv + "T"
   strKv = strKv + datetime.datetime.fromtimestamp(seconds).strftime('%H:%M:%S')
   strKv = strKv +"Z"
   return strKv

################################################
#
# Takes a string of the time in ISO8601 format,
#   and returns the time (in seconds).
# Note: Timezone is UTC
#
################################################

def ISO8601ToTime(strISOTime):
   K1 = 0
   K2 = 9999999999
   K3 = 0
   counter = 0
   while counter < 95:
     K3 = (K1 + K2) / 2
     strK4 = TimeToISO8601(K3)
     if strK4 < strISOTime:
       K1 = K3
     if strK4 > strISOTime:
       K2 = K3
     counter = counter + 1
   return K3

################################################
#
# Takes a string of the time in ISO8601 (UTC) format,
#   and returns a python DateTime object.
# Note: returned value is your local time zone.
#
################################################

def ISO8601ToDateTime(strISOTime):
   return time.gmtime(ISO8601ToTime(strISOTime))


#To test:
Test = "2014-09-27T12:05:06.9876"
print ("The test value is: " + Test)
Ans = ISO8601ToTime(Test)
print ("The answer in seconds is: " + str(Ans))
print ("And a Python datetime object is: " + str(ISO8601ToDateTime(Test)))

Run a string as a command within a Bash script

You can use eval to execute a string:

eval $illcommando

No newline after div?

Have you considered using span instead of div? It is the in-line version of div.

Docker build gives "unable to prepare context: context must be a directory: /Users/tempUser/git/docker/Dockerfile"

One of the reasons for me getting an error was the file name make sure the file name is Dockerfile So i figured it out, hope it might help someone.

How do I set Java's min and max heap size through environment variables?

You can't do it using environment variables directly. You need to use the set of "non standard" options that are passed to the java command. Run: java -X for details. The options you're looking for are -Xmx and -Xms (this is "initial" heap size, so probably what you're looking for.)

Some products like Ant or Tomcat might come with a batch script that looks for the JAVA_OPTS environment variable, but it's not part of the Java runtime. If you are using one of those products, you may be able to set the variable like:

set JAVA_OPTS="-Xms128m -Xmx256m"  

You can also take this approach with your own command line like:

set JAVA_OPTS="-Xms128m -Xmx256m"  
java ${JAVA_OPTS} MyClass

AngularJS check if form is valid in controller

Here is another solution

Set a hidden scope variable in your html then you can use it from your controller:

<span style="display:none" >{{ formValid = myForm.$valid}}</span>

Here is the full working example:

_x000D_
_x000D_
angular.module('App', [])_x000D_
.controller('myController', function($scope) {_x000D_
  $scope.userType = 'guest';_x000D_
  $scope.formValid = false;_x000D_
  console.info('Ctrl init, no form.');_x000D_
  _x000D_
  $scope.$watch('myForm', function() {_x000D_
    console.info('myForm watch');_x000D_
    console.log($scope.formValid);_x000D_
  });_x000D_
  _x000D_
  $scope.isFormValid = function() {_x000D_
    //test the new scope variable_x000D_
    console.log('form valid?: ', $scope.formValid);_x000D_
  };_x000D_
});
_x000D_
<!doctype html>_x000D_
<html ng-app="App">_x000D_
<head>_x000D_
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<form name="myForm" ng-controller="myController">_x000D_
  userType: <input name="input" ng-model="userType" required>_x000D_
  <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>_x000D_
  <tt>userType = {{userType}}</tt><br>_x000D_
  <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>_x000D_
  <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>_x000D_
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br>_x000D_
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>_x000D_
  _x000D_
  _x000D_
  /*-- Hidden Variable formValid to use in your controller --*/_x000D_
  <span style="display:none" >{{ formValid = myForm.$valid}}</span>_x000D_
  _x000D_
  _x000D_
  <br/>_x000D_
  <button ng-click="isFormValid()">Check Valid</button>_x000D_
 </form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

What are the correct version numbers for C#?

The biggest problem when dealing with C#'s version numbers is the fact that it is not tied to a version of the .NET Framework, which it appears to be due to the synchronized releases between Visual Studio and the .NET Framework.

The version of C# is actually bound to the compiler, not the framework. For instance, in Visual Studio 2008 you can write C# 3.0 and target .NET Framework 2.0, 3.0 and 3.5. The C# 3.0 nomenclature describes the version of the code syntax and supported features in the same way that ANSI C89, C90, C99 describe the code syntax/features for C.

Take a look at Mono, and you will see that Mono 2.0 (mostly implemented version 2.0 of the .NET Framework from the ECMA specifications) supports the C# 3.0 syntax and features.

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

This question and answer helped me solve a specific problem with signing up new users in Parse.

Because the signUp( attrs, options ) function uses local storage to persist the session, if a user is in private browsing mode it throws the "QuotaExceededError: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota." exception and the success/error functions are never called.

In my case, because the error function is never called it initially appeared to be an issue with firing the click event on the submit or the redirect defined on success of sign up.

Including a warning for users resolved the issue.

Parse Javascript SDK Reference https://parse.com/docs/js/api/classes/Parse.User.html#methods_signUp

Signs up a new user with a username (or email) and password. This will create a new Parse.User on the server, and also persist the session in localStorage so that you can access the user using {@link #current}.

When should you use constexpr capability in C++11?

Introduction

constexpr was not introduced as a way to tell the implementation that something can be evaluated in a context which requires a constant-expression; conforming implementations has been able to prove this prior to C++11.

Something an implementation cannot prove is the intent of a certain piece of code:

  • What is it that the developer want to express with this entity?
  • Should we blindly allow code to be used in a constant-expression, just because it happens to work?

What would the world be without constexpr?

Let's say you are developing a library and realize that you want to be able to calculate the sum of every integer in the interval (0,N].

int f (int n) {
  return n > 0 ? n + f (n-1) : n;
}

The lack of intent

A compiler can easily prove that the above function is callable in a constant-expression if the argument passed is known during translation; but you have not declared this as an intent - it just happened to be the case.

Now someone else comes along, reads your function, does the same analysis as the compiler; "Oh, this function is usable in a constant-expression!", and writes the following piece of code.

T arr[f(10)]; // freakin' magic

The optimization

You, as an "awesome" library developer, decide that f should cache the result when being invoked; who would want to calculate the same set of values over and over?

int func (int n) { 
  static std::map<int, int> _cached;

  if (_cached.find (n) == _cached.end ()) 
    _cached[n] = n > 0 ? n + func (n-1) : n;

  return _cached[n];
}

The result

By introducing your silly optimization, you just broke every usage of your function that happened to be in a context where a constant-expression was required.

You never promised that the function was usable in a constant-expression, and without constexpr there would be no way of providing such promise.


So, why do we need constexpr?

The primary usage of constexpr is to declare intent.

If an entity isn't marked as constexpr - it was never intended to be used in a constant-expression; and even if it is, we rely on the compiler to diagnose such context (because it disregards our intent).

Android difference between Two Dates

DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, Locale);
DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, Locale);
Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()

it returns how many days between given two dates, where DateTime is from joda library

Running a cron job at 2:30 AM everyday

  1. To edit:

    crontab -e
    
  2. Add this command line:

    30 2 * * * /your/command
    
    • Crontab Format:

      MIN HOUR DOM MON DOW CMD

    • Format Meanings and Allowed Value:
    • MIN Minute field 0 to 59
    • HOUR Hour field 0 to 23
    • DOM Day of Month 1-31
    • MON Month field 1-12
    • DOW Day Of Week 0-6
    • CMD Command Any command to be executed.
  3. Restart cron with latest data:

    service crond restart
    

how do I use an enum value on a switch statement in C++

i had a similar issue using enum with switch cases later i resolved it on my own....below is the corrected code, perhaps this might help.

     //Menu Chooser Programe using enum
     #include<iostream>
     using namespace std;
     int main()
     {
        enum level{Novice=1, Easy, Medium, Hard};
        level diffLevel=Novice;
        int i;
        cout<<"\nenter a level: ";
        cin>>i;
        switch(i)
        {
        case Novice: cout<<"\nyou picked Novice\n"; break;
        case Easy: cout<<"\nyou picked Easy\n"; break;
        case Medium: cout<<"\nyou picked Medium\n"; break;
        case Hard: cout<<"\nyou picked Hard\n"; break;
        default: cout<<"\nwrong input!!!\n"; break;
        }
        return 0;
     }

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

In a bug I was investigating there was a Response.Redirect() and it was executing in an unexpected location (read: inappropriate location - inside a member property getter method).

If you're debugging a problem and experience the "Unable to evaluate expression..." exception:

  1. Perform a search for Response.Redirect() and either make the second parameter endResponse = false, or
  2. Temporarily disable the redirect call.

This was frustrating as it would appear to execute the Redirect call before the "step through" on the debugger had reached that location.

Differences between cookies and sessions?

A lot contributions on this thread already, just summarize a sequence diagram to illustrate it in another way.

enter image description here

The is also a good link about this topic, https://web.stanford.edu/~ouster/cgi-bin/cs142-fall10/lecture.php?topic=cookie

Connect to external server by using phpMyAdmin

at version 4.0 or above, we need to create one 'config.inc.php' or rename the 'config.sample.inc.php' to 'config.inc.php';

In my case, I also work with one mysql server for each environment (dev and production):

/* others code*/  
$whoIam = gethostname();
switch($whoIam) {
    case 'devHost':
        $cfg['Servers'][$i]['host'] = 'localhost';
        break;
    case 'MasterServer':
        $cfg['Servers'][$i]['host'] = 'masterMysqlServer';
        break;
} /* others code*/ 

"Cannot instantiate the type..."

I had the very same issue, not being able to instantiate the type of a class which I was absolutely sure was not abstract. Turns out I was implementing an abstract class from Java.util instead of implementing my own class.

So if the previous answers did not help you, please check that you import the class you actually wanted to import, and not something else with the same name that you IDE might have hinted you.

For example, if you were trying to instantiate the class Queue from the package myCollections which you coded yourself :

import java.util.*; // replace this line
import myCollections.Queue; // by this line

     Queue<Edge> theQueue = new Queue<Edge>();

How to protect Excel workbook using VBA?

To lock whole workbook from opening, Thisworkbook.password option can be used in VBA.

If you want to Protect Worksheets, then you have to first Lock the cells with option Thisworkbook.sheets.cells.locked = True and then use the option Thisworkbook.sheets.protect password:="pwd".

Primarily search for these keywords: Thisworkbook.password or Thisworkbook.Sheets.Cells.Locked

PostgreSQL JOIN data from 3 tables

Something like:

select t1.name, t2.image_id, t3.path
from table1 t1 inner join table2 t2 on t1.person_id = t2.person_id
inner join table3 t3 on t2.image_id=t3.image_id

How to get Bitmap from an Uri?

try
{
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(c.getContentResolver() , Uri.parse(paths));
}
catch (Exception e) 
{
    //handle exception
}

and yes path must be in a format of like this

file:///mnt/sdcard/filename.jpg

How to see the CREATE VIEW code for a view in PostgreSQL?

Kept having to return here to look up pg_get_viewdef (how to remember that!!), so searched for a more memorable command... and got it:

\d+ viewname

You can see similar sorts of commands by typing \? at the pgsql command line.

Bonus tip: The emacs command sql-postgres makes pgsql a lot more pleasant (edit, copy, paste, command history).

"Cannot start compilation: the output path is not specified for module..."

Bugs caused by missing predefined folder for store compiled class file which is normally is /out folder by default. You can give a try to close Intellij > Import Project > From existing source. This will solve this problem.

How to open a web page automatically in full screen mode

You can go fullscreen automatically by putting this code in:

var elem = document.documentElement; if (elem.requestFullscreen) { elem.requestFullscreen() }

demo: https://codepen.io/ConfidentCoding/pen/ewLyPX

note: does not always work for security reasons. but it works for me at least. does not work when inspecting and pasting the code.

Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

Make sure you started the server:

mysql.server start

Then connect with root user:

mysql -uroot

How do you write a migration to rename an ActiveRecord model and its table in Rails?

You also need to replace your indexes:

class RenameOldTableToNewTable< ActiveRecord:Migration
  def self.up
    remove_index :old_table_name, :column_name
    rename_table :old_table_name, :new_table_name
    add_index :new_table_name, :column_name
  end 

  def self.down
    remove_index :new_table_name, :column_name
    rename_table :new_table_name, :old_table_name
    add_index :old_table_name, :column_name
  end
end

And rename your files etc, manually as other answers here describe.

See: http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

Make sure you can rollback and roll forward after you write this migration. It can get tricky if you get something wrong and get stuck with a migration that tries to effect something that no longer exists. Best trash the whole database and start again if you can't roll back. So be aware you might need to back something up.

Also: check schema_db for any relevant column names in other tables defined by a has_ or belongs_to or something. You'll probably need to edit those too.

And finally, doing this without a regression test suite would be nuts.

Can you force a React component to rerender without calling setState?

forceUpdate(), but every time I've ever heard someone talk about it, it's been followed up with you should never use this.

Regex for checking if a string is strictly alphanumeric

It's 2016 or later and things have progressed. This matches Unicode alphanumeric strings:

^[\\p{IsAlphabetic}\\p{IsDigit}]+$

See the reference (section "Classes for Unicode scripts, blocks, categories and binary properties"). There's also this answer that I found helpful.

What is the difference between Task.Run() and Task.Factory.StartNew()

See this blog article that describes the difference. Basically doing:

Task.Run(A)

Is the same as doing:

Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);   

List<Object> and List<?>

To answer your second question, yes, you can cast the List<?> as a List<Object> or a List<T> of any type, since the ? (Wildcard) parameter indicates that the list contains a homogenous collection of an any Object. However, there's no way to know at compile what the type is since it's part of the exported API only - meaning you can't see what's being inserted into the List<?>.

Here's how you would make the cast:

List<?> wildcardList = methodThatReturnsWildcardList();
// generates Unchecked cast compiler warning
List<Object> objectReference = (List<Object>)wildcardList;

In this case you can ignore the warning because in order for an object to be used in a generic class it must be a subtype of Object. Let's pretend that we're trying to cast this as a List<Integer> when it actually contains a collection of Strings.

// this code will compile safely
List<?> wildcardList = methodThatReturnsWildcardList();
List<Integer> integerReference = (List<Integer>)wildcardList;

// this line will throw an invalid cast exception for any type other than Integer
Integer myInteger = integerRefence.get(0);

Remember: generic types are erased at runtime. You won't know what the collection contains, but you can get an element and call .getClass() on it to determine its type.

Class objectClass = wildcardList.get(0).getClass();

Resize jqGrid when browser is resized?

autowidth: true

worked perfectly for me. learnt from here.

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

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

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

Changing default encoding of Python?

First: reload(sys) and setting some random default encoding just regarding the need of an output terminal stream is bad practice. reload often changes things in sys which have been put in place depending on the environment - e.g. sys.stdin/stdout streams, sys.excepthook, etc.

Solving the encode problem on stdout

The best solution I know for solving the encode problem of print'ing unicode strings and beyond-ascii str's (e.g. from literals) on sys.stdout is: to take care of a sys.stdout (file-like object) which is capable and optionally tolerant regarding the needs:

  • When sys.stdout.encoding is None for some reason, or non-existing, or erroneously false or "less" than what the stdout terminal or stream really is capable of, then try to provide a correct .encoding attribute. At last by replacing sys.stdout & sys.stderr by a translating file-like object.

  • When the terminal / stream still cannot encode all occurring unicode chars, and when you don't want to break print's just because of that, you can introduce an encode-with-replace behavior in the translating file-like object.

Here an example:

#!/usr/bin/env python
# encoding: utf-8
import sys

class SmartStdout:
    def __init__(self, encoding=None, org_stdout=None):
        if org_stdout is None:
            org_stdout = getattr(sys.stdout, 'org_stdout', sys.stdout)
        self.org_stdout = org_stdout
        self.encoding = encoding or \
                        getattr(org_stdout, 'encoding', None) or 'utf-8'
    def write(self, s):
        self.org_stdout.write(s.encode(self.encoding, 'backslashreplace'))
    def __getattr__(self, name):
        return getattr(self.org_stdout, name)

if __name__ == '__main__':
    if sys.stdout.isatty():
        sys.stdout = sys.stderr = SmartStdout()

    us = u'aouäöü?zß²'
    print us
    sys.stdout.flush()

Using beyond-ascii plain string literals in Python 2 / 2 + 3 code

The only good reason to change the global default encoding (to UTF-8 only) I think is regarding an application source code decision - and not because of I/O stream encodings issues: For writing beyond-ascii string literals into code without being forced to always use u'string' style unicode escaping. This can be done rather consistently (despite what anonbadger's article says) by taking care of a Python 2 or Python 2 + 3 source code basis which uses ascii or UTF-8 plain string literals consistently - as far as those strings potentially undergo silent unicode conversion and move between modules or potentially go to stdout. For that, prefer "# encoding: utf-8" or ascii (no declaration). Change or drop libraries which still rely in a very dumb way fatally on ascii default encoding errors beyond chr #127 (which is rare today).

And do like this at application start (and/or via sitecustomize.py) in addition to the SmartStdout scheme above - without using reload(sys):

...
def set_defaultencoding_globally(encoding='utf-8'):
    assert sys.getdefaultencoding() in ('ascii', 'mbcs', encoding)
    import imp
    _sys_org = imp.load_dynamic('_sys_org', 'sys')
    _sys_org.setdefaultencoding(encoding)

if __name__ == '__main__':
    sys.stdout = sys.stderr = SmartStdout()
    set_defaultencoding_globally('utf-8') 
    s = 'aouäöü?zß²'
    print s

This way string literals and most operations (except character iteration) work comfortable without thinking about unicode conversion as if there would be Python3 only. File I/O of course always need special care regarding encodings - as it is in Python3.

Note: plains strings then are implicitely converted from utf-8 to unicode in SmartStdout before being converted to the output stream enconding.

How do I remove background-image in css?

If your div rule is just div {...}, then #a {...} will be sufficient. If it is more complicated, you need a "more specific" selector, as defined by the CSS specification on specificity. (#a being more specific than div is just single aspect in the algorithm.)

What is a plain English explanation of "Big O" notation?

Big O in plain english is like <= (less than or equal). When we say for two functions f and g, f = O(g) it means that f <= g.

However, this does not mean that for any n f(n) <= g(n). Actually what it means is that f is less than or equal g in terms of growth. It means that after a point f(n) <= c*g(n) if c is a constant. And after a point means than for all n >= n0 where n0 is another constant.

How to call a method with a separate thread in Java?

Thread t1 = new Thread(new Runnable() {
    @Override
    public void run() {
        // code goes here.
    }
});  
t1.start();

or

new Thread(new Runnable() {
     @Override
     public void run() {
          // code goes here.
     }
}).start();

or

new Thread(() -> {
    // code goes here.
}).start();

or

Executors.newSingleThreadExecutor().execute(new Runnable() {
    @Override
    public void run() {
        myCustomMethod();
    }
});

or

Executors.newCachedThreadPool().execute(new Runnable() {
    @Override
    public void run() {
        myCustomMethod();
    }
});

System.drawing namespace not found under console application

  1. Add using System.Drawing;
  2. Go to solution explorer and right click on references and select add reference
  3. Click on assemblies on the left
  4. search for system.drawing
  5. check system.drawing
  6. Click OK
  7. Done

How to communicate between iframe and the parent site?

It must be here, because accepted answer from 2012

In 2018 and modern browsers you can send a custom event from iframe to parent window.

iframe:

var data = { foo: 'bar' }
var event = new CustomEvent('myCustomEvent', { detail: data })
window.parent.document.dispatchEvent(event)

parent:

window.document.addEventListener('myCustomEvent', handleEvent, false)
function handleEvent(e) {
  console.log(e.detail) // outputs: {foo: 'bar'}
}

PS: Of course, you can send events in opposite direction same way.

document.querySelector('#iframe_id').contentDocument.dispatchEvent(event)

How can I show a message box with two buttons?

You probably want to do something like this:

result = MsgBox ("Yes or No?", vbYesNo, "Yes No Example")

Select Case result
Case vbYes
    MsgBox("You chose Yes")
Case vbNo
    MsgBox("You chose No")
End Select

To add an icon:

result = MsgBox ("Yes or No?", vbYesNo + vbQuestion, "Yes No Example")

Other icon options:

vbCritical or vbExclamation

How to get sp_executesql result into a variable?

Return values are generally not used to "return" a result but to return success (0) or an error number (1-65K). The above all seem to indicate that sp_executesql does not return a value, which is not correct. sp_executesql will return 0 for success and any other number for failure.

In the below, @i will return 2727

DECLARE @s NVARCHAR(500)
DECLARE @i INT;
SET @s = 'USE [Blah]; UPDATE STATISTICS [dbo].[TableName] [NonExistantStatisticsName];';
EXEC @i = sys.sp_executesql @s
SELECT @i AS 'Blah'

SSMS will show this Msg 2727, Level 11, State 1, Line 1 Cannot find index 'NonExistantStaticsName'.

Sharing link on WhatsApp from mobile website (not application) for Android

The official docs say to use: wa.me. Don't use wa.me. I apologize for the length of these results, but it's been a rapidly-evolving issue....

April, 2020 Results

Share Link

This link is incorrect. Close this window and try a different link.

May, 2020 Results

Share Link GitHub Ticket: WhatsApp short link without phone number not working anymore

We couldn't find the page you were looking for

Looks like you're looking for a page that doesn't exist. Or a page we might have just deleted. Either way, go back or be sure to check the url, your spelling and try again.

August, 2020 Results

Share Link

Works as expected!

LATEST - October, 2020 Results

Share Link

(Broken again!) og:image tag previews are disabled when using wa.me.

Based on some of the comments I'm seeing, it seems like this still be an intermittent problem, so, going forward, I recommend you stick to the api.whatsapp.com URL!

If you want to share, you must absolutely use one of the two following URL formats:

https://api.whatsapp.com/send?text=YourShareTextHere
https://api.whatsapp.com/send?text=YourShareTextHere&phone=123

If you are interested in watching a project that keeps track of these URLs, then check us out!: https://github.com/bradvin/social-share-urls#telegramme

Social Share URLs

Where can I find the default timeout settings for all browsers?

After the last Firefox update we had the same session timeout issue and the following setting helped to resolve it.

We can control it with network.http.response.timeout parameter.

  1. Open Firefox and type in ‘about:config’ in the address bar and press Enter.
  2. Click on the "I'll be careful, I promise!" button.
  3. Type ‘timeout’ in the search box and network.http.response.timeout parameter will be displayed.
  4. Double-click on the network.http.response.timeout parameter and enter the time value (it is in seconds) that you don't want your session not to timeout, in the box.

Renaming the current file in Vim

How about this (improved by Jake's suggestion):

:exe "!mv % newfilename" | e newfilename

NuGet auto package restore does not work with MSBuild

Ian Kemp has the answer (have some points btw..), this is to simply add some meat to one of his steps.

The reason I ended up here was that dev's machines were building fine, but the build server simply wasn't pulling down the packages required (empty packages folder) and therefore the build was failing. Logging onto the build server and manually building the solution worked, however.

To fulfil the second of Ians 3 point steps (running nuget restore), you can create an MSBuild target running the exec command to run the nuget restore command, as below (in this case nuget.exe is in the .nuget folder, rather than on the path), which can then be run in a TeamCity build step (other CI available...) immediately prior to building the solution

<Target Name="BeforeBuild">
  <Exec Command="..\.nuget\nuget restore ..\MySolution.sln"/>
</Target>

For the record I'd already tried the "nuget installer" runner type but this step was hanging on web projects (worked for DLL's and Windows projects)

How do I send a file as an email attachment using Linux command line?

Just to add my 2 cents, I'd write my own PHP Script:

http://php.net/manual/en/function.mail.php

There are lots of ways to do the attachment in the examples on that page.

How to convert a list of numbers to jsonarray in Python

import json
row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
row_json = json.dumps(row)

Initializing entire 2D array with one value

You get this behavior, because int array [ROW][COLUMN] = {1}; does not mean "set all items to one". Let me try to explain how this works step by step.

The explicit, overly clear way of initializing your array would be like this:

#define ROW 2
#define COLUMN 2

int array [ROW][COLUMN] =
{
  {0, 0},
  {0, 0}
};

However, C allows you to leave out some of the items in an array (or struct/union). You could for example write:

int array [ROW][COLUMN] =
{
  {1, 2}
};

This means, initialize the first elements to 1 and 2, and the rest of the elements "as if they had static storage duration". There is a rule in C saying that all objects of static storage duration, that are not explicitly initialized by the programmer, must be set to zero.

So in the above example, the first row gets set to 1,2 and the next to 0,0 since we didn't give them any explicit values.

Next, there is a rule in C allowing lax brace style. The first example could as well be written as

int array [ROW][COLUMN] = {0, 0, 0, 0};

although of course this is poor style, it is harder to read and understand. But this rule is convenient, because it allows us to write

int array [ROW][COLUMN] = {0};

which means: "initialize the very first column in the first row to 0, and all other items as if they had static storage duration, ie set them to zero."

therefore, if you attempt

int array [ROW][COLUMN] = {1};

it means "initialize the very first column in the first row to 1 and set all other items to zero".

How to browse localhost on Android device?

If your firewall is on, turn it off and use IPv4 to test your app in the actual device, then test your application.

Where does the slf4j log file get saved?

The log file is not visible because the slf4j configuration file location needs to passed to the java run command using the following arguments .(e.g.)

-Dlogging.config={file_location}\log4j2.xml 

or this:

-Dlog4j.configurationFile={file_location}\log4j2.xml

Finding elements not in a list

>> items = [1,2,3,4]
>> Z = [3,4,5,6]

>> print list(set(items)-set(Z))
[1, 2]

How to explicitly obtain post data in Spring MVC?

You can simply just pass the attribute you want without any annotations in your controller:

@RequestMapping(value = "/someUrl")
public String someMethod(String valueOne) {
 //do stuff with valueOne variable here
}

Works with GET and POST

Cross-Origin Read Blocking (CORB)

Return response with header 'Access-Control-Allow-Origin:*' Check below code for the Php server response.

<?php header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
echo json_encode($phparray); 

How do I copy a version of a single file from one git branch to another?

Please note that in the accepted answer, the first option stages the entire file from the other branch (like git add ... had been performed), and that the second option just results in copying the file, but doesn't stage the changes (as if you had just edited the file manually and had outstanding differences).

Git copy file from another branch without staging it

Changes staged (e.g. git add filename):

$ git checkout directory/somefile.php feature-B

$ git status
On branch feature-A
Your branch is up-to-date with 'origin/feature-A'.
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   directory/somefile.php

Changes outstanding (not staged or committed):

$ git show feature-B:directory/somefile.php > directory/somefile.php

$ git status
On branch feature-A
Your branch is up-to-date with 'origin/feature-A'.
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   directory/somefile.php

no changes added to commit (use "git add" and/or "git commit -a")

get basic SQL Server table structure information

sp_help will give you a whole bunch of information about a table including the columns, keys and constraints. For example, running

exec sp_help 'Address' 

will give you information about Address.

How do I get the result of a command in a variable in windows?

you need to use the SET command with parameter /P and direct your output to it. For example see http://www.ss64.com/nt/set.html. Will work for CMD, not sure about .BAT files

From a comment to this post:

That link has the command "Set /P _MyVar=<MyFilename.txt" which says it will set _MyVar to the first line from MyFilename.txt. This could be used as "myCmd > tmp.txt" with "set /P myVar=<tmp.txt". But it will only get the first line of the output, not all the output

Why can't I make a vector of references?

The component type of containers like vectors must be assignable. References are not assignable (you can only initialize them once when they are declared, and you cannot make them reference something else later). Other non-assignable types are also not allowed as components of containers, e.g. vector<const int> is not allowed.

PowerShell: Run command from script's directory

I made a one-liner out of @JohnL's solution:

$MyInvocation.MyCommand.Path | Split-Path | Push-Location

Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

I faced the same issue although i added [System.Web.Mvc.AllowHtml] to the concerning property as described in some answers.

In my case, i have an UnhandledExceptionFilter class that accesses the Request object before MVC validation takes place (and therefore AllowHtml has not effect) and this access raises a [HttpRequestValidationException] A potentially dangerous Request.Form value was detected from the client.

This means, accessing certain properties of a Request object implicitly fires validation (in my case its the Params property).

A solution to prevent validation is documented on MSDN

To disable request validation for a specific field in a request (for example, for an input element or query string value), call the Request.Unvalidated method when you get the item, as shown in the following example

Therefore, if you have code like this

var lParams = aRequestContext.HttpContext.Request.Params;
if (lParams.Count > 0)
{
  ...

change it to

var lUnvalidatedRequest = aRequestContext.HttpContext.Request.Unvalidated;

var lForm = lUnvalidatedRequest.Form;
if (lForm.Count > 0)
{
  ...

or just use the Form property which does not seem to fire validation

var lForm = aRequestContext.HttpContext.Request.Form;
if (lForm.Count > 0)
{
  ...

Equivalent of *Nix 'which' command in PowerShell?

The very first alias I made once I started customizing my profile in PowerShell was 'which'.

New-Alias which get-command

To add this to your profile, type this:

"`nNew-Alias which get-command" | add-content $profile

The `n at the start of the last line is to ensure it will start as a new line.

Transitions on the CSS display property

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

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

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

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

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

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

How to programmatically set the SSLContext of a JAX-WS client?

This one was a hard nut to crack, so for the record:

To solve this, it required a custom KeyManager and a SSLSocketFactory that uses this custom KeyManager to access the separated KeyStore. I found the base code for this KeyStore and SSLFactory on this excellent blog entry: how-to-dynamically-select-a-certificate-alias-when-invoking-web-services

Then, the specialized SSLSocketFactory needs to be inserted into the WebService context:

service = getWebServicePort(getWSDLLocation());
BindingProvider bindingProvider = (BindingProvider) service; 
bindingProvider.getRequestContext().put("com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory", getCustomSocketFactory()); 

Where the getCustomSocketFactory() returns a SSLSocketFactory created using the method mentioned above. This would only work for JAX-WS RI from the Sun-Oracle impl built into the JDK, given that the string indicating the SSLSocketFactory property is proprietary for this implementation.

At this stage, the JAX-WS service communication is secured through SSL, but if you are loading the WSDL from the same secure server () then you'll have a bootstrap problem, as the HTTPS request to gather the WSDL will not be using the same credentials than the Web Service. I worked around this problem by making the WSDL locally available (file:///...) and dynamically changing the web service endpoint: (a good discussion on why this is needed can be found in this forum)

bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, webServiceLocation); 

Now the WebService gets bootstrapped and is able to communicate through SSL with the server counterpart using a named (alias) Client-Certificate and mutual authentication. ?

How do I drop table variables in SQL-Server? Should I even do this?

Temp table variable is saved to the temp.db and the scope is limited to the current execution. Hence, unlike dropping a Temp tables e.g drop table #tempTable, we don't have to explicitly drop Temp table variable @tempTableVariable. It is automatically taken care by the sql server.

drop table @tempTableVariable -- Invalid

What to use now Google News API is deprecated?

Depending on your needs, you want to use their section feeds, their search feeds

http://news.google.com/news?q=apple&output=rss

or Bing News Search.

http://www.bing.com/toolbox/bingdeveloper/

Add object to ArrayList at specified index

If you are using the Android flavor of Java, might I suggest using a SparseArray. It's a more memory efficient mapping of integers to objects and easier to iterate over than a Map

CSS force image resize and keep aspect ratio

Fullscreen presentation:

img[data-attribute] {height: 100vh;}

Keep in mind that if the view-port height is greater than the image the image will naturally degrade relative to the difference.

Escape double quote in grep

The problem is that you aren't correctly escaping the input string, try:

echo "\"member\":\"time\"" | grep -e "member\""

Alternatively, you can use unescaped double quotes within single quotes:

echo '"member":"time"' | grep -e 'member"'

It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').

How to set up gradle and android studio to do release build?

No need to update gradle for making release application in Android studio.If you were eclipse user then it will be so easy for you. If you are new then follow the steps

1: Go to the "Build" at the toolbar section. 2: Choose "Generate Signed APK..." option. enter image description here

3:fill opened form and go next 4 :if you already have .keystore or .jks then choose that file enter your password and alias name and respective password. 5: Or don't have .keystore or .jks file then click on Create new... button as shown on pic 1 then fill the form.enter image description here

Above process was to make build manually. If You want android studio to automatically Signing Your App

In Android Studio, you can configure your project to sign your release APK automatically during the build process:

On the project browser, right click on your app and select Open Module Settings. On the Project Structure window, select your app's module under Modules. Click on the Signing tab. Select your keystore file, enter a name for this signing configuration (as you may create more than one), and enter the required information. enter image description here Figure 4. Create a signing configuration in Android Studio.

Click on the Build Types tab. Select the release build. Under Signing Config, select the signing configuration you just created. enter image description here Figure 5. Select a signing configuration in Android Studio.

4:Most Important thing that make debuggable=false at gradle.

    buildTypes {
        release {
           minifyEnabled false
          proguardFiles getDefaultProguardFile('proguard-  android.txt'), 'proguard-rules.txt'
        debuggable false
        jniDebuggable false
        renderscriptDebuggable false
        zipAlignEnabled true
       }
     }

visit for more in info developer.android.com

cannot find module "lodash"

If there is a package.json, and in it there is lodash configuration in it. then you should:

npm install

if in the package.json there is no lodash:

npm install --save-dev

Naming convention - underscore in C++ and C# variables

I use the _var naming for member variables of my classes. There are 2 main reasons I do:

1) It helps me keep track of class variables and local function variables when I'm reading my code later.

2) It helps in Intellisense (or other code-completion system) when I'm looking for a class variable. Just knowing the first character is helpful in filtering through the list of available variables and methods.

Same font except its weight seems different on different browsers

I collected and tested discussed solutions:

Windows10 Prof x64:

* FireFox v.56.0 x32 
* Opera v.49.0
* Google Chrome v.61.0.3163.100 x64-bit

macOs X Serra v.10.12.6 Mac mini (Mid 2010):

* Safari v.10.1.2(12603.3.8)
* FireFox v.57.0 Quantum
* Opera v49.0

Semi (still micro fat in Safari) solved fatty fonts:

text-transform: none; // mac ff fix
-webkit-font-smoothing: antialiased; // safari mac nicer
-moz-osx-font-smoothing: grayscale; // fix fatty ff on mac

Have no visual effect

line-height: 1;
text-rendering: optimizeLegibility; 
speak: none;
font-style: normal;
font-variant: normal;

Wrong visual effect:

-webkit-font-smoothing: subpixel-antialiased !important; //more fatty in safari
text-rendering: geometricPrecision !important; //more fatty in safari

do not forget to set !important when testing or be sure that your style is not overridden

Is not an enclosing class Java

In case if Parent class is singleton use following way:

Parent.Child childObject = (Parent.getInstance()).new Child();

where getInstance() will return parent class singleton object.

Copy entire contents of a directory to another using php

The best solution is!

<?php
$src = "/home/www/domain-name.com/source/folders/123456";
$dest = "/home/www/domain-name.com/test/123456";

shell_exec("cp -r $src $dest");

echo "<H3>Copy Paste completed!</H3>"; //output when done
?>

Get multiple elements by Id

You can't have duplicate ids. Ids are supposed to be unique. You might want to use a specialized class instead.

Bigger Glyphicons

If you are using bootstrap 3, use tag, like this <small><span class="glyphicon glyphicon-send"></span></small> It works perfect for Bootstrap 3.
You can even use multiple <small> tags to set the size more smaller.
Code:
<small><small><span class="glyphicon glyphicon-send"></span></small></small>

HTML5 input type range show range value

If you want your current value to be displayed beneath the slider and moving along with it, try this:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <title>MySliderValue</title>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
  <h1>MySliderValue</h1>_x000D_
_x000D_
  <div style="position:relative; margin:auto; width:90%">_x000D_
    <span style="position:absolute; color:red; border:1px solid blue; min-width:100px;">_x000D_
    <span id="myValue"></span>_x000D_
    </span>_x000D_
    <input type="range" id="myRange" max="1000" min="0" style="width:80%"> _x000D_
  </div>_x000D_
_x000D_
  <script type="text/javascript" charset="utf-8">_x000D_
var myRange = document.querySelector('#myRange');_x000D_
var myValue = document.querySelector('#myValue');_x000D_
var myUnits = 'myUnits';_x000D_
var off = myRange.offsetWidth / (parseInt(myRange.max) - parseInt(myRange.min));_x000D_
var px =  ((myRange.valueAsNumber - parseInt(myRange.min)) * off) - (myValue.offsetParent.offsetWidth / 2);_x000D_
_x000D_
  myValue.parentElement.style.left = px + 'px';_x000D_
  myValue.parentElement.style.top = myRange.offsetHeight + 'px';_x000D_
  myValue.innerHTML = myRange.value + ' ' + myUnits;_x000D_
_x000D_
  myRange.oninput =function(){_x000D_
    let px = ((myRange.valueAsNumber - parseInt(myRange.min)) * off) - (myValue.offsetWidth / 2);_x000D_
    myValue.innerHTML = myRange.value + ' ' + myUnits;_x000D_
    myValue.parentElement.style.left = px + 'px';_x000D_
  };_x000D_
  </script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Note that this type of HTML input element has one hidden feature, such as you can move the slider with left/right/down/up arrow keys when the element has focus on it. The same with Home/End/PageDown/PageUp keys.

creating batch script to unzip a file without additional zip tools

Try this:

@echo off
setlocal
cd /d %~dp0
Call :UnZipFile "C:\Temp\" "c:\path\to\batch.zip"
exit /b

:UnZipFile <ExtractTo> <newzipfile>
set vbs="%temp%\_.vbs"
if exist %vbs% del /f /q %vbs%
>%vbs%  echo Set fso = CreateObject("Scripting.FileSystemObject")
>>%vbs% echo If NOT fso.FolderExists(%1) Then
>>%vbs% echo fso.CreateFolder(%1)
>>%vbs% echo End If
>>%vbs% echo set objShell = CreateObject("Shell.Application")
>>%vbs% echo set FilesInZip=objShell.NameSpace(%2).items
>>%vbs% echo objShell.NameSpace(%1).CopyHere(FilesInZip)
>>%vbs% echo Set fso = Nothing
>>%vbs% echo Set objShell = Nothing
cscript //nologo %vbs%
if exist %vbs% del /f /q %vbs%

Revision

To have it perform the unzip on each zip file creating a folder for each use:

@echo off
setlocal
cd /d %~dp0
for %%a in (*.zip) do (
    Call :UnZipFile "C:\Temp\%%~na\" "c:\path\to\%%~nxa"
)
exit /b

If you don't want it to create a folder for each zip, change Call :UnZipFile "C:\Temp\%%~na\" "c:\path\to\%%~nxa" to Call :UnZipFile "C:\Temp\" "c:\path\to\%%~nxa"

React Native - Image Require Module using Dynamic Names

First, create a file with image required - React native images must be loaded this way.

assets/index.js

export const friendsandfoe = require('./friends-and-foe.png'); 
export const lifeanddeath = require('./life-and-death.png'); 
export const homeandgarden = require('./home-and-garden.png');

Now import all your assets

App.js

import * as All  from '../../assets';

You can now use your image as an interpolated value where imageValue (coming in from backend) is the same as named local file ie: 'homeandgarden':

<Image style={styles.image} source={All[`${imageValue}`]}></Image>

how to add values to an array of objects dynamically in javascript?

In Year 2019, we can use Javascript's ES6 Spread syntax to do it concisely and efficiently

data = [...data, {"label": 2, "value": 13}]

Examples

_x000D_
_x000D_
var data = [_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
    ];_x000D_
    _x000D_
data = [...data, {"label" : "2", "value" : 14}] _x000D_
console.log(data)
_x000D_
_x000D_
_x000D_

For your case (i know it was in 2011), we can do it with map() & forEach() like below

_x000D_
_x000D_
var lab = ["1","2","3","4"];_x000D_
var val = [42,55,51,22];_x000D_
_x000D_
//Using forEach()_x000D_
var data = [];_x000D_
val.forEach((v,i) => _x000D_
   data= [...data, {"label": lab[i], "value":v}]_x000D_
)_x000D_
_x000D_
//Using map()_x000D_
var dataMap = val.map((v,i) => _x000D_
 ({"label": lab[i], "value":v})_x000D_
)_x000D_
_x000D_
console.log('data: ', data);_x000D_
console.log('dataMap : ', dataMap);
_x000D_
_x000D_
_x000D_

CSS Background Opacity

I would do something like this

<div class="container">
  <div class="text">
    <p>text yay!</p>
  </div>
</div>

CSS:

.container {
    position: relative;
}

.container::before {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    background: url('/path/to/image.png');
    opacity: .4;
    content: "";
    z-index: -1;
}

It should work. This is assuming you are required to have a semi-transparent image BTW, and not a color (which you should just use rgba for). Also assumed is that you can't just alter the opacity of the image beforehand in Photoshop.

int *array = new int[n]; what is this function actually doing?

It allocates space on the heap equal to an integer array of size N, and returns a pointer to it, which is assigned to int* type pointer called "array"

How to linebreak an svg text within javascript?

I think this does what you want:

function ShowTooltip(evt, mouseovertext){
    // Make tooltip text        
    var tooltip_text = tt.childNodes.item(1);
    var words = mouseovertext.split("\\\n");
    var max_length = 0;

    for (var i=0; i<3; i++){
        tooltip_text.childNodes.item(i).firstChild.data = i<words.length ?  words[i] : " ";
        length = tooltip_text.childNodes.item(i).getComputedTextLength();
        if (length > max_length) {max_length = length;}
    }

    var x = evt.clientX + 14 + max_length/2;
    var y = evt.clientY + 29;
    tt.setAttributeNS(null,"transform", "translate(" + x + " " + y + ")")

    // Make tooltip background
    bg.setAttributeNS(null,"width", max_length+15);
    bg.setAttributeNS(null,"height", words.length*15+6);
    bg.setAttributeNS(null,"x",evt.clientX+8);
    bg.setAttributeNS(null,"y",evt.clientY+14);

    // Show everything
    tt.setAttributeNS(null,"visibility","visible");
    bg.setAttributeNS(null,"visibility","visible");
}

It splits the text on \\\n and for each puts each fragment in a tspan. Then it calculates the size of the box required based on the longest length of text and the number of lines. You will also need to change the tooltip text element to contain three tspans:

<g id="tooltip" visibility="hidden">
    <text><tspan>x</tspan><tspan x="0" dy="15">x</tspan><tspan x="0" dy="15">x</tspan></text>
</g>

This assumes that you never have more than three lines. If you want more than three lines you can add more tspans and increase the length of the for loop.

error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

Had an issue similar to this, Ended up using UTF-16 to decode. my code is below.

with open(path_to_file,'rb') as f:
    contents = f.read()
contents = contents.rstrip("\n").decode("utf-16")
contents = contents.split("\r\n")

this would take the file contents as an import, but it would return the code in UTF format. from there it would be decoded and seperated by lines.

Javascript Regex: How to put a variable inside a regular expression?

You can always give regular expression as string, i.e. "ReGeX" + testVar + "ReGeX". You'll possibly have to escape some characters inside your string (e.g., double quote), but for most cases it's equivalent.

You can also use RegExp constructor to pass flags in (see the docs).

Convert Newtonsoft.Json.Linq.JArray to a list of specific object type

Just call array.ToObject<List<SelectableEnumItem>>() method. It will return what you need.

Documentation: Convert JSON to a Type

WPF binding to Listbox selectedItem

since you set your itemsource to your collection, your textbox is tied to each individual item in that collection. the selected item property is useful in this scenario if you were trying to do a master-detail form, having 2 listboxes. you would bind the second listbox's itemsource to the child collection of rules. in otherwords the selected item alerts outside controls that your source has changed, internal controls(those inside your datatemplate already are aware of the change.

and to answer your question yes in most circumstances setting the itemsource is the same as setting the datacontext of the control.

comparing 2 strings alphabetically for sorting purposes

"a".localeCompare("b") should actually return -1 since a sorts before b

http://www.w3schools.com/jsref/jsref_localecompare.asp

ActiveModel::ForbiddenAttributesError when creating new user

For those using CanCanCan:

You will get this error if CanCanCan cannot find the correct params method.

For the :create action, CanCan will try to initialize a new instance with sanitized input by seeing if your controller will respond to the following methods (in order):

  1. create_params
  2. <model_name>_params such as article_params (this is the default convention in rails for naming your param method)
  3. resource_params (a generically named method you could specify in each controller)

Additionally, load_and_authorize_resource can now take a param_method option to specify a custom method in the controller to run to sanitize input.

You can associate the param_method option with a symbol corresponding to the name of a method that will get called:

class ArticlesController < ApplicationController
  load_and_authorize_resource param_method: :my_sanitizer

  def create
    if @article.save
      # hurray
    else
      render :new
    end
  end

  private

  def my_sanitizer
    params.require(:article).permit(:name)
  end
end

source: https://github.com/CanCanCommunity/cancancan#33-strong-parameters

Executing set of SQL queries using batch file?

Use the SQLCMD utility.

http://technet.microsoft.com/en-us/library/ms162773.aspx

There is a connect statement that allows you to swing from database server A to server B in the same batch.

:Connect server_name[\instance_name] [-l timeout] [-U user_name [-P password]] Connects to an instance of SQL Server. Also closes the current connection.

On the other hand, if you are familiar with PowerShell, you can programmatic do the same.

http://technet.microsoft.com/en-us/library/cc281954(v=sql.105).aspx

How do I concatenate a boolean to a string in Python?

answer = True
myvar = "the answer is " + str(answer)

or

myvar = "the answer is %s" % answer

How To Show And Hide Input Fields Based On Radio Button Selection

You can do with Very Simple Step

$(':radio[id=radio1]').change(function() {
   $("#yes").removeClass("none");
   $("#no").addClass("none");


});
$(':radio[id=radio2]').change(function() {
   $("#no").removeClass("none");
   $("#yes").addClass("none");

});

Adding asterisk to required fields in Bootstrap 3

This works for me:

CSS

.form-group.required.control-label:before{
   content: "*";
   color: red;
}

OR

.form-group.required.control-label:after{
   content: "*";
   color: red;
}

Basic HTML

<div class="form-group required control-label">
  <input class="form-control" />
</div>

getting file size in javascript

To get the file size of pages on the web I built a javascript bookmarklet to do the trick. It alerts the size in kb's. Change the alert to a prompt if you want to copy the filesize.

Here's the bookmarklet code for the alert.

<a href="javascript:a=document.getElementsByTagName('HTML')[0].outerHTML;b=a.length/1024;c=Math.round(b);alert(c+' kb');">Doc Size</a>

Here's the bookmarklet code for the prompt.

<a href="javascript:a=document.getElementsByTagName('HTML')[0].outerHTML;b=a.length/1024;c=Math.round(b);prompt('Page Size',c+' kb');">Doc Size</a>

See it in action at http://bookmarklets.to.g0.to/filesize.php

How to get the background color of an HTML element?

As with all css properties that contain hyphens, their corresponding names in JS is to remove the hyphen and make the following letter capital: backgroundColor

alert(myDiv.style.backgroundColor);

Jenkins / Hudson environment variables

Solution that worked for me

source ~/.bashrc

Explanation

I first verified Jenkins was running BASH, with echo $SHELL and echo $BASH (note I'm explicitly putting #!/bin/bash atop the textarea in Jenkins, I'm not sure if that's a requirement to get BASH). sourceing /etc/profile as others suggested was not working.

Looking at /etc/profile I found

if [ "$PS1" ]; then
...

and inspecting "$PS1" found it null. I tried spoofing $PS1 to no avail like so

export PS1=1
bash -c 'echo $PATH'

however this did not produce the desired result (add the rest of the $PATH I expect to see). But if I tell bash to be interactive

export PS1=1
bash -ci 'echo $PATH'

the $PATH was altered as I expected.

I was trying to figure out how to properly spoof an interactive shell to get /etc/bash.bashrc to load, however it turns out all I needed was down in ~/.bashrc, so simply sourceing it solved the problem.

How to get the category title in a post in Wordpress?

You can use

<?php the_category(', '); ?>

which would output them in a comma separated list.

You can also do the same for tags as well:

<?php the_tags('<em>:</em>', ', ', ''); ?>

SSRS Query execution failed for dataset

I had the similar issue showing the error

For more information about this error navigate to the report server on the local server machine, or enable remote errors Query execution failed for dataset 'PrintInvoice'.

Solution: 1) The error may be with the dataset in some cases, you can always check if the dataset is populating the exact data you are expecting by going to the dataset properties and choosing 'Query Designer' and try 'Run', If you can successfully able to pull the fields you are expecting, then you can be sure that there isn't any problem with the dataset, which takes us to next solution.

2) Even though the error message says "Query Failed Execution for the dataset", another probable chances are with the datasource connection, make sure you have connected to the correct datasource that has the tables you need and you have permissions to access that datasource.

Maximum Java heap size of a 32-bit JVM on a 64-bit OS

On Solaris the limit has been about 3.5 GB since Solaris 2.5. (about 10 years ago)

Google Maps V3 - How to calculate the zoom level for a given bounds

None of the highly upvoted answers worked for me. They threw various undefined errors and ended up calculating inf/nan for angles. I suspect perhaps the behavior of LatLngBounds has changed over time. In any case, I found this code to work for my needs, perhaps it can help someone:

function latRad(lat) {
  var sin = Math.sin(lat * Math.PI / 180);
  var radX2 = Math.log((1 + sin) / (1 - sin)) / 2;
  return Math.max(Math.min(radX2, Math.PI), -Math.PI) / 2;
}

function getZoom(lat_a, lng_a, lat_b, lng_b) {

      let latDif = Math.abs(latRad(lat_a) - latRad(lat_b))
      let lngDif = Math.abs(lng_a - lng_b)

      let latFrac = latDif / Math.PI 
      let lngFrac = lngDif / 360 

      let lngZoom = Math.log(1/latFrac) / Math.log(2)
      let latZoom = Math.log(1/lngFrac) / Math.log(2)

      return Math.min(lngZoom, latZoom)

}

Test if executable exists in Python?

For python 3.3 and later:

import shutil

command = 'ls'
shutil.which(command) is not None

As a one-liner of Jan-Philip Gehrcke Answer:

cmd_exists = lambda x: shutil.which(x) is not None

As a def:

def cmd_exists(cmd):
    return shutil.which(cmd) is not None

For python 3.2 and earlier:

my_command = 'ls'
any(
    (
        os.access(os.path.join(path, my_command), os.X_OK) 
        and os.path.isfile(os.path.join(path, my_command)
    )
    for path in os.environ["PATH"].split(os.pathsep)
)

This is a one-liner of Jay's Answer, Also here as a lambda func:

cmd_exists = lambda x: any((os.access(os.path.join(path, x), os.X_OK) and os.path.isfile(os.path.join(path, x))) for path in os.environ["PATH"].split(os.pathsep))
cmd_exists('ls')

Or lastly, indented as a function:

def cmd_exists(cmd, path=None):
    """ test if path contains an executable file with name
    """
    if path is None:
        path = os.environ["PATH"].split(os.pathsep)

    for prefix in path:
        filename = os.path.join(prefix, cmd)
        executable = os.access(filename, os.X_OK)
        is_not_directory = os.path.isfile(filename)
        if executable and is_not_directory:
            return True
    return False

Is there a command to restart computer into safe mode?

My first answer!

This will set the safemode switch:

bcdedit /set {current} safeboot minimal 

with networking:

bcdedit /set {current} safeboot network

then reboot the machine with

shutdown /r

to put back in normal mode via dos:

bcdedit /deletevalue {current} safeboot

Javascript to export html table to Excel

ShieldUI's export to excel functionality should already support all special chars.

html5 audio player - jquery toggle click play/pause?

I did it inside of a jQuery accordion.

$(function() {
        /*video controls*/
            $("#player_video").click(function() {
              if (this.paused == false) {
                  this.pause();
              }
            });
        /*end video controls*/

        var stop = false;
        $("#accordion h3").click(function(event) {
            if (stop) {
                event.stopImmediatePropagation();
                event.preventDefault();
                stop = false;
            }
            $("#player_video").click();
        });

    });

How to Set focus to first text input in a bootstrap modal after shown

Try to remove the tabIndex property of the modal, when your input/textbox is open. Set it back to what ever it was, when you close input/textbox. This would resolve the issue irrespective bootstrap version, and without compromising the user experience flow.

How to automatically redirect HTTP to HTTPS on Apache servers?

Actually, your topic is belongs on https://serverfault.com/ but you can still try to check these .htaccess directives:

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*) https://%{HTTP_HOST}/$1

OnItemClickListener using ArrayAdapter for ListView

Use OnItemClickListener

   ListView lv = getListView();
   lv.setOnItemClickListener(new OnItemClickListener()
   {
      @Override
      public void onItemClick(AdapterView<?> adapter, View v, int position,
            long arg3) 
      {
            String value = (String)adapter.getItemAtPosition(position); 
            // assuming string and if you want to get the value on click of list item
            // do what you intend to do on click of listview row
      }
   });

When you click on a row a listener is fired. So you setOnClickListener on the listview and use the annonymous inner class OnItemClickListener.

You also override onItemClick. The first param is a adapter. Second param is the view. third param is the position ( index of listview items).

Using the position you get the item .

Edit : From your comments i assume you need to set the adapter o listview

So assuming your activity extends ListActivtiy

     setListAdapter(adapter); 

Or if your activity class extends Activity

     ListView lv = (ListView) findViewById(R.id.listview1);
     //initialize adapter 
     lv.setAdapter(adapter); 

If list index exists, do X

Using the length of the list would be the fastest solution to check if an index exists:

def index_exists(ls, i):
    return (0 <= i < len(ls)) or (-len(ls) <= i < 0)

This also tests for negative indices, and most sequence types (Like ranges and strs) that have a length.

If you need to access the item at that index afterwards anyways, it is easier to ask forgiveness than permission, and it is also faster and more Pythonic. Use try: except:.

try:
    item = ls[i]
    # Do something with item
except IndexError:
    # Do something without the item

This would be as opposed to:

if index_exists(ls, i):
    item = ls[i]
    # Do something with item
else:
    # Do something without the item

What's the difference between abstraction and encapsulation?

Encapsulation : Suppose I have some confidential documents, now I hide these documents inside a locker so no one can gain access to them, this is encapsulation.

Abstraction : A huge incident took place which was summarised in the newspaper. Now the newspaper only listed the more important details of the actual incident, this is abstraction. Further the headline of the incident highlights on even more specific details in a single line, hence providing higher level of abstraction on the incident. Also highlights of a football/cricket match can be considered as abstraction of the entire match.

Hence encapsulation is hiding of data to protect its integrity and abstraction is highlighting more important details.

In programming terms we can see that a variable may be enclosed is the scope of a class as private hence preventing it from being accessed directly from outside, this is encapsulation. Whereas a a function may be written in a class to swap two numbers. Now the numbers may be swapped in either by either using a temporary variable or through bit manipulation or using arithmetic operation, but the goal of the user is to receive the numbers swapped irrespective of the method used for swapping, this is abstraction.

How to conclude your merge of a file?

The easiest solution I found for this:

git commit -m "fixing merge conflicts"
git push

How to sort a list/tuple of lists/tuples by the element at a given index?

itemgetter() is somewhat faster than lambda tup: tup[1], but the increase is relatively modest (around 10 to 25 percent).

(IPython session)

>>> from operator import itemgetter
>>> from numpy.random import randint
>>> values = randint(0, 9, 30000).reshape((10000,3))
>>> tpls = [tuple(values[i,:]) for i in range(len(values))]

>>> tpls[:5]    # display sample from list
[(1, 0, 0), 
 (8, 5, 5), 
 (5, 4, 0), 
 (5, 7, 7), 
 (4, 2, 1)]

>>> sorted(tpls[:5], key=itemgetter(1))    # example sort
[(1, 0, 0), 
 (4, 2, 1), 
 (5, 4, 0), 
 (8, 5, 5), 
 (5, 7, 7)]

>>> %timeit sorted(tpls, key=itemgetter(1))
100 loops, best of 3: 4.89 ms per loop

>>> %timeit sorted(tpls, key=lambda tup: tup[1])
100 loops, best of 3: 6.39 ms per loop

>>> %timeit sorted(tpls, key=(itemgetter(1,0)))
100 loops, best of 3: 16.1 ms per loop

>>> %timeit sorted(tpls, key=lambda tup: (tup[1], tup[0]))
100 loops, best of 3: 17.1 ms per loop

Import / Export database with SQL Server Server Management Studio

I tried the answers above but the generated script file was very large and I was having problems while importing the data. I ended up Detaching the database, then copying .mdf to my new machine, then Attaching it to my new version of SQL Server Management Studio.

I found instructions for how to do this on the Microsoft Website:
https://msdn.microsoft.com/en-us/library/ms187858.aspx

NOTE: After Detaching the database I found the .mdf file within this directory:
C:\Program Files\Microsoft SQL Server\

Android Failed to install HelloWorld.apk on device (null) Error

I had the same problem and solved it by adding the paths of Android SDK folder tools and platform-tools to system PATH variable then restarting the device.

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0

I solve it by download the reportviewer.exe and install it. After the installation, all related assemblies will be available in C:\Windows\assembly\GAC_MSIL, then you can refer it in web config

How can I set a custom baud rate on Linux?

You can just use the normal termios header and normal termios structure (it's the same as the termios2 when using header asm/termios).

So, you open the device using open() and get a file descriptor, then use it in tcgetattr() to fill your termios structure.

Then clear CBAUD and set CBAUDEX on c_cflag. CBAUDEX has the same value as BOTHER.

After setting this, you can set a custom baud rate using normal functions, like cfsetspeed(), specifying the desired baud rate as an integer.

Install a module using pip for specific python version

Use a version of pip installed against the Python instance you want to install new packages to.

In many distributions, there may be separate python2.6-pip and python2.7-pip packages, invoked with binary names such as pip-2.6 and pip-2.7. If pip is not packaged in your distribution for the desired target, you might look for a setuptools or easyinstall package, or use virtualenv (which will always include pip in a generated environment).

pip's website includes installation instructions, if you can't find anything within your distribution.

Class method differences in Python: bound, unbound and static

When you call a class member, Python automatically uses a reference to the object as the first parameter. The variable self actually means nothing, it's just a coding convention. You could call it gargaloo if you wanted. That said, the call to method_two would raise a TypeError, because Python is automatically trying to pass a parameter (the reference to its parent object) to a method that was defined as having no parameters.

To actually make it work, you could append this to your class definition:

method_two = staticmethod(method_two)

or you could use the @staticmethod function decorator.

How do I create a unique constraint that also allows nulls?

CREATE UNIQUE NONCLUSTERED INDEX [UIX_COLUMN_NAME]
ON [dbo].[Employee]([Username] ASC) WHERE ([Username] IS NOT NULL) 
WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, 
DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, 
MAXDOP = 0) ON [PRIMARY];

How to return Json object from MVC controller to view

You could use AJAX to call this controller action. For example if you are using jQuery you might use the $.ajax() method:

<script type="text/javascript">
    $.ajax({
        url: '@Url.Action("NameOfYourAction")',
        type: 'GET',
        cache: false,
        success: function(result) {
            // you could use the result.values dictionary here
        }
    });
</script>

TOMCAT - HTTP Status 404

  1. Click on Window > Show view > Server or right click on the server in "Servers" view, select "Properties".
  2. In the "General" panel, click on the "Switch Location" button.
  3. The "Location: [workspace metadata]" should replace by something else.
  4. Open the Overview screen for the server by double clicking it.
  5. In the Server locations tab , select "Use Tomcat location".
  6. Save the configurations and restart the Server.

You may want to follow the steps above before starting the server. Because server location section goes grayed-unreachable.

server Locations in eclipse view

Load JSON text into class object in c#

I recommend you to use JSON.NET. it is an open source library to serialize and deserialize your c# objects into json and Json objects into .net objects ...

Serialization Example:

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": new Date(1230422400000),
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);

Performance Comparison To Other JSON serializiation Techniques enter image description here

Decimal values in SQL for dividing results

There may be other ways to get your desired result.

Declare @a int
Declare @b int
SET @a = 3
SET @b=2
SELECT cast((cast(@a as float)/ cast(@b as float)) as float)

Finding the handle to a WPF window

Just use your window with the WindowsInteropHelper class:

// ... Window myWindow = get your Window instance...
IntPtr windowHandle = new WindowInteropHelper(myWindow).Handle;

Right now, you're asking for the Application's main window, of which there will always be one. You can use this same technique on any Window, however, provided it is a System.Windows.Window derived Window class.

Reading binary file and looping over each byte

if you are looking for something speedy, here's a method I've been using that's worked for years:

from array import array

with open( path, 'rb' ) as file:
    data = array( 'B', file.read() ) # buffer the file

# evaluate it's data
for byte in data:
    v = byte # int value
    c = chr(byte)

if you want to iterate chars instead of ints, you can simply use data = file.read(), which should be a bytes() object in py3.

How to use string.substr() function?

Another interesting variant question can be:

How would you make "12345" as "12 23 34 45" without using another string?

Will following do?

    for(int i=0; i < a.size()-1; ++i)
    {
        //b = a.substr(i, 2);
        c = atoi((a.substr(i, 2)).c_str());
        cout << c << " ";
    }

Get last 5 characters in a string

Checks for errors:

Dim result As String = str
If str.Length > 5 Then
    result = str.Substring(str.Length - 5)
End If

Best way to create enum of strings?

Depending on what you mean by "use them as Strings", you might not want to use an enum here. In most cases, the solution proposed by The Elite Gentleman will allow you to use them through their toString-methods, e.g. in System.out.println(STRING_ONE) or String s = "Hello "+STRING_TWO, but when you really need Strings (e.g. STRING_ONE.toLowerCase()), you might prefer defining them as constants:

public interface Strings{
  public static final String STRING_ONE = "ONE";
  public static final String STRING_TWO = "TWO";      
}

JPA getSingleResult() or null

Here's another extension, this time in Scala.

customerQuery.getSingleOrNone match {
  case Some(c) => // ...
  case None    => // ...
}

With this pimp:

import javax.persistence.{NonUniqueResultException, TypedQuery}
import scala.collection.JavaConversions._

object Implicits {

  class RichTypedQuery[T](q: TypedQuery[T]) {

    def getSingleOrNone : Option[T] = {

      val results = q.setMaxResults(2).getResultList

      if (results.isEmpty)
        None
      else if (results.size == 1)
        Some(results.head)
      else
        throw new NonUniqueResultException()
    }
  }

  implicit def query2RichQuery[T](q: TypedQuery[T]) = new RichTypedQuery[T](q)
}

xpath find if node exists

A variation when using xpath in Java using count():

int numberofbodies = Integer.parseInt((String) xPath.evaluate("count(/html/body)", doc));
if( numberofbodies==0) {
    // body node missing
}

Read lines from a text file but skip the first two lines

Dim sFileName As String
Dim iFileNum As Integer
Dim sBuf As String
Dim Fields as String
Dim TempStr as String

sFileName = "c:\fields.ini"
''//Does the file exist?
If Len(Dir$(sFileName)) = 0 Then
    MsgBox ("Cannot find fields.ini")
End If

iFileNum = FreeFile()
Open sFileName For Input As iFileNum

''//This part skips the first two lines
if not(EOF(iFileNum)) Then Line Input #iFilenum, TempStr
if not(EOF(iFileNum)) Then Line Input #iFilenum, TempStr

Do While Not EOF(iFileNum)
    Line Input #iFileNum, Fields

    MsgBox (Fields)
Loop

Writing Python lists to columns in csv

If you are happy to use a 3rd party library, you can do this with Pandas. The benefits include seamless access to specialized methods and row / column labeling:

import pandas as pd

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]

df = pd.DataFrame(list(zip(*[list1, list2, list3]))).add_prefix('Col')

df.to_csv('file.csv', index=False)

print(df)

   Col0  Col1  Col2
0     1     4     7
1     2     5     8
2     3     6     9

How to enable ASP classic in IIS7.5

  • Go to control panel
  • click program features
  • turn windows on and off
  • go to internet services
  • under world wide web services check the asp.net and others

Click ok and your web sites will load properly.

Creating a PHP header/footer

You can use this for header: Important: Put the following on your PHP pages that you want to include the content.

<?php
//at top:
require('header.php'); 
 ?>
 <?php
// at bottom:
require('footer.php');
?>

You can also include a navbar globaly just use this instead:

 <?php
 // At top:
require('header.php'); 
 ?>
  <?php
// At bottom:
require('footer.php');
 ?>
 <?php
 //Wherever navbar goes:
require('navbar.php'); 
?>

In header.php:

 <!DOCTYPE html>
 <html lang="en">
 <head>
    <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
 </head>
 <body> 

Do Not close Body or Html tags!
Include html here:

 <?php
 //Or more global php here:

 ?>

Footer.php:

Code here:

<?php
//code

?>

Navbar.php:

<p> Include html code here</p>
<?php
 //Include Navbar PHP code here
 
?>

Benifits:

  • Cleaner main php file (index.php) script.
  • Change the header or footer. etc to change it on all pages with the include— Good for alerts on all pages etc...
  • Time Saving!
  • Faster page loads!
  • you can have as many files to include as needed!
  • server sided!

batch file to check 64bit or 32bit OS

This is the correct way to perform the check as-per Microsoft's knowledgebase reference ( http://support.microsoft.com/kb/556009 ) that I have re-edited into just a single line of code.

It doesn't rely on any environment variables or folder names and instead checks directly in the registry.

As shown in a full batch file below it sets an environment variable OS equal to either 32BIT or 64BIT that you can use as desired.

@echo OFF

reg Query "HKLM\Hardware\Description\System\CentralProcessor\0" | find /i "x86" > NUL && set OS=32BIT || set OS=64BIT

if %OS%==32BIT echo This is a 32bit operating system
if %OS%==64BIT echo This is a 64bit operating system

Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port

Like the previous comment mention, the message "It looks like you are trying to access MongoDB over HTTP on the native driver port." its a warning because you are missunderstanding this line: mongoose.connect('mongodb://localhost/info'); and browsing this url: http://localhost:28017/

However, if you want to see the mongo's admin web page, you could do it, with this command:

mongod --rest --httpinterface

browsing this url: http://localhost:28017/

the parameter httpinterface activate the admin web page, and the parameter rest its needed for activate the rest services the page require

var self = this?

This question is not specific to jQuery, but specific to JavaScript in general. The core problem is how to "channel" a variable in embedded functions. This is the example:

var abc = 1; // we want to use this variable in embedded functions

function xyz(){
  console.log(abc); // it is available here!
  function qwe(){
    console.log(abc); // it is available here too!
  }
  ...
};

This technique relies on using a closure. But it doesn't work with this because this is a pseudo variable that may change from scope to scope dynamically:

// we want to use "this" variable in embedded functions

function xyz(){
  // "this" is different here!
  console.log(this); // not what we wanted!
  function qwe(){
    // "this" is different here too!
    console.log(this); // not what we wanted!
  }
  ...
};

What can we do? Assign it to some variable and use it through the alias:

var abc = this; // we want to use this variable in embedded functions

function xyz(){
  // "this" is different here! --- but we don't care!
  console.log(abc); // now it is the right object!
  function qwe(){
    // "this" is different here too! --- but we don't care!
    console.log(abc); // it is the right object here too!
  }
  ...
};

this is not unique in this respect: arguments is the other pseudo variable that should be treated the same way — by aliasing.

Pass a password to ssh in pure bash

You can not specify the password from the command line but you can do either using ssh keys or using sshpass as suggested by John C. or using a expect script.

To use sshpass, you need to install it first. Then

sshpass -f <(printf '%s\n' your_password) ssh user@hostname

instead of using sshpass -p your_password. As mentioned by Charles Duffy in the comments, it is safer to supply the password from a file or from a variable instead of from command line.

BTW, a little explanation for the <(command) syntax. The shell executes the command inside the parentheses and replaces the whole thing with a file descriptor, which is connected to the command's stdout. You can find more from this answer https://unix.stackexchange.com/questions/156084/why-does-process-substitution-result-in-a-file-called-dev-fd-63-which-is-a-pipe

Best way to replace multiple characters in a string?

Here is a python3 method using str.translate and str.maketrans:

s = "abc&def#ghi"
print(s.translate(str.maketrans({'&': '\&', '#': '\#'})))

The printed string is abc\&def\#ghi.

Display A Popup Only Once Per User

Offering a quick answer for people using Ionic. I need to show a tooltip only once so I used the $localStorage to achieve this. This is for playing a track, so when they push play, it shows the tooltip once.

$scope.storage = $localStorage; //connects an object to $localstorage

$scope.storage.hasSeenPopup = "false";  // they haven't seen it


$scope.showPopup = function() {  // popup to tell people to turn sound on

    $scope.data = {}
    // An elaborate, custom popup
    var myPopup = $ionicPopup.show({
        template: '<p class="popuptext">Turn Sound On!</p>',
        cssClass: 'popup'

    });        
    $timeout(function() {
        myPopup.close(); //close the popup after 3 seconds for some reason
    }, 2000);
    $scope.storage.hasSeenPopup = "true"; // they've now seen it

};

$scope.playStream = function(show) {
    PlayerService.play(show);

    $scope.audioObject = audioObject; // this allow for styling the play/pause icons

    if ($scope.storage.hasSeenPopup === "false"){ //only show if they haven't seen it.
        $scope.showPopup();
    }
}

How do I get a specific range of numbers from rand()?

if you care about the quality of your random numbers don't use rand()

use some other prng like http://en.wikipedia.org/wiki/Mersenne_twister or one of the other high quality prng's out there

then just go with the modulus.

How to get value at a specific index of array In JavaScript?

You can just use []:

var valueAtIndex1 = myValues[1];

How do I parse command line arguments in Java?

As one of the comments mentioned earlier (https://github.com/pcj/google-options) would be a good choice to start with.

One thing I want to add-on is:

1) If you run into some parser reflection error, please try use a newer version of the guava. in my case:

maven_jar(
    name = "com_google_guava_guava",
    artifact = "com.google.guava:guava:19.0",
    server = "maven2_server",
)

maven_jar(
    name = "com_github_pcj_google_options",
    artifact = "com.github.pcj:google-options:jar:1.0.0",
    server = "maven2_server",
)

maven_server(
    name = "maven2_server",
    url = "http://central.maven.org/maven2/",
)

2) When running the commandline:

bazel run path/to/your:project -- --var1 something --var2 something -v something

3) When you need the usage help, just type:

bazel run path/to/your:project -- --help

Change tab bar tint color on iOS 7

You can set your tint color and font as setTitleTextattribute:

UIFont *font= (kUIScreenHeight>KipadHeight)?[UIFont boldSystemFontOfSize:32.0f]:[UIFont boldSystemFontOfSize:16.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,
                            tintColorLight, NSForegroundColorAttributeName, nil];
[[UINavigationBar appearance] setTitleTextAttributes:attributes];

HTML combo box with option to type an entry

    <html>
<head>
    <title></title>
    <script src="jquery-3.1.0.js"></script>
    <script>
        $(function () {
            $('#selectnumber').change(function(){
                alert('.val() = ' + $('#selectnumber').val() + '  AND  html() = ' + $('#selectnumber option:selected').html() + '  AND .text() = ' + $('#selectnumber option:selected').text());
            })
        });
    </script>
</head>
<body>
       <div>
        <select id="selectnumber">
            <option value="1">one</option>
            <option value="2">two</option>
            <option value="3">three</option>
            <option value="4">four</option>
        </select>

    </div>
   </body>
</html>

Click to see OutPut Screen

Thanks...:)

Browser detection in JavaScript?

It is usually best to avoid browser-specific code where possible. The JQuery $.support property is available for detection of support for particular features rather than relying on browser name and version.

In Opera for example, you can fake an internet explorer or firefox instance.

alt text

A detailed description of JQuery.support can be found here: http://api.jquery.com/jQuery.support/

Now deprecated according to jQuery.

We strongly recommend the use of an external library such as Modernizr instead of dependency on properties in jQuery.support.

When coding websites, I always make sure, that basic functionality like navigation is also accessible to non-js users. This may be object to discussion and can be ignored if the homepage is targeted to a special audience.

UITableView load more when scrolling to bottom like Facebook application

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger lastSectionIndex = [tableView numberOfSections] - 1;
    NSInteger lastRowIndex = [tableView numberOfRowsInSection:lastSectionIndex] - 1;
    if ((indexPath.section == lastSectionIndex) && (indexPath.row == lastRowIndex)) {
        // This is the last cell
        [self loadMore];
    }
}

If you are using Core Data and NSFetchedResultsController, then loadMore could look like the following:

// Load more
- (void)loadMore {
    [self.fetchedResultsController.fetchRequest setFetchLimit:newFetchLimit];
    [NSFetchedResultsController deleteCacheWithName:@"cache name"];
    NSError *error;
    if (![self.fetchedResultsController performFetch:&error]) {
        // Update to handle the error appropriately.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    }

    [self.tableView reloadData];
}

Adding a splash screen to Flutter apps

You can make design of flutter splash screen same as other screens. The only change is use of timer. So you can display splash screen for specific amount of time.

import 'dart:async';
import 'package:flutter/material.dart';
 
class Splash extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return SplashState();
  }
 
}
 
class SplashState extends State<Splash>{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
 
    );
  }
 
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    startTimer();
  }
 
  startTimer() async{
     Timer(Duration(seconds: 3), nextScreen);
  }
 
   void nextScreen(){
 
  }
 
}
import ‘package:flutter/material.dart’;
import ‘package:fluttersplashsample/splash.dart’;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
    // This widget is the root of your application.
    @override
    Widget build(BuildContext context) {
          return MaterialApp(
              home: Splash(),
          );
     }
}

Java: Find .txt files in specified folder

Try:

List<String> textFiles(String directory) {
  List<String> textFiles = new ArrayList<String>();
  File dir = new File(directory);
  for (File file : dir.listFiles()) {
    if (file.getName().endsWith((".txt"))) {
      textFiles.add(file.getName());
    }
  }
  return textFiles;
}

You want to do a case insensitive search in which case:

    if (file.getName().toLowerCase().endsWith((".txt"))) {

If you want to recursively search for through a directory tree for text files, you should be able to adapt the above as either a recursive function or an iterative function using a stack.

Chain-calling parent initialisers in python

The way you are doing it is indeed the recommended one (for Python 2.x).

The issue of whether the class is passed explicitly to super is a matter of style rather than functionality. Passing the class to super fits in with Python's philosophy of "explicit is better than implicit".

HTML not loading CSS file

I was having similar problem but resolved changing the Style.css to style.css Because of this name caps letter "S"change it was throwing 404 error we won't notice small changes in my system it was working but when I hosted in cloud it was throwing this error make sure this all being checked after uploading in cloud

How can I install Visual Studio Code extensions offline?

UPDATE 2017-12-13

You can now download the extension directly from the marketplace.

Enter image description here

As of Visual Studio Code 1.7.1 dragging or opening the extension does not work any more. In order to install it manually you need to:

  • open the extensions sidebar
  • click on the ellipsis in the right upper corner
  • choose Install from VSIX

Install from VSIX...


Old Method

According to the documentation it is possible to download an extension directly:

An extension's direct download URL is in the form:

https://${publisher}.gallery.vsassets.io/_apis/public/gallery/publisher/${publisher}/extension/${extension name}/${version}/assetbyname/Microsoft.VisualStudio.Services.VSIXPackage

This means that in order to download the extension you need to know

  • the publisher name
  • the version
  • the extension name

You can find all this information in the URL.

Example

Here's an example for downloading an installing the C# v1.3.0 extension:

Publisher, Extension and Version

You can find the publisher and the extension names on the extension's homepage inside its URL:

https://marketplace.visualstudio.com/items?itemName=ms-vscode.csharp

Here the publisher is ms-vscode and the extension name is csharp.

The version can be found on the right side in the More Info area.

To download it you need to create a link from the template above:

https://ms-vscode.gallery.vsassets.io/_apis/public/gallery/publisher/ms-vscode/extension/csharp/1.3.0/assetbyname/Microsoft.VisualStudio.Services.VSIXPackage

All packages will have the same name Microsoft.VisualStudio.Services.VSIXPackage, so you'll need to rename it after downloading if you want to know what package it was later.

Installation

In order to install the extension

  • Rename the file and give it the *.vsix extension
  • Open Visual Studio Code, go to menu FileOpen File... or Ctrl + O and select the .vsix file
  • If everything went fine, you should see this message at the top of the window:

Extension was successfully installed. Restart to enable it.

Bootstrap control with multiple "data-toggle"

Since Bootstrap forces you to initialize tooltips only through Javascript, I changed data-toggle="tooltip" (since it's useless then) to class="bootstrap-tooltip" and used this Javascript to initialize my tooltips:

$('.bootstrap-tooltip').tooltip();

And so I was free to use the data-toggle attribute for something else (e.g. data-toggle="button").

Which exception should I raise on bad/illegal argument combinations in Python?

It depends on what the problem with the arguments is.

If the argument has the wrong type, raise a TypeError. For example, when you get a string instead of one of those Booleans.

if not isinstance(save, bool):
    raise TypeError(f"Argument save must be of type bool, not {type(save)}")

Note, however, that in Python we rarely make any checks like this. If the argument really is invalid, some deeper function will probably do the complaining for us. And if we only check the boolean value, perhaps some code user will later just feed it a string knowing that non-empty strings are always True. It might save him a cast.

If the arguments have invalid values, raise ValueError. This seems more appropriate in your case:

if recurse and not save:
    raise ValueError("If recurse is True, save should be True too")

Or in this specific case, have a True value of recurse imply a True value of save. Since I would consider this a recovery from an error, you might also want to complain in the log.

if recurse and not save:
    logging.warning("Bad arguments in import_to_orm() - if recurse is True, so should save be")
    save = True

Getting each individual digit from a whole integer

Don't reinvent the wheel. C has sprintf for a reason. Since your variable is called score, I'm guessing this is for a game where you're planning to use the individual digits of the score to display the numeral glyphs as images. In this case, sprintf has convenient format modifiers that will let you zero-pad, space-pad, etc. the score to a fixed width, which you may want to use.

Set title background color

This thread will get you started with building your own title bar in a xml file and using it in your activities

Edit

Here is a brief summary of the content of the link above - This is just to set the color of the text and the background of the title bar - no resizing, no buttons, just the simpliest sample

res/layout/mytitle.xml - This is the view that will represent the title bar

<?xml version="1.0" encoding="utf-8"?>
<TextView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/myTitle"
  android:text="This is my new title"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:textColor="@color/titletextcolor"
   />

res/values/themes.xml - We want to keep the default android theme and just need to change the background color of the title background. So we create a theme that inherits the default theme and set the background style to our own style.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="customTheme" parent="android:Theme"> 
        <item name="android:windowTitleBackgroundStyle">@style/WindowTitleBackground</item>   
    </style> 
</resources>

res/values/styles.xml - This is where we set the theme to use the color we want for the title background

<?xml version="1.0" encoding="utf-8"?>
<resources> 
   <style name="WindowTitleBackground">     
        <item name="android:background">@color/titlebackgroundcolor</item>                   
    </style>
</resources>

res/values/colors.xml - Set here the color you want

<?xml version="1.0" encoding="utf-8"?>
<resources>   
    <color name="titlebackgroundcolor">#3232CD</color>
    <color name="titletextcolor">#FFFF00</color>
</resources>

In the AndroidMANIFEST.xml, set the theme attribute either in the application (for the whole application) or in the activity (only this activity) tags

<activity android:name=".CustomTitleBar" android:theme="@style/customTheme" ...

From the Activity (called CustomTitleBar) :

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

        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.main);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.mytitle);

}

Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4

Compiling PIL on Windows x64 is apparently a bit of a pain. (Well, compiling anything on Windows is a bit of a pain in my experience. But still.) As well as PIL itself you'll need to build many dependencies. See these notes from the mailing list too.

There's an unofficial precompiled binary for x64 linked from this message, but I haven't tried it myself. Might be worth a go if you don't mind the download being from one of those slightly dodgy file-upload sites. Other than that... well, you could always give up and instead the 32-bit Python binary instead.

Assembly code vs Machine code vs Object code?

The source files of your programs are compiled into object files, and then the linker links those object files together, producing an executable file including your architecture's machine codes.

Both object file and executable file involves architecture's machine code in the form of printable and non-printable characters when it's opened by a text editor.

Nonetheless, the dichotomy between the files is that the object file(s) may contain unresolved external references (such as printf, for instance). So, it may need to be linked against other object files.. That is to say, the unresolved external references are needed to be resolved in order to get the decent runnable executable file by linking with other object files such as C/C++ runtime library's.

VB.NET Inputbox - How to identify when the Cancel Button is pressed?

Dim userReply As String
userReply = Microsoft.VisualBasic.InputBox("Message")
If userReply = "" Then 
  MsgBox("You did not enter anything. Try again")
ElseIf userReply.Length = 0 Then 
  MsgBox("You did not enter anything")
End If

Google Authenticator available as a public service?

Yes, need no network service, because Google Authenticator app won't communicate with the google server, it just keeps synced with the initital secret that your server generate(input into your phone from QR code) while the time pass.

Center content vertically on Vuetify

Update for new vuetify version

In v.2.x.x , we can use align and justify. We have below options for setup the horizontal and vertical alignment.

  1. PROPS align : 'start','center','end','baseline','stretch'

  2. PRPS justify : 'start','center','end','space-around','space-between'

<v-container fill-height fluid>
  <v-row align="center"
      justify="center">
      <v-col></v-col>
  </v-row>
</v-container>

For more details please refer this vuetify grid-system and you could check here with working codepen demo.


Original answer

You could use align-center for layout and fill-height for container.

Demo with v1.x.x

_x000D_
_x000D_
new Vue({
  el: '#app' 
})
_x000D_
.bg{
    background: gray;
    color: #fff;
    font-size: 18px;
}
_x000D_
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.js"></script>

<div id="app">
  <v-app>
      <v-container bg fill-height grid-list-md text-xs-center>
        <v-layout row wrap align-center>
          <v-flex>
            Hello I am center to vertically using "align-center".
          </v-flex>
        </v-layout>
      </v-container>
  </v-app>
</div>
_x000D_
_x000D_
_x000D_

What are the basic rules and idioms for operator overloading?

Why can't operator<< function for streaming objects to std::cout or to a file be a member function?

Let's say you have:

struct Foo
{
   int a;
   double b;

   std::ostream& operator<<(std::ostream& out) const
   {
      return out << a << " " << b;
   }
};

Given that, you cannot use:

Foo f = {10, 20.0};
std::cout << f;

Since operator<< is overloaded as a member function of Foo, the LHS of the operator must be a Foo object. Which means, you will be required to use:

Foo f = {10, 20.0};
f << std::cout

which is very non-intuitive.

If you define it as a non-member function,

struct Foo
{
   int a;
   double b;
};

std::ostream& operator<<(std::ostream& out, Foo const& f)
{
   return out << f.a << " " << f.b;
}

You will be able to use:

Foo f = {10, 20.0};
std::cout << f;

which is very intuitive.

Is there an opposite to display:none?

visibility:hidden will hide the element but element is their with DOM. And in case of display:none it'll remove the element from the DOM.

So you have option for element to either hide or unhide. But once you delete it ( I mean display none) it has not clear opposite value. display have several values like display:block,display:inline, display:inline-block and many other. you can check it out from W3C.

Java : Cannot format given Object as a Date

public static String showDate(){
    SimpleDateFormat df=new SimpleDateFormat("\nTime:yyyy-MM-dd HH:mm:ss");
    System.out.println(df.format(new Date()));
    String s=df.format(new Date());
    return s;
}

I think this code may solve your problem.

MySQL Select Date Equal to Today

SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d') 
FROM users 
WHERE DATE(signup_date) = CURDATE()

How can I cast int to enum?

enter image description here

To convert a string to ENUM or int to ENUM constant we need to use Enum.Parse function. Here is a youtube video https://www.youtube.com/watch?v=4nhx4VwdRDk which actually demonstrate's with string and the same applies for int.

The code goes as shown below where "red" is the string and "MyColors" is the color ENUM which has the color constants.

MyColors EnumColors = (MyColors)Enum.Parse(typeof(MyColors), "Red");

How to download all files (but not HTML) from a website using wget?

wget -m -A * -pk -e robots=off www.mysite.com/

this will download all type of files locally and point to them from the html file and it will ignore robots file