Programs & Examples On #Mobile os

Preloading images with JavaScript

Working solution as of 2020

Most answers on this post no longer work - (atleast on Firefox)

Here's my solution:

var cache = document.createElement("CACHE");
cache.style = "position:absolute;z-index:-1000;opacity:0;";
document.body.appendChild(cache);
function preloadImage(url) {
    var img = new Image();
    img.src = url;
    img.style = "position:absolute";
    cache.appendChild(img);
}

Usage:

preloadImage("example.com/yourimage.png");

Obviously <cache> is not a "defined" element, so you could use a <div> if you wanted to.

Use this in your CSS, instead of applying the style attribute:

cache {
    position: absolute;
    z-index: -1000;
    opacity: 0;
}

cache image {
    position: absolute;
}

If you have tested this, please leave a comment.

Notes:

  • Do NOT apply display: none; to cache - this will not load the image.
  • Don't resize the image element, as this will also affect the quality of the loaded image when you come to use it.
  • Setting position: absolute to the image is necessary, as the image elements will eventually make it's way outside of the viewport - causing them to not load, and affect performance.

UPDATE

While above solution works, here's a small update I made to structure it nicely:

(This also now accepts multiple images in one function)

var cache = document.createElement("CACHE");
document.body.appendChild(cache);
function preloadImage() {
    for (var i=0; i<arguments.length; i++) {
        var img = new Image();
        img.src = arguments[i];
        var parent = arguments[i].split("/")[1]; // Set to index of folder name
        if ($(`cache #${parent}`).length == 0) {
            var ele = document.createElement("DIV");
            ele.id = parent;
            cache.appendChild(ele);
        }
        $(`cache #${parent}`)[0].appendChild(img);
        console.log(parent);
    }
}

preloadImage(
    "assets/office/58.png",
    "assets/leftbutton/124.png",
    "assets/leftbutton/125.png",
    "assets/leftbutton/130.png",
    "assets/leftbutton/122.png",
    "assets/leftbutton/124.png"
);

Preview:

enter image description here

Notes:

  • Try not to keep too many images preloaded at the same time (this can cause major performance issues) - I got around this by hiding images, which I knew wasn't going to be visible during certain events. Then, of course, show them again when I needed it.

What does "select 1 from" do?

It does what you ask, SELECT 1 FROM table will SELECT (return) a 1 for every row in that table, if there were 3 rows in the table you would get

1
1
1

Take a look at Count(*) vs Count(1) which may be the issue you were described.

adb shell su works but adb root does not

I use for enter su mode in abd shell

adb shell "su"

How to resolve "local edit, incoming delete upon update" message

Try to resolve the conflict using

svn resolve --accept=working PATH

Redirecting 404 error with .htaccess via 301 for SEO etc

You will need to know something about the URLs, like do they have a specific directory or some query string element because you have to match for something. Otherwise you will have to redirect on the 404. If this is what is required then do something like this in your .htaccess:

ErrorDocument 404 /index.php

An error page redirect must be relative to root so you cannot use www.mydomain.com.

If you have a pattern to match too then use 301 instead of 302 because 301 is permanent and 302 is temporary. A 301 will get the old URLs removed from the search engines and the 302 will not.

Mod Rewrite Reference: http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html

How to debug Google Apps Script (aka where does Logger.log log to?)

I am having the same problem, I found the below on the web somewhere....

Event handlers in Docs are a little tricky though. Because docs can handle multiple simultaneous edits by multiple users, the event handlers are handled server-side. The major issue with this structure is that when an event trigger script fails, it fails on the server. If you want to see the debug info you'll need to setup an explicit trigger under the triggers menu that emails you the debug info when the event fails or else it will fail silently.

Best implementation for Key Value Pair Data Structure?

There is a KeyValuePair built-in type. As a matter of fact, this is what the IDictionary is giving you access to when you iterate in it.

Also, this structure is hardly a tree, finding a more representative name might be a good exercise.

ip address validation in python using regex

Why not use a library function to validate the ip address?

>>> ip="241.1.1.112343434" 
>>> socket.inet_aton(ip)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
socket.error: illegal IP address string passed to inet_aton

Checkout subdirectories in Git?

There is an inspiration here. Just utilize shell regex or git regex.

git checkout commit_id */*.bat  # *.bat in 1-depth subdir exclude current dir, shell regex  
git checkout commit_id '*.bat'  # *.bat in all subdir include current dir, git regex

Use quotation to escape shell regex interpretation and pass wildcards to git.

The first one is not recursive, only files in 1-depth subdir. But the second one is recursive.

As for your situation, the following may be enough.

git checkout master */*/wp-content/*/*
git checkout master '*/wp-content/*'

Just hack the lines as required.

How to use registerReceiver method?

The whole code if somebody need it.

void alarm(Context context, Calendar calendar) {
    AlarmManager alarmManager = (AlarmManager)context.getSystemService(ALARM_SERVICE);

    final String SOME_ACTION = "com.android.mytabs.MytabsActivity.AlarmReceiver";
    IntentFilter intentFilter = new IntentFilter(SOME_ACTION);

    AlarmReceiver mReceiver = new AlarmReceiver();
    context.registerReceiver(mReceiver, intentFilter);

    Intent anotherIntent = new Intent(SOME_ACTION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, anotherIntent, 0);
    alramManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

    Toast.makeText(context, "Added", Toast.LENGTH_LONG).show();
}

class AlarmReceiver extends BroadcastReceiver {     
    @Override
    public void onReceive(Context context, Intent arg1) {
        Toast.makeText(context, "Started", Toast.LENGTH_LONG).show();
    }
}

Convert seconds to hh:mm:ss in Python

Read up on the datetime module.

SilentGhost's answer has the details my answer leaves out and is reposted here:

>>> a = datetime.timedelta(seconds=65)
datetime.timedelta(0, 65)
>>> str(a)
'0:01:05'

Assigning the output of a command to a variable

If you want to do it with multiline/multiple command/s then you can do this:

output=$( bash <<EOF
#multiline/multiple command/s
EOF
)

Or:

output=$(
#multiline/multiple command/s
)

Example:

#!/bin/bash
output="$( bash <<EOF
echo first
echo second
echo third
EOF
)"
echo "$output"

Output:

first
second
third

warning: assignment makes integer from pointer without a cast

The warning comes from the fact that you're dereferencing src in the assignment. The expression *src has type char, which is an integral type. The expression "anotherstring" has type char [14], which in this particular context is implicitly converted to type char *, and its value is the address of the first character in the array. So, you wind up trying to assign a pointer value to an integral type, hence the warning. Drop the * from *src, and it should work as expected:

src = "anotherstring";

since the type of src is char *.

How to set Sqlite3 to be case insensitive when string comparing?

Simply, you can use COLLATE NOCASE in your SELECT query:

SELECT * FROM ... WHERE name = 'someone' COLLATE NOCASE

package R does not exist

I forgot to add the "name" of my "package" at the top of my java class. Check if yours is actually added.

How to get complete month name from DateTime

If you want the current month you can use DateTime.Now.ToString("MMMM") to get the full month or DateTime.Now.ToString("MMM") to get an abbreviated month.

If you have some other date that you want to get the month string for, after it is loaded into a DateTime object, you can use the same functions off of that object:
dt.ToString("MMMM") to get the full month or dt.ToString("MMM") to get an abbreviated month.

Reference: Custom Date and Time Format Strings

Alternatively, if you need culture specific month names, then you could try these: DateTimeFormatInfo.GetAbbreviatedMonthName Method
DateTimeFormatInfo.GetMonthName Method

How to copy selected files from Android with adb pull

As to the short script, the following runs on my Linux host

#!/bin/bash
HOST_DIR=<pull-to>
DEVICE_DIR=/sdcard/<pull-from>
EXTENSION="\.jpg"

while read MYFILE ; do
    adb pull "$DEVICE_DIR/$MYFILE" "$HOST_DIR/$MYFILE"
done < $(adb shell ls -1 "$DEVICE_DIR" | grep "$EXTENSION")

"ls minus one" lets "ls" show one file per line, and the quotation marks allow spaces in the filename.

How to fix 'fs: re-evaluating native module sources is not supported' - graceful-fs

Type npm list graceful-fs and you will see which versions of graceful-fs are currently installed.

In my case I got:

npm list graceful-fs

@request/[email protected] /projects/request/promise-core
+-- [email protected]
| `-- [email protected]
|   +-- [email protected]
|   | `-- [email protected]
|   |   `-- [email protected]
|   |     `-- [email protected]
|   |       `-- [email protected]        <==== !!!
|   `-- [email protected] 
`-- [email protected]
  +-- [email protected]
  | `-- [email protected]
  |   `-- [email protected]
  |     `-- [email protected]
  |       `-- [email protected] 
  `-- [email protected]
    `-- [email protected]
      `-- [email protected]

As you can see gulp deep down depends on a very old version. Unfortunately, I can't update that myself using npm update graceful-fs. gulp would need to update their dependencies. So if you have a case like this you are out of luck. But you may open an issue for the project with the old dependency - i.e. gulp.

CURL and HTTPS, "Cannot resolve host"

Just a note which may be helpful- I was having this trouble with Apache on my laptop (which connects by wifi AFTER startup), and restarting the server (after connect) fixed the issue. I guess in my case this may be to do with apache starting offline and perhaps there noting that DNS lookups fail?

Default optional parameter in Swift function

If you want to be able to call the func with or without the parameter you can create a second func of the same name which calls the other.

func test(firstThing: Int?) {
    if firstThing != nil {
        print(firstThing!)
    }
    print("done")
}

func test() {
    test(firstThing: nil)
}

now you can call a function named test without or without the parameter.

// both work
test()
test(firstThing: 5)

Entity Framework - Linq query with order by and group by

It's method syntax (which I find easier to read) but this might do it

Updated post comment

Use .FirstOrDefault() instead of .First()

With regard to the dates average, you may have to drop that ordering for the moment as I am unable to get to an IDE at the moment

var groupByReference = context.Measurements
                              .GroupBy(m => m.Reference)
                              .Select(g => new {Creation = g.FirstOrDefault().CreationTime, 
//                                              Avg = g.Average(m => m.CreationTime.Ticks),
                                                Items = g })
                              .OrderBy(x => x.Creation)
//                            .ThenBy(x => x.Avg)
                              .Take(numOfEntries)
                              .ToList();

Getting the PublicKeyToken of .Net assemblies

another option:

if you use PowerShell, you can find out like:

PS C:\Users\Pravat> ([system.reflection.assembly]::loadfile("C:\Program Files (x86)\MySQL\Connector NET 6.6.5\Assemblies\v4.0\MySql.Data.dll")).FullName

like

PS C:\Users\Pravat> ([system.reflection.assembly]::loadfile("dll full path")).FullName

and will appear like

MySql.Data, Version=6.6.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d

Executing a batch script on Windows shutdown

I found this topic while searching for run script for startup and shutdown Windows 10. Those answers above didn't working. For me on windows 10 worked when I put scripts to task scheduler. How to do this: press window key and write Task scheduler, open it, then on the right is Add task... button. Here you can add scripts. PS: I found action for startup and logout user, there is not for shutdown.

Fitting polynomial model to data in R

Which model is the "best fitting model" depends on what you mean by "best". R has tools to help, but you need to provide the definition for "best" to choose between them. Consider the following example data and code:

x <- 1:10
y <- x + c(-0.5,0.5)

plot(x,y, xlim=c(0,11), ylim=c(-1,12))

fit1 <- lm( y~offset(x) -1 )
fit2 <- lm( y~x )
fit3 <- lm( y~poly(x,3) )
fit4 <- lm( y~poly(x,9) )
library(splines)
fit5 <- lm( y~ns(x, 3) )
fit6 <- lm( y~ns(x, 9) )

fit7 <- lm( y ~ x + cos(x*pi) )

xx <- seq(0,11, length.out=250)
lines(xx, predict(fit1, data.frame(x=xx)), col='blue')
lines(xx, predict(fit2, data.frame(x=xx)), col='green')
lines(xx, predict(fit3, data.frame(x=xx)), col='red')
lines(xx, predict(fit4, data.frame(x=xx)), col='purple')
lines(xx, predict(fit5, data.frame(x=xx)), col='orange')
lines(xx, predict(fit6, data.frame(x=xx)), col='grey')
lines(xx, predict(fit7, data.frame(x=xx)), col='black')

Which of those models is the best? arguments could be made for any of them (but I for one would not want to use the purple one for interpolation).

how to delete installed library form react native project

I will post my answer here since it's the first result in google's search

1) react-native unlink <Module Name>

2) npm unlink <Module Name>

3) npm uninstall --save <Module name

Section vs Article HTML5

A section is basically a wrapper for h1 (or other h tags) and the content that corresponds to this. An article is essentially a document within your document that is repeated or paginated...like each blog post on your document can be an article, or each comment on your document can be an article.

SQL Server String Concatenation with Null

Use COALESCE. Instead of your_column use COALESCE(your_column, ''). This will return the empty string instead of NULL.

Error loading the SDK when Eclipse starts

I couldn't delete the system image (idk why), so I took the approach of deleting all occurrences of g:skin in any xml file since eclipse don't know what that is:

$ find . -type f -name "*.xml" -print0 | xargs -0 sed -i /d:skin/d

On windows you might want to run it within Cygwin or cmder

Draw a connecting line between two elements

GoJS supports this, with its State Chart example, that supports dragging and dropping of elements, and editing of connections.

This answer is based off of Walter Northwoods' answer.

Control the dashed border stroke length and distance between strokes

I just recently had the same problem. I have made this work around, hope it will help someone.

HTML + tailwind

<div class="dashed-border h-14 w-full relative rounded-lg">
    <div class="w-full h-full rounded-lg bg-page z-10 relative">
        Content goes here...
    <div>
</div>

CSS

.dashed-border::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  width: 100%;
  height: calc(100% + 4px);
  transform: translateY(-50%);
  background-image: linear-gradient(to right, #333 50%, transparent 50%);
  background-size: 16px;
  z-index: 0;
  border-radius: 0.5rem;
}
.dashed-border::after {
  content: '';
  position: absolute;
  left: 50%;
  top: 0;
  height: 100%;
  width: calc(100% + 4px);
  transform: translateX(-50%);
  background-image: linear-gradient(to bottom, #333 50%, transparent 50%);
  background-size: 4px 16px;
  z-index: 1;
  border-radius: 0.5rem;
}

Show Console in Windows Application?

As per Jeffrey Knight quote above, as soon as I run into situations where I need API calls to get something done, I tend to stop and ask myself "am I overcomplicating things?".

If what is wanted is to have some code and run it in Windows GUI mode or Console mode, consider moving the code used in both modes off to a code library DLL, and then having a Windows Forms application that uses that DLL, and a Console application that uses that DLL (i.e. if in Visual Studio you now have a three-project solution: library with the bulk of the code, GUI with just the Win Forms code, and Console with just your console code.)

Where can I find error log files?

This will defiantly help you,

https://davidwinter.me/enable-php-error-logging/

OR

In php.ini: (vim /etc/php.ini Or Sudo vim /usr/local/etc/php/7.1/php.ini)

display_errors = Off

log_errors = On

error_log = /var/log/php-errors.log

Make the log file, and writable by www-data:

sudo touch /var/log/php-errors.log

/var/log/php-errors.log

sudo chown :www

Thanks,

How can I show/hide a specific alert with twitter bootstrap?

I had this problem today, was in a lot of time crunch, so below idea worked:

  • setTimeout with 1 sec -- call a function that shows the div
  • setTimeout with 10 sec -- call a function that hides the div

Fade is not there, but that bootstrap feeling will be there.

Hope that helps.

How to copy to clipboard in Vim?

Use the register "+ to copy to the system clipboard (i.e. "+y instead of y).

Likewise you can paste from "+ to get text from the system clipboard (i.e. "+p instead of p).

How to get the current location latitude and longitude in android

IMPORTANT:

Please notice this solution is from 2015 might be too old and deprecated.


None of the above worked for me so I made a tutorial and wrote it for myself since I lost many hours trying to implement this. Hope this helps someone:

How to use Google Play Services LOCATION API to get current latitude & longitude

1) Add to your AndroidManifest.xml file the ACCESS_COARSE_LOCATION & ACCESS_FINE_LOCATION:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.appname" >

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

        <application...

2) Go to app/build.gradlefile and add the following dependency (make sure to use the latest available version):

    dependencies {
        //IMPORTANT: make sure to use the newest version. 11.0.1 is old AF
        compile 'com.google.android.gms:play-services-location:11.0.1
    }

3) In your activity implement the following:

    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
    import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
    import com.google.android.gms.location.LocationListener;
    import com.google.android.gms.location.LocationRequest;
    import com.google.android.gms.location.LocationServices;
    import com.google.android.gms.maps.GoogleMap;

    public class HomeActivity extends AppCompatActivity implements
            ConnectionCallbacks,
            OnConnectionFailedListener,
            LocationListener {

        //Define a request code to send to Google Play services
        private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
        private GoogleApiClient mGoogleApiClient;
        private LocationRequest mLocationRequest;
        private double currentLatitude;
        private double currentLongitude;


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

            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    // The next two lines tell the new client that “this” current class will handle connection stuff
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    //fourth line adds the LocationServices API endpoint from GooglePlayServices
                    .addApi(LocationServices.API)
                    .build();

            // Create the LocationRequest object
            mLocationRequest = LocationRequest.create()
                    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                    .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                    .setFastestInterval(1 * 1000); // 1 second, in milliseconds

        }

        @Override
        protected void onResume() {
            super.onResume();
            //Now lets connect to the API
            mGoogleApiClient.connect();
        }

        @Override
        protected void onPause() {
            super.onPause();
            Log.v(this.getClass().getSimpleName(), "onPause()");

            //Disconnect from API onPause()
            if (mGoogleApiClient.isConnected()) {
                LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
                mGoogleApiClient.disconnect();
            }


        }

        /**
         * If connected get lat and long
         * 
         */
        @Override
        public void onConnected(Bundle bundle) {
            Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

            if (location == null) {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

            } else {
                //If everything went fine lets get latitude and longitude
                currentLatitude = location.getLatitude();
                currentLongitude = location.getLongitude();

                Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
            }
        }


        @Override
        public void onConnectionSuspended(int i) {}

        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            /*
             * Google Play services can resolve some errors it detects.
             * If the error has a resolution, try sending an Intent to
             * start a Google Play services activity that can resolve
             * error.
             */
            if (connectionResult.hasResolution()) {
                try {
                    // Start an Activity that tries to resolve the error
                    connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                    /*
                     * Thrown if Google Play services canceled the original
                     * PendingIntent
                     */
                } catch (IntentSender.SendIntentException e) {
                    // Log the error
                    e.printStackTrace();
                }
            } else {
                /*
                 * If no resolution is available, display a dialog to the
                 * user with the error.
                 */
                Log.e("Error", "Location services connection failed with code " + connectionResult.getErrorCode());
            }
        }

        /**
         * If locationChanges change lat and long
         * 
         * 
         * @param location
         */
        @Override
        public void onLocationChanged(Location location) {
            currentLatitude = location.getLatitude();
            currentLongitude = location.getLongitude();

            Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
        }

    }

If you need more info just go to:

The Beginner’s Guide to Location in Android

Note: This doesn't seem to work in the emulator but works just fine on a device

Android layout replacing a view with another view on run time

private void replaceView(View oldV,View newV){
        ViewGroup par = (ViewGroup)oldV.getParent();
        if(par == null){return;}
        int i1 = par.indexOfChild(oldV);
        par.removeViewAt(i1);
        par.addView(newV,i1);
    }

Unable to import a module that is definitely installed

In my case it was a problem with a missing init.py file in the module, that I wanted to import in a Python 2.7 environment.

Python 3.3+ has Implicit Namespace Packages that allow it to create a packages without an init.py file.

How can I read the contents of an URL with Python?

# retrieving data from url
# only for python 3

import urllib.request

def main():
  url = "http://docs.python.org"

# retrieving data from URL
  webUrl = urllib.request.urlopen(url)
  print("Result code: " + str(webUrl.getcode()))

# print data from URL 
  print("Returned data: -----------------")
  data = webUrl.read().decode("utf-8")
  print(data)

if __name__ == "__main__":
  main()

Can't install any package with node npm

npm install <packagename> --registry http://registry.npmjs.org/

Try specifying the registry with the install command. Solved my problem.

Is there a Python equivalent to Ruby's string interpolation?

Python 3.6 will add literal string interpolation similar to Ruby's string interpolation. Starting with that version of Python (which is scheduled to be released by the end of 2016), you will be able to include expressions in "f-strings", e.g.

name = "Spongebob Squarepants"
print(f"Who lives in a Pineapple under the sea? {name}.")

Prior to 3.6, the closest you can get to this is

name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? %(name)s." % locals())

The % operator can be used for string interpolation in Python. The first operand is the string to be interpolated, the second can have different types including a "mapping", mapping field names to the values to be interpolated. Here I used the dictionary of local variables locals() to map the field name name to its value as a local variable.

The same code using the .format() method of recent Python versions would look like this:

name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))

There is also the string.Template class:

tmpl = string.Template("Who lives in a Pineapple under the sea? $name.")
print(tmpl.substitute(name="Spongebob Squarepants"))

Returning JSON from a PHP Script

<?php
$data = /** whatever you're serializing **/;
header("Content-type: application/json; charset=utf-8");
echo json_encode($data);
?>

How do I include a newline character in a string in Delphi?

Here's an even shorter approach:

my_string := 'Hello,'#13#10' world!';

Import one schema into another new schema - Oracle

The issue was with the dmp file itself. I had to re-export the file and the command works fine. Thank you @Justin Cave

SyntaxError: cannot assign to operator

In case it helps someone, if your variables have hyphens in them, you may see this error since hyphens are not allowed in variable names in Python and are used as subtraction operators.

Example:

my-variable = 5   # would result in 'SyntaxError: can't assign to operator'

FlutterError: Unable to load asset

I ran into this issue and very nearly gave up on Flutter until I stumbled upon the cause. In my case what I was doing was along the following lines

static Future<String> resourceText(String resName) async
{
 try
 { 
  ZLibCodec zlc = new ZLibCodec(gzip:false,raw:true,level:9);
  var data= await rootBundle.load('assets/path/to/$resName');
  String result = new 
  String.fromCharCodes(zlc.decode(puzzleData.buffer.asUint8List()));
  return puzzle;
 } catch(e)
 {
  debugPrint('Resource Error $resName $e');
  return ''; 
 } 
}

static Future<String> fallBackText(String textName) async
{
 if (testCondtion) return 'Some Required Text';
 else return resourceText('default');
} 

where Some Required Text was a text string sent back if the testCondition was being met. Failing that I was trying to pick up default text from the app resources and send that back instead. My mistake was in the line return resourceText('default');. After changing it to read return await resourceText('default') things worked just as expected.

This issue arises from the fact that rootBundle.load operates asynchronously. In order to return its results correctly we need to await their availability which I had failed to do. It strikes me as slightly surprising that neither the Flutter VSCode plugin nor the Flutter build process flag up this as an error. While there may well be other reasons why rootBundle.load fails this answer will, hopefully, help others who are running into mysterious asset load failures in Flutter.

POI setting Cell Background to a Custom Color

As pointed in Vlad's answer, you are running out of free color slots. One way to get around that would be to cache the colors: whenever you try a RGB combination, the routine should first check if the combination is in the cache; if it is in the cache, then it should use that one instead of creating a new one from scratch; new colors would then only be created if they're not yet in cache.

Here's the implementation I use; it uses XSSF plus Guava's LoadingCache and is geared towards generationg XSSF colors from CSS rgb(r, g, b) declarations, but it should be relatively trivial to adapt it to HSSF:

    private final LoadingCache<String, XSSFColor> colorsFromCSS = CacheBuilder.newBuilder()
            .build(new CacheLoader<String, XSSFColor>() {

                private final Pattern RGB = Pattern.compile("rgb\\(\\s*(\\d+)\\s*, \\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)");

                @Override
                public XSSFColor load(String style) throws Exception {
                    Matcher mat = RGB.matcher(style);
                    if (!mat.find()) {
                        throw new IllegalStateException("Couldn't read CSS color: " + style);
                    }                       
                    return new XSSFColor(new java.awt.Color(
                            Integer.parseInt(mat.group(1)), 
                            Integer.parseInt(mat.group(2)), 
                            Integer.parseInt(mat.group(3))));
                }

            });

Perhaps someone else could post a HSSF equivalent? ;)

How to make a programme continue to run after log out from ssh?

Start in the background:

./long_running_process options &

And disown the job before you log out:

disown

Controlling a USB power supply (on/off) with Linux

The reason why folks post questions such as this is due to the dreaded- indeed "EVIL"- USB Auto-Suspend "feature".

Auto suspend winds-down the power to an "idle" USB device and unless the device's driver supports this feature correctly, the device can become uncontactable. So powering a USB port on/off is a symptom of the problem, not the problem in itself.

I'll show you how to GLOBALLY disable auto-suspend, negating the need to manually toggle the USB ports on & off:

Short Answer:

You do NOT need to edit "autosuspend_delay_ms" individually: USB autosuspend can be disabled globally and PERSISTENTLY using the following commands:

sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/&usbcore.autosuspend=-1 /' /etc/default/grub

update-grub

systemctl reboot

An Ubuntu 18.04 screen-grab follows at the end of the "Long Answer" illustrating how my results were achieved.

Long Answer:

It's true that the USB Power Management Kernel Documentation states autosuspend is to be deprecated and in in its' place "autosuspend_delay_ms" used to disable USB autosuspend:

"In 2.6.38 the "autosuspend" file will be deprecated
and replaced by the "autosuspend_delay_ms" file."

HOWEVER my testing reveals that setting usbcore.autosuspend=-1 in /etc/default/grub as below can be used as a GLOBAL toggle for USB autosuspend functionality- you do NOT need to edit individual "autosuspend_delay_ms" files.

The same document linked above states a value of "0" is ENABLED and a negative value is DISABLED:

power/autosuspend_delay_ms

    <snip> 0 means to autosuspend
    as soon as the device becomes idle, and negative
    values mean never to autosuspend.  You can write a
    number to the file to change the autosuspend
    idle-delay time.

In the annotated Ubuntu 18.04 screen-grab below illustrating how my results were achieved (and reproducible), please remark the default is "0" (enabled) in autosuspend_delay_ms.

Then note that after ONLY setting usbcore.autosuspend=-1 in Grub, these values are now negative (disabled) after reboot. This will save me the bother of editing individual values and can now script disabling USB autosuspend.

screengrab: autosuspend values Before and after globally editing

Hope this makes disabling USB autosuspend a little easier and more scriptable-

How to post JSON to PHP with curl

Jordans analysis of why the $_POST-array isn't populated is correct. However, you can use

$data = file_get_contents("php://input");

to just retrieve the http body and handle it yourself. See PHP input/output streams.

From a protocol perspective this is actually more correct, since you're not really processing http multipart form data anyway. Also, use application/json as content-type when posting your request.

How to sort by two fields in Java?

Arrays.sort(persons, new PersonComparator());



import java.util.Comparator;

public class PersonComparator implements Comparator<? extends Person> {

    @Override
    public int compare(Person o1, Person o2) {
        if(null == o1 || null == o2  || null == o1.getName() || null== o2.getName() ){
            throw new NullPointerException();
        }else{
            int nameComparisonResult = o1.getName().compareTo(o2.getName());
            if(0 == nameComparisonResult){
                return o1.getAge()-o2.getAge();
            }else{
                return nameComparisonResult;
            }
        }
    }
}


class Person{
    int age; String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Updated version:

public class PersonComparator implements Comparator<? extends Person> {

   @Override
   public int compare(Person o1, Person o2) {

      int nameComparisonResult = o1.getName().compareToIgnoreCase(o2.getName());
      return 0 == nameComparisonResult?o1.getAge()-o2.getAge():nameComparisonResult;

   }
 }

How to force reloading a page when using browser back button?

Currently this is the most up to date way reload page if the user clicks the back button.

const [entry] = performance.getEntriesByType("navigation");

// Show it in a nice table in the developer console
console.table(entry.toJSON());

if (entry["type"] === "back_forward")
    location.reload();

See here for source

How to set standard encoding in Visual Studio

What

It is possible with EditorConfig.

EditorConfig helps developers define and maintain consistent coding styles between different editors and IDEs.

This also includes file encoding.

EditorConfig is built-in Visual Studio 2017 by default, and I there were plugins available for versions as old as VS2012. Read more from EditorConfig Visual Studio Plugin page.

How

You can set up a EditorConfig configuration file high enough in your folder structure to span all your intended repos (up to your drive root should your files be really scattered everywhere) and configure the setting charset:

charset: set to latin1, utf-8, utf-8-bom, utf-16be or utf-16le to control the character set.

You can add filters and exceptions etc on every folder level or by file name/type should you wish for finer control.

Once configured then compatible IDEs should automatically do it's thing to make matching files comform to set rules. Note that Visual Studio does not automatically convert all your files but do its bit when you work with files in IDE (open and save).

What next

While you could have a Visual-studio-wide setup, I strongly suggest to still include an EditorConfig root to your solution version control, so that explicit settings are automatically synced to all team members as well. Your drive root editorconfig file can be the fallback should some project not have their own editorconfig files set up yet.

What is the difference between a Shared Project and a Class Library in Visual Studio 2015?

The difference between a shared project and a class library is that the latter is compiled and the unit of reuse is the assembly.

Whereas with the former, the unit of reuse is the source code, and the shared code is incorporated into each assembly that references the shared project.

This can be useful when you want to create separate assemblies that target specific platforms but still have code that should be shared.

See also here:

The shared project reference shows up under the References node in the Solution Explorer, but the code and assets in the shared project are treated as if they were files linked into the main project.


In previous versions of Visual Studio1, you could share source code between projects by Add -> Existing Item and then choosing to Link. But this was kind of clunky and each separate source file had to be selected individually. With the move to supporting multiple disparate platforms (iOS, Android, etc), they decided to make it easier to share source between projects by adding the concept of Shared Projects.


1 This question and my answer (up until now) suggest that Shared Projects was a new feature in Visual Studio 2015. In fact, they made their debut in Visual Studio 2013 Update 2

What is difference between 'git reset --hard HEAD~1' and 'git reset --soft HEAD~1'?

Git reset has 5 main modes: soft, mixed, merged, hard, keep. The difference between them is to change or not change head, stage (index), working directory.

Git reset --hard will change head, index and working directory.
Git reset --soft will change head only. No change to index, working directory.

So in other words if you want to undo your commit, --soft should be good enough. But after that you still have the changes from bad commit in your index and working directory. You can modify the files, fix them, add them to index and commit again.

With the --hard, you completely get a clean slate in your project. As if there hasn't been any change from the last commit. If you are sure this is what you want then move forward. But once you do this, you'll lose your last commit completely. (Note: there are still ways to recover the lost commit).

Best way to store time (hh:mm) in a database

I would convert them to an integer (HH*3600 + MM*60), and store it that way. Small storage size, and still easy enough to work with.

Install opencv for Python 3.3

A full instruction relating to James Fletcher's answer can be found here

Particularly for Anaconda distribution I had to modify it this way:

 cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D PYTHON3_PACKAGES_PATH=/anaconda/lib/python3.4/site-packages/ \
    -D PYTHON3_LIBRARY=/anaconda/lib/libpython3.4m.dylib \
    -D PYTHON3_INCLUDE_DIR=/anaconda/include/python3.4m \
    -D INSTALL_C_EXAMPLES=ON \
    -D INSTALL_PYTHON_EXAMPLES=ON \
    -D BUILD_EXAMPLES=ON \
    -D BUILD_opencv_python3=ON \
    -D OPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules ..

Last line can be ommited (see link above)

No appenders could be found for logger(log4j)?

I think you should understand where the log4j jar file or the Java code looks for the log4j configuration files.

src/main/resources/log4j.properties is Eclipse path. Place them in a proper location so that you don't have to hard code the absolute path in code.

Read my article and sample solution for that https://askyourquestions.info/how-to-see-where-the-log-is-logger-in-slf4j/

How to make rounded percentages add up to 100%

For those having the percentages in a pandas Series, here is my implemantation of the Largest remainder method (as in Varun Vohra's answer), where you can even select the decimals to which you want to round.

import numpy as np

def largestRemainderMethod(pd_series, decimals=1):

    floor_series = ((10**decimals * pd_series).astype(np.int)).apply(np.floor)
    diff = 100 * (10**decimals) - floor_series.sum().astype(np.int)
    series_decimals = pd_series - floor_series / (10**decimals)
    series_sorted_by_decimals = series_decimals.sort_values(ascending=False)

    for i in range(0, len(series_sorted_by_decimals)):
        if i < diff:
            series_sorted_by_decimals.iloc[[i]] = 1
        else:
            series_sorted_by_decimals.iloc[[i]] = 0

    out_series = ((floor_series + series_sorted_by_decimals) / (10**decimals)).sort_values(ascending=False)

    return out_series

Bulk Insert to Oracle using .NET

Finding the linked examples somewhat confusing, I worked out some code that demonstrates a working array insert into a test table (jkl_test). Here's the table:

create table jkl_test (id number(9));

Here is .Net code for a simple Console application that connects to Oracle using ODP.Net and inserts an array of 5 integers:

using Oracle.DataAccess.Client;

namespace OracleArrayInsertExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Open a connection using ODP.Net
            var connection = new OracleConnection("Data Source=YourDatabase; Password=YourPassword; User Id=YourUser");
            connection.Open();

            // Create an insert command
            var command = connection.CreateCommand();
            command.CommandText = "insert into jkl_test values (:ids)";

            // Set up the parameter and provide values
            var param = new OracleParameter("ids", OracleDbType.Int32);
            param.Value = new int[] { 22, 55, 7, 33, 11 };

            // This is critical to the process; in order for the command to 
            // recognize and bind arrays, an array bind count must be specified.
            // Set it to the length of the array.
            command.ArrayBindCount = 5;
            command.Parameters.Add(param);
            command.ExecuteNonQuery();
        }
    }
}

How to dismiss ViewController in Swift?

Based on my experience, I add a method to dismiss me as extension to UIViewController:

extension UIViewController {
    func dismissMe(animated: Bool, completion: (()->())?) {
        var count = 0
        if let c = self.navigationController?.viewControllers.count {
            count = c
        }
        if count > 1 {
            self.navigationController?.popViewController(animated: animated)
            if let handler = completion {
                handler()
            }
        } else {
            dismiss(animated: animated, completion: completion)
        }
    }
}

Then I call this method to dismiss view controller in any UIViewController subclass. For example, in cancel action:

class MyViewController: UIViewController {
   ...
   @IBAction func cancel(sender: AnyObject) {
     dismissMe(animated: true, completion: nil)
   }
   ...
}

How do I wait until Task is finished in C#?

I'm an async novice, so I can't tell you definitively what is happening here. I suspect that there's a mismatch in the method execution expectations, even though you are using tasks internally in the methods. I think you'd get the results you are expecting if you changed Print to return a Task<string>:

private static string Send(int id)
{
    Task<HttpResponseMessage> responseTask = client.GetAsync("aaaaa");
    Task<string> result;
    responseTask.ContinueWith(x => result = Print(x));
    result.Wait();
    responseTask.Wait(); // There's likely a better way to wait for both tasks without doing it in this awkward, consecutive way.
    return result.Result;
}

private static Task<string> Print(Task<HttpResponseMessage> httpTask)
{
    Task<string> task = httpTask.Result.Content.ReadAsStringAsync();
    string result = string.Empty;
    task.ContinueWith(t =>
    {
        Console.WriteLine("Result: " + t.Result);
        result = t.Result;
    });
    return task;
}

Undefined symbols for architecture x86_64 on Xcode 6.1

I solved the same issue by going to Xcode Build Settings and in Architectures, I changed the Xcode 6.1.1 standard architecture to:-

$(ARCHS_STANDARD_32_BIT)

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

I had a similar problem with 'org.codehaus.mojo'-'jaxws-maven-plugin': could not resolve dependencies. Fortunately, I was able to do a Project > Clean in Eclipse, which resolved the issue.

java.io.FileNotFoundException: (Access is denied)

Here's a gotcha that I just discovered - perhaps it might help someone else. If using windows the classes folder must not have encryption enabled! Tomcat doesn't seem to like that. Right click on the classes folder, select "Properties" and then click the "Advanced..." button. Make sure the "Encrypt contents to secure data" checkbox is cleared. Restart Tomcat.

It worked for me so here's hoping it helps someone else, too.

Pausing a batch file for amount of time

If choice is available, use this:

choice /C X /T 10 /D X > nul

where /T 10 is the number of seconds to delay. Note the syntax can vary depending on your Windows version, so use CHOICE /? to be sure.

Get a list of checked checkboxes in a div using jQuery

Would this do?

var selected = [];
$('div#checkboxes input[type=checkbox]').each(function() {
   if ($(this).is(":checked")) {
       selected.push($(this).attr('name'));
   }
});

How to check whether an object is a date?

Also you can use short form

function getClass(obj) {
  return {}.toString.call(obj).slice(8, -1);
}
alert( getClass(new Date) ); //Date

or something like this:

(toString.call(date)) == 'Date'

How to disable registration new users in Laravel

Method 1 for version 5.3

In laravel 5.3 don't have AuthController. to disable register route you should change in constructor of RegisterController like this:

You can change form:

public function __construct()
{

    $this->middleware('guest');

}

to:

use Illuminate\Support\Facades\Redirect;

public function __construct()
{

    Redirect::to('/')->send();

}

Note: for use Redirect don't forget to user Redirect; So user access to https://host_name/register it's redirect to "/".

Method 2 for version 5.3

When we use php artisan make:auth it's added Auth::route(); automatically. Please Override Route in /routes/web.php. You can change it's like this: * you need to comment this line: Auth::routes();

    <?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/


// Auth::routes();
Route::get('/login', 'Auth\LoginController@showLoginForm' );
Route::post('/login', 'Auth\LoginController@login');
Route::post('/logout', 'Auth\LoginController@logout');

Route::get('/home', 'HomeController@index');

Thanks! I hope it's can solve your problems.

cmd line rename file with date and time

I took the above but had to add one more piece because it was putting a space after the hour which gave a syntax error with the rename command. I used:

    set HR=%time:~0,2%
    set HR=%Hr: =0% 
    set HR=%HR: =%
    rename c:\ops\logs\copyinvoices.log copyinvoices_results_%date:~10,4%-%date:~4,2%-%date:~7,2%_%HR%%time:~3,2%.log 

This gave me my format I needed: copyinvoices_results_2013-09-13_0845.log

Java LinkedHashMap get first or last entry

public static List<Fragment> pullToBackStack() {
    List<Fragment> fragments = new ArrayList<>();
    List<Map.Entry<String, Fragment>> entryList = new ArrayList<>(backMap.entrySet());
    int size = entryList.size();
    if (size > 0) {
        for (int i = size - 1; i >= 0; i--) {// last Fragments
            fragments.add(entryList.get(i).getValue());
            backMap.remove(entryList.get(i).getKey());
        }
        return fragments;
    }
    return null;
}

How do you show animated GIFs on a Windows Form (c#)

Public Class Form1

    Private animatedimage As New Bitmap("C:\MyData\Search.gif")
    Private currentlyanimating As Boolean = False

    Private Sub OnFrameChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

        Me.Invalidate()

    End Sub

    Private Sub AnimateImage()

        If currentlyanimating = True Then
            ImageAnimator.Animate(animatedimage, AddressOf Me.OnFrameChanged)
            currentlyanimating = False
        End If

    End Sub

    Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)

        AnimateImage()
        ImageAnimator.UpdateFrames(animatedimage)
        e.Graphics.DrawImage(animatedimage, New Point((Me.Width / 4) + 40, (Me.Height / 4) + 40))

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        BtnStop.Enabled = False

    End Sub

    Private Sub BtnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStop.Click

        currentlyanimating = False
        ImageAnimator.StopAnimate(animatedimage, AddressOf Me.OnFrameChanged)
        BtnStart.Enabled = True
        BtnStop.Enabled = False

    End Sub

    Private Sub BtnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStart.Click

        currentlyanimating = True
        AnimateImage()
        BtnStart.Enabled = False
        BtnStop.Enabled = True

    End Sub

End Class

How can I pass an argument to a PowerShell script?

# ENTRY POINT MAIN()
Param(
    [Parameter(Mandatory=$True)]
    [String] $site,
    [Parameter(Mandatory=$True)]
    [String] $application,
    [Parameter(Mandatory=$True)]
    [String] $dir,
    [Parameter(Mandatory=$True)]
    [String] $applicationPool
)

# Create Web IIS Application
function ValidateWebSite ([String] $webSiteName)
{
    $iisWebSite = Get-Website -Name $webSiteName
    if($Null -eq $iisWebSite)
    {
        Write-Error -Message "Error: Web Site Name: $($webSiteName) not exists."  -Category ObjectNotFound
    }
    else
    {
        return 1
    }
}

# Get full path from IIS WebSite
function GetWebSiteDir ([String] $webSiteName)
{
    $iisWebSite = Get-Website -Name $webSiteName
    if($Null -eq $iisWebSite)
    {
        Write-Error -Message "Error: Web Site Name: $($webSiteName) not exists."  -Category ObjectNotFound
    }
    else
    {
        return $iisWebSite.PhysicalPath
    }
}

# Create Directory
function CreateDirectory([string]$fullPath)
{
    $existEvaluation = Test-Path $fullPath -PathType Any
    if($existEvaluation -eq $false)
    {
        new-item $fullPath -itemtype directory
    }
    return 1
}

function CreateApplicationWeb
{
    Param(
        [String] $WebSite,
        [String] $WebSitePath,
        [String] $application,
        [String] $applicationPath,
        [String] $applicationPool
        )
    $fullDir = "$($WebSitePath)\$($applicationPath)"
    CreateDirectory($fullDir)
    New-WebApplication -Site $WebSite -Name $application -PhysicalPath $fullDir -ApplicationPool $applicationPool -Force
}

$fullWebSiteDir = GetWebSiteDir($Site)f($null -ne $fullWebSiteDir)
{
    CreateApplicationWeb -WebSite $Site -WebSitePath $fullWebSiteDir -application $application  -applicationPath $dir -applicationPool $applicationPool
}

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

If you want to use rollback, then use start transaction and otherwise forget all those things,

By default, MySQL automatically commits the changes to the database.

To force MySQL not to commit these changes automatically, execute following:

SET autocommit = 0;
//OR    
SET autocommit = OFF

To enable the autocommit mode explicitly:

SET autocommit = 1;
//OR    
SET autocommit = ON;

Android WebView style background-color:transparent ignored on android 2.2

This didn't work,

android:background="@android:color/transparent"

Setting the webview background color as worked

webView.setBackgroundColor(0)

Additionally, I set window background drawable as transparent

Utils to read resource text file to String (Java)

Here's a solution using Java 11's Files.readString:

public class Utils {
    public static String readResource(String name) throws URISyntaxException, IOException {
        var uri = Utils.class.getResource("/" + name).toURI();
        var path = Paths.get(uri);
        return Files.readString(path);
    }
}

Persistent invalid graphics state error when using ggplot2

I found this to occur when you mix ggplot charts with plot charts in the same session. Using the 'dev.off' solution suggested by Paul solves the issue.

Can a normal Class implement multiple interfaces?

public class A implements C,D {...} valid

this is the way to implement multiple inheritence in java

C# DataRow Empty-check

I prefer approach of Tommy Carlier, but with a little change.

foreach (DataColumn column in row.Table.Columns)
    if (!row.IsNull(column))
      return false;

  return true;

I suppose this approach looks more simple and bright.

Logcat not displaying my log calls

Probably it's not be correct, and a little bit longer, but I solved this problem (Android Studio) by using this:

System.out.println("Some text here");

Like this:

try {
       ...code here...
} catch(Exception e) {
  System.out.println("Error desc: " + e.getMessage());
}

ios Upload Image and Text using HTTP POST

use below code. it will work fine for me.

+(void) sendHttpRequestWithArrayContent:(NSMutableArray *) array 
ToUrl:(NSString *) strUrl withHttpMethod:(NSString *) strMethod 
withBlock:(dictionary)block
{
if (![Utility isConnectionAvailableWithAlert:TRUE])
{
    [Utility showAlertWithTitle:@"" andMessage:@"No internet connection available"];
}


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;

[request setURL:[NSURL URLWithString:strUrl]];
[request setTimeoutInterval:120.0];
[request setHTTPMethod:strMethod];

NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body=[[NSMutableData alloc]init];

for (NSMutableDictionary *dict in array)
{
    if ([[dict valueForKey:[[dict allKeys]objectAtIndex:0]] isKindOfClass:[NSString class]])
    {
        [body appendData:[self contentDataFormStringWithValue:[dict valueForKey:[[dict allKeys]objectAtIndex:0]] withKey:[[dict allKeys]objectAtIndex:0]]];
    }
    else if ([[dict valueForKey:[[dict allKeys]objectAtIndex:0]] isKindOfClass:[UIImage class]])
    {
        [body appendData:[self contentDataFormImage:[dict valueForKey:[[dict allKeys]objectAtIndex:0]] withKey:[[dict allKeys]objectAtIndex:0]]];
    }
    else if ([[dict valueForKey:[[dict allKeys]objectAtIndex:0]] isKindOfClass:[NSMutableDictionary class]])
    {
        [body appendData:[self contentDataFormStringWithValue:[dict valueForKey:[[dict allKeys]objectAtIndex:0]] withKey:[[dict allKeys]objectAtIndex:0]]];
    }
    else
    {
        NSMutableData *dataBody = [NSMutableData data];
        [dataBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [dataBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"ipodfile.jpg\"\r\n",@"image"] dataUsingEncoding:NSUTF8StringEncoding]];
        [dataBody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

        [dataBody appendData:[dict valueForKey:[[dict allKeys]objectAtIndex:0]]];

        [body appendData:dataBody];
    }
}

[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:body];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
 {
     if (!data) {
         NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
          [dict setObject:[NSString stringWithFormat:@"%@",SomethingWentWrong] forKey:@"error"];
         block(dict);
         return ;
     }
     NSError *error = nil;
    // NSString *str=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
     NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
     NSLog(@"%@",dict);
     if (!dict) {
         NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
         [dict setObject:ServerResponceError forKey:@"error"];
         block(dict);
         return ;
     }
     block(dict);

 }];

}
+(NSMutableData*) contentDataFormStringWithValue:(NSString*)strValue 
withKey:(NSString *) key
{
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSMutableData *data=[[NSMutableData alloc]init];
[data appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key] dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[[NSString stringWithFormat:@"%@",strValue] dataUsingEncoding:NSUTF8StringEncoding]];  // title
return data;
}

+(NSMutableData*) contentDataFormImage:(UIImage*)image withKey:
(NSString *) key
{
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"ipodfile.jpg\"\r\n",key] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
NSData *imageData=UIImageJPEGRepresentation(image, 0.40);
[body appendData:imageData];

return body;
}

How to add items into a numpy array

import numpy as np
a = np.array([[1,3,4],[1,2,3],[1,2,1]])
b = np.array([10,20,30])
c = np.hstack((a, np.atleast_2d(b).T))

returns c:

array([[ 1,  3,  4, 10],
       [ 1,  2,  3, 20],
       [ 1,  2,  1, 30]])

How can I kill all sessions connecting to my oracle database?

I've been using something like this for a while to kill my sessions on a shared server. The first line of the 'where' can be removed to kill all non 'sys' sessions:

BEGIN
  FOR c IN (
      SELECT s.sid, s.serial#
      FROM v$session s
      WHERE (s.Osuser = 'MyUser' or s.MACHINE = 'MyNtDomain\MyMachineName')
      AND s.USERNAME <> 'SYS'
      AND s.STATUS <> 'KILLED'
  )
  LOOP
      EXECUTE IMMEDIATE 'alter system kill session ''' || c.sid || ',' || c.serial# || '''';
  END LOOP;
END;

Abstract variables in Java?

Use enums to force values as well to keep bound checks:

enum Speed {
    HIGH, LOW;
}
private abstract  class SuperClass {
    Speed speed;
    SuperClass(Speed speed) {
        this.speed = speed;
    }
}
private class ChildClass extends SuperClass {
    ChildClass(Speed speed) {
        super(speed);
    }
}

HTTP Request in Swift with POST method

let session = URLSession.shared
        let url = "http://...."
        let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        var params :[String: Any]?
        params = ["Some_ID" : "111", "REQUEST" : "SOME_API_NAME"]
        do{
            request.httpBody = try JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions())
            let task = session.dataTask(with: request as URLRequest as URLRequest, completionHandler: {(data, response, error) in
                if let response = response {
                    let nsHTTPResponse = response as! HTTPURLResponse
                    let statusCode = nsHTTPResponse.statusCode
                    print ("status code = \(statusCode)")
                }
                if let error = error {
                    print ("\(error)")
                }
                if let data = data {
                    do{
                        let jsonResponse = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions())
                        print ("data = \(jsonResponse)")
                    }catch _ {
                        print ("OOps not good JSON formatted response")
                    }
                }
            })
            task.resume()
        }catch _ {
            print ("Oops something happened buddy")
        }

Getting attribute using XPath

If you are using PostgreSQL, this is the right way to get it. This is just an assumption where as you have a book table TITLE and PRICE column with populated data. Here's the query

SELECT xpath('/bookstore/book/title/@lang', xmlforest(book.title AS title, book.price AS price), ARRAY[ARRAY[]::TEXT[]]) FROM book LIMIT 1;

Javascript Date - set just the date, ignoring time?

_x000D_
_x000D_
new Date((new Date("07/06/2012 13:30")).toDateString())
_x000D_
_x000D_
_x000D_

Get filename in batch for loop

I am a little late but I used this:

dir /B *.* > dir_file.txt

then you can make a simple FOR loop to extract the file name and use them. e.g:

for /f "tokens=* delims= " %%a in (dir_file.txt) do (
gawk -f awk_script_file.awk %%a
)

or store them into Vars (!N1!, !N2!..!Nn!) for later use. e.g:

set /a N=0
for /f "tokens=* delims= " %%a in (dir_file.txt) do (
set /a N+=1
set v[!N!]=%%a
)

Xcode error - Thread 1: signal SIGABRT

SIGABRT is, as stated in other answers, a general uncaught exception. You should definitely learn a little bit more about Objective-C. The problem is probably in your UITableViewDelegate method didSelectRowAtIndexPath.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

I can't tell you much more until you show us something of the code where you handle the table data source and delegate methods.

Is it safe to store a JWT in localStorage with ReactJS?

Isn't neither localStorage or httpOnly cookie acceptable? In regards to a compromised 3rd party library, the only solution I know of that will reduce / prevent sensitive information from being stolen would be enforced Subresource Integrity.

Subresource Integrity (SRI) is a security feature that enables browsers to verify that resources they fetch (for example, from a CDN) are delivered without unexpected manipulation. It works by allowing you to provide a cryptographic hash that a fetched resource must match.

As long as the compromised 3rd party library is active on your website, a keylogger can start collecting info like username, password, and whatever else you input into the site.

An httpOnly cookie will prevent access from another computer but will do nothing to prevent the hacker from manipulating the user's computer.

How to check if a process is in hang state (Linux)

What do you mean by ‘hang state’? Typically, a process that is unresponsive and using 100% of a CPU is stuck in an endless loop. But there's no way to determine whether that has happened or whether the process might not eventually reach a loop exit state and carry on.

Desktop hang detectors just work by sending a message to the application's event loop and seeing if there's any response. If there's not for a certain amount of time they decide the app has ‘hung’... but it's entirely possible it was just doing something complicated and will come back to life in a moment once it's done. Anyhow, that's not something you can use for any arbitrary process.

Getting full URL of action in ASP.NET MVC

I was having an issue with this, my server was running behind a load balancer. The load balancer was terminating the SSL/TLS connection. It then passed the request to the web servers using http.

Using the Url.Action() method with Request.Url.Schema, it kept creating a http url, in my case to create a link in an automated email (which my PenTester didn't like).

I may have cheated a little, but it is exactly what I needed to force a https url:

<a href="@Url.Action("Action", "Controller", new { id = Model.Id }, "https")">Click Here</a>

I actually use a web.config AppSetting so I can use http when debugging locally, but all test and prod environments use transformation to set the https value.

After MySQL install via Brew, I get the error - The server quit without updating PID file

Please check the log , you will get more detailed information .

Use the below command to tail the error log

tail -100 /usr/local/var/mysql/<user_name>.local.err

For me , one of the directory is missing , once created the server has started .

What's the function like sum() but for multiplication? product()?

Perhaps not a "builtin", but I consider it builtin. anyways just use numpy

import numpy 
prod_sum = numpy.prod(some_list)

How to check if a date is greater than another in Java?

You can use Date.before() or Date.after() or Date.equals() for date comparison.

Taken from here:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDiff {

    public static void main( String[] args )
    {
        compareDates("2017-01-13 00:00:00", "2017-01-14 00:00:00");// output will be Date1 is before Date2
        compareDates("2017-01-13 00:00:00", "2017-01-12 00:00:00");//output will be Date1 is after Date2
        compareDates("2017-01-13 00:00:00", "2017-01-13 10:20:30");//output will be Date1 is before Date2 because date2 is ahead of date 1 by 10:20:30 hours
        compareDates("2017-01-13 00:00:00", "2017-01-13 00:00:00");//output will be Date1 is equal Date2 because both date and time are equal
    }

    public static void compareDates(String d1,String d2)
    {
        try{
            // If you already have date objects then skip 1

            //1
            // Create 2 dates starts
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = sdf.parse(d1);
            Date date2 = sdf.parse(d2);

            System.out.println("Date1"+sdf.format(date1));
            System.out.println("Date2"+sdf.format(date2));System.out.println();

            // Create 2 dates ends
            //1

            // Date object is having 3 methods namely after,before and equals for comparing
            // after() will return true if and only if date1 is after date 2
            if(date1.after(date2)){
                System.out.println("Date1 is after Date2");
            }
            // before() will return true if and only if date1 is before date2
            if(date1.before(date2)){
                System.out.println("Date1 is before Date2");
            }

            //equals() returns true if both the dates are equal
            if(date1.equals(date2)){
                System.out.println("Date1 is equal Date2");
            }

            System.out.println();
        }
        catch(ParseException ex){
            ex.printStackTrace();
        }
    }

    public static void compareDates(Date date1,Date date2)
    {
        // if you already have date objects then skip 1
        //1

        //1

        //date object is having 3 methods namely after,before and equals for comparing
        //after() will return true if and only if date1 is after date 2
        if(date1.after(date2)){
            System.out.println("Date1 is after Date2");
        }

        //before() will return true if and only if date1 is before date2
        if(date1.before(date2)){
            System.out.println("Date1 is before Date2");
        }

        //equals() returns true if both the dates are equal
        if(date1.equals(date2)){
            System.out.println("Date1 is equal Date2");
        }

        System.out.println();
    }
}

fork and exec in bash

How about:

(sleep 5; echo "Hello World") &

Graphical user interface Tutorial in C

You can also have a look at FLTK (C++ and not plain C though)

FLTK (pronounced "fulltick") is a cross-platform C++ GUI toolkit for UNIX®/Linux® (X11), Microsoft® Windows®, and MacOS® X. FLTK provides modern GUI functionality without the bloat and supports 3D graphics via OpenGL® and its built-in GLUT emulation.

FLTK is designed to be small and modular enough to be statically linked, but works fine as a shared library. FLTK also includes an excellent UI builder called FLUID that can be used to create applications in minutes.

Here are some quickstart screencasts

[Happy New Year!]

Is either GET or POST more secure than the other?

Disclaimer: Following points are only applicable for API calls and not the website URLs.

Security over the network: You must use HTTPS. GET and POST are equally safe in this case.

Browser History: For front-end applications like, Angular JS, React JS etc API calls are AJAX calls made by front-end. These does not become part of browser history. Hence, POST and GET are equally secure.

Server side logs: With using write set of data-masking and access logs format it is possible to hide all or only sensitive data from request-URL.

Data visibility in browser console: For someone with mallicious intent, it's almost the same efforts to view POST data as much as GET.

Hence, with right logging practices, GET API is as secure as POST API. Following POST everywhere, forces poor API definitions and should be avoided.

How to access private data members outside the class without making "friend"s?

Here's a way, not recommended though

class Weak {
private:
    string name;

public:
    void setName(const string& name) {
        this->name = name;
    }

    string getName()const {
        return this->name;
    }

};

struct Hacker {
    string name;
};

int main(int argc, char** argv) {

    Weak w;
    w.setName("Jon");
    cout << w.getName() << endl;
    Hacker *hackit = reinterpret_cast<Hacker *>(&w);
    hackit->name = "Jack";
    cout << w.getName() << endl;

}

How to get the client IP address in PHP

$_SERVER['REMOTE_ADDR'] may not actually contain real client IP addresses, as it will give you a proxy address for clients connected through a proxy, for example. That may well be what you really want, though, depending what your doing with the IPs. Someone's private RFC1918 address may not do you any good if you're say, trying to see where your traffic is originating from, or remembering what IP the user last connected from, where the public IP of the proxy or NAT gateway might be the more appropriate to store.

There are several HTTP headers like X-Forwarded-For which may or may not be set by various proxies. The problem is that those are merely HTTP headers which can be set by anyone. There's no guarantee about their content. $_SERVER['REMOTE_ADDR'] is the actual physical IP address that the web server received the connection from and that the response will be sent to. Anything else is just arbitrary and voluntary information. There's only one scenario in which you can trust this information: you are controlling the proxy that sets this header. Meaning only if you know 100% where and how the header was set should you heed it for anything of importance.

Having said that, here's some sample code:

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
    $ip = $_SERVER['REMOTE_ADDR'];
}

Editor's note: Using the above code has security implications. The client can set all HTTP header information (ie. $_SERVER['HTTP_...) to any arbitrary value it wants. As such it's far more reliable to use $_SERVER['REMOTE_ADDR'], as this cannot be set by the user.

From: http://roshanbh.com.np/2007/12/getting-real-ip-address-in-php.html

Using 'starts with' selector on individual class names

If an element has multiples classes "[class^='apple-']" dosen't work, e.g.

<div class="fruits apple-monkey"></div>

Updating address bar with new URL without hash or reloading the page

Update to Davids answer to even detect browsers that do not support pushstate:

if (history.pushState) {
  window.history.pushState("object or string", "Title", "/new-url");
} else {
  document.location.href = "/new-url";
}

How do I tell matplotlib that I am done with a plot?

There is a clear figure command, and it should do it for you:

plt.clf()

If you have multiple subplots in the same figure

plt.cla()

clears the current axes.

How do I bind Twitter Bootstrap tooltips to dynamically created elements?

I found a combination of these answers gave me the best outcome - allowing me to still position the tooltip and attach it to the relevant container:

$('body').on('mouseenter', '[rel=tooltip]', function(){
  var el = $(this);
  if (el.data('tooltip') === undefined) {
    el.tooltip({
      placement: el.data("placement") || "top",
      container: el.data("container") || false
    });
  }
  el.tooltip('show');
});

$('body').on('mouseleave', '[rel=tooltip]', function(){
  $(this).tooltip('hide');
});

Relevant HTML:

<button rel="tooltip" class="btn" data-placement="bottom" data-container=".some-parent" title="Show Tooltip">
    <i class="icon-some-icon"></i>
</button>

Google Chrome "window.open" workaround?

This worked for me:

newwindow = window.open(url, "_blank", "resizable=yes, scrollbars=yes, titlebar=yes, width=800, height=900, top=10, left=10");

Object of class mysqli_result could not be converted to string in

Try with:

$row = mysqli_fetch_assoc($result);
echo "my result <a href='data/" . htmlentities($row['classtype'], ENT_QUOTES, 'UTF-8') . ".php'>My account</a>";

Format numbers to strings in Python

You can use following to achieve desired functionality

"%d:%d:d" % (hours, minutes, seconds)

How do you do dynamic / dependent drop downs in Google Sheets?

Caution! The scripts have a limit: it handles up to 500 values in a single drop-down list.

Multi-line, multi-Level, multi-List, multi-Edit-Line Dependent Drop-Down Lists in Google Sheets. Script

More Info


This solution is not perfect, but it gives some benefits:

  1. Let you make multiple dropdown lists
  2. Gives more control
  3. Source Data is placed on the only sheet, so it's simple to edit

First of all, here's working example, so you can test it before going further.

When you choose one option, script makes new validation rule

Installation:

  1. Prepare Data
  2. Make the first list as usual: Data > Validation
  3. Add Script, set some variables
  4. Done!

Prepare Data

Data looks like a single table with all possible variants inside it. It must be located on a separate sheet, so it can be used by the script. Look at this example:

Sourse Data

Here we have four levels, each value repeats. Note that 2 columns on the right of data are reserved, so don't type/paste there any data.


First simple Data Validation (DV)

Prepare a list of unique values. In our example, it is a list of Planets. Find free space on sheet with data, and paste formula: =unique(A:A) On your mainsheet select first column, where DV will start. Go to Data > Validation and select range with a unique list.

4 columns right from data


Script

Paste this code into script editor:

_x000D_
_x000D_
function onEdit(event) _x000D_
{_x000D_
_x000D_
  // Change Settings:_x000D_
  //--------------------------------------------------------------------------------------_x000D_
  var TargetSheet = 'Main'; // name of sheet with data validation_x000D_
  var LogSheet = 'Data1'; // name of sheet with data_x000D_
  var NumOfLevels = 4; // number of levels of data validation_x000D_
  var lcol = 2; // number of column where validation starts; A = 1, B = 2, etc._x000D_
  var lrow = 2; // number of row where validation starts_x000D_
  var offsets = [1,1,1,2]; // offsets for levels_x000D_
  //                   ^ means offset column #4 on one position right._x000D_
  _x000D_
  // =====================================================================================_x000D_
  SmartDataValidation(event, TargetSheet, LogSheet, NumOfLevels, lcol, lrow, offsets);_x000D_
  _x000D_
  // Change Settings:_x000D_
  //--------------------------------------------------------------------------------------_x000D_
  var TargetSheet = 'Main'; // name of sheet with data validation_x000D_
  var LogSheet = 'Data2'; // name of sheet with data_x000D_
  var NumOfLevels = 7; // number of levels of data validation_x000D_
  var lcol = 9; // number of column where validation starts; A = 1, B = 2, etc._x000D_
  var lrow = 2; // number of row where validation starts_x000D_
  var offsets = [1,1,1,1,1,1,1]; // offsets for levels_x000D_
  // =====================================================================================  _x000D_
  SmartDataValidation(event, TargetSheet, LogSheet, NumOfLevels, lcol, lrow, offsets);_x000D_
_x000D_
  _x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
function SmartDataValidation(event, TargetSheet, LogSheet, NumOfLevels, lcol, lrow, offsets) _x000D_
{_x000D_
  //--------------------------------------------------------------------------------------_x000D_
  // The event handler, adds data validation for the input parameters_x000D_
  //--------------------------------------------------------------------------------------_x000D_
  _x000D_
  var FormulaSplitter = ';'; // depends on regional setting, ';' or ',' works for US_x000D_
  //--------------------------------------------------------------------------------------_x000D_
  _x000D_
  // ===================================   key variables  =================================_x000D_
  //_x000D_
  //  ss   sheet we change (TargetSheet)_x000D_
  //   br    range to change_x000D_
  //   scol   number of column to edit_x000D_
  //   srow   number of row to edit _x000D_
  //   CurrentLevel level of drop-down, which we change_x000D_
  //   HeadLevel  main level_x000D_
  //   r    current cell, which was changed by user_x000D_
  //   X           number of levels could be checked on the right_x000D_
  //_x000D_
  //  ls   Data sheet (LogSheet)_x000D_
  //_x000D_
  //    ======================================================================================_x000D_
_x000D_
// Checks_x000D_
var ts = event.source.getActiveSheet();_x000D_
var sname = ts.getName(); _x000D_
if (sname !== TargetSheet) { return -1;  } // not main sheet_x000D_
// Test if range fits_x000D_
var br = event.range;_x000D_
var scol = br.getColumn(); // the column number in which the change is made_x000D_
var srow = br.getRow() // line number in which the change is made_x000D_
var ColNum = br.getWidth();_x000D_
_x000D_
if ((scol + ColNum - 1) < lcol) { return -2; }  // columns... _x000D_
if (srow < lrow) { return -3; } // rows_x000D_
// Test range is in levels_x000D_
var columnsLevels = getColumnsOffset_(offsets, lcol); // Columns for all levels _x000D_
var CurrentLevel = getCurrentLevel_(ColNum, br, scol, columnsLevels);_x000D_
if(CurrentLevel === 1) { return -4; } // out of data validations_x000D_
if(CurrentLevel > NumOfLevels) { return -5; } // last level _x000D_
_x000D_
_x000D_
/*_x000D_
 ts - sheet with validation, sname = name of sheet_x000D_
 _x000D_
      NumOfLevels = 4                     _x000D_
      offsets = [1,1,1,2] - last offset is 2 because need to skip 1 column_x000D_
      columnsLevels = [4,5,6,8] - Columns of validation_x000D_
      _x000D_
          Columns 7 is skipped_x000D_
          |_x000D_
    1 2  3   4    5    6    7    8    9    _x000D_
 |----+----+----+----+----+----+----+----+----+_x000D_
1 |  |    |    |    |    |    |  x |    |    |_x000D_
 |----+----+----+----+----+----+----+----+----+_x000D_
2 |  |    |    |  v |  V |  ? |  x |  ? |    | lrow = 2 - number of row where validation starts_x000D_
 |----+----+----+----+----+----+----+----+----+_x000D_
3 |  |    |    |    |    |    |  x |    |    |_x000D_
 |----+----+----+----+----+----+----+----+----+_x000D_
4 |  |    |    |    |    |    |  x |    |    |_x000D_
 |----+----+----+----+----+----+----+----+----+_x000D_
       |  |   |     |           |_x000D_
       |  |   |     | Currentlevel = 3 - the number of level to change_x000D_
       |  |   |                 |_x000D_
       |  |   | br - cell, user changes: scol - column, srow - row,_x000D_
       |  |          ColNum = 1 - width   _x000D_
       |__|________   _.....____|_x000D_
       |         v_x000D_
       |  Drop-down lists     _x000D_
       |_x000D_
       | lcol = 4 - number of column where validation starts_x000D_
*/_x000D_
// Constants_x000D_
var ReplaceCommas = getDecimalMarkIsCommaLocals(); // // ReplaceCommas = true if locale uses commas to separate decimals_x000D_
var ls = SpreadsheetApp.getActive().getSheetByName(LogSheet); // Data sheet                    _x000D_
var RowNum = br.getHeight();_x000D_
/*  Adjust the range 'br' _x000D_
    ???       !_x000D_
 xxx       x_x000D_
 xxx       x _x000D_
 xxx  =>   x_x000D_
 xxx       x_x000D_
 xxx       x_x000D_
*/ _x000D_
br = ts.getRange(br.getRow(), columnsLevels[CurrentLevel - 2], RowNum); _x000D_
// Levels_x000D_
var HeadLevel = CurrentLevel - 1; // main level_x000D_
var X = NumOfLevels - CurrentLevel + 1; // number of levels left       _x000D_
// determine columns on the sheet "Data"_x000D_
var KudaCol = NumOfLevels + 2;_x000D_
var KudaNado = ls.getRange(1, KudaCol);  // 1 place for a formula_x000D_
var lastRow = ls.getLastRow();_x000D_
var ChtoNado = ls.getRange(1, KudaCol, lastRow, KudaCol); // the range with list, returned by a formula_x000D_
_x000D_
// ============================================================================= > loop >_x000D_
var CurrLevelBase = CurrentLevel; // remember the first current level_x000D_
_x000D_
_x000D_
_x000D_
for (var j = 1; j <= RowNum; j++) // [01] loop rows start_x000D_
{    _x000D_
  // refresh first val  _x000D_
  var currentRow = br.getCell(j, 1).getRow();      _x000D_
  loopColumns_(HeadLevel, X, currentRow, NumOfLevels, CurrLevelBase, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts);_x000D_
} // [01] loop rows end_x000D_
_x000D_
       _x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function getColumnsOffset_(offsets, lefColumn)_x000D_
{_x000D_
// Columns for all levels_x000D_
var columnsLevels = [];_x000D_
var totalOffset = 0; _x000D_
for (var i = 0, l = offsets.length; i < l; i++)_x000D_
{ _x000D_
 totalOffset += offsets[i];_x000D_
 columnsLevels.push(totalOffset + lefColumn - 1);_x000D_
} _x000D_
_x000D_
return columnsLevels;_x000D_
_x000D_
}_x000D_
_x000D_
function test_getCurrentLevel()_x000D_
{_x000D_
  var br = SpreadsheetApp.getActive().getActiveSheet().getRange('A5:C5');_x000D_
  var scol = 1;_x000D_
  _x000D_
  _x000D_
  /*_x000D_
        |  1  |  2  |  3  |  4  |  5  |  6  |  7  |  8  |_x000D_
  range |xxxxx| _x000D_
   dv range |xxxxxxxxxxxxxxxxx|_x000D_
 levels    1     2     3_x000D_
  level          2_x000D_
  _x000D_
  */_x000D_
  Logger.log(getCurrentLevel_(1, br, scol, [1,2,3])); // 2_x000D_
  _x000D_
  /*_x000D_
        |  1  |  2  |  3  |  4  |  5  |  6  |  7  |  8  |_x000D_
  range |xxxxxxxxxxx| _x000D_
   dv range |xxxxx|     |xxxxx|     |xxxxx|_x000D_
 levels    1           2           3_x000D_
  level                2_x000D_
  _x000D_
  */  _x000D_
  Logger.log(getCurrentLevel_(2, br, scol, [1,3,5])); // 2_x000D_
  _x000D_
  /*_x000D_
        |  1  |  2  |  3  |  4  |  5  |  6  |  7  |  8  |_x000D_
  range |xxxxxxxxxxxxxxxxx| _x000D_
   dv range |xxxxx|                 |xxxxxxxxxxx| _x000D_
 levels    1                       2     3_x000D_
  level                            2_x000D_
  _x000D_
  */    _x000D_
  Logger.log(getCurrentLevel_(3, br, scol, [1,5,6])); // 2_x000D_
  _x000D_
  _x000D_
  /*_x000D_
        |  1  |  2  |  3  |  4  |  5  |  6  |  7  |  8  |_x000D_
  range |xxxxxxxxxxxxxxxxx| _x000D_
   dv range |xxxxxxxxxxx|                             |xxxxx| _x000D_
 levels    1     2                                   3_x000D_
  level                                              3_x000D_
  _x000D_
  */    _x000D_
  Logger.log(getCurrentLevel_(3, br, scol, [1,2,8])); // 3_x000D_
  _x000D_
  _x000D_
  /*_x000D_
        |  1  |  2  |  3  |  4  |  5  |  6  |  7  |  8  |_x000D_
  range |xxxxxxxxxxxxxxxxx| _x000D_
   dv range |xxxxxxxxxxxxxxxxx|_x000D_
 levels    1     2     3_x000D_
  level                      4 (error)_x000D_
  _x000D_
  */    _x000D_
  Logger.log(getCurrentLevel_(3, br, scol, [1,2,3]));_x000D_
  _x000D_
  _x000D_
  /*_x000D_
        |  1  |  2  |  3  |  4  |  5  |  6  |  7  |  8  |_x000D_
  range |xxxxxxxxxxxxxxxxx| _x000D_
   dv range                         |xxxxxxxxxxxxxxxxx|_x000D_
 levels    _x000D_
  level    1 (error)                      _x000D_
  _x000D_
  */    _x000D_
  Logger.log(getCurrentLevel_(3, br, scol, [5,6,7])); // 1 _x000D_
  _x000D_
}_x000D_
_x000D_
_x000D_
function getCurrentLevel_(ColNum, br, scol, columnsLevels)_x000D_
{_x000D_
var colPlus = 2; // const_x000D_
if (ColNum === 1) { return columnsLevels.indexOf(scol) + colPlus; }_x000D_
var CurrentLevel = -1;_x000D_
var level = 0;_x000D_
var column = 0;_x000D_
for (var i = 0; i < ColNum; i++ )_x000D_
{_x000D_
 column = br.offset(0, i).getColumn();_x000D_
 level = columnsLevels.indexOf(column) + colPlus;_x000D_
 if (level > CurrentLevel) { CurrentLevel = level; }_x000D_
}_x000D_
return CurrentLevel;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
function loopColumns_(HeadLevel, X, currentRow, NumOfLevels, CurrentLevel, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts)_x000D_
{_x000D_
  for (var k = 1; k <= X; k++)_x000D_
  {   _x000D_
HeadLevel = HeadLevel + k - 1; _x000D_
CurrentLevel = CurrLevelBase + k - 1;_x000D_
var r = ts.getRange(currentRow, columnsLevels[CurrentLevel - 2]);_x000D_
var SearchText = r.getValue(); // searched text _x000D_
X = loopColumn_(X, SearchText, HeadLevel, HeadLevel, currentRow, NumOfLevels, CurrentLevel, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts);_x000D_
  } _x000D_
}_x000D_
_x000D_
_x000D_
function loopColumn_(X, SearchText, HeadLevel, HeadLevel, currentRow, NumOfLevels, CurrentLevel, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts)_x000D_
{_x000D_
_x000D_
_x000D_
  // if nothing is chosen!_x000D_
  if (SearchText === '') // condition value =''_x000D_
  {_x000D_
// kill extra data validation if there were _x000D_
// columns on the right_x000D_
if (CurrentLevel <= NumOfLevels) _x000D_
{_x000D_
  for (var f = 0; f < X; f++) _x000D_
  {_x000D_
    var cell = ts.getRange(currentRow, columnsLevels[CurrentLevel + f - 1]);    _x000D_
    // clean & get rid of validation_x000D_
    cell.clear({contentsOnly: true});              _x000D_
    cell.clear({validationsOnly: true});_x000D_
    // exit columns loop  _x000D_
  }_x000D_
}_x000D_
return 0; // end loop this row _x000D_
  }_x000D_
  _x000D_
  _x000D_
  // formula for values_x000D_
  var formula = getDVListFormula_(CurrentLevel, currentRow, columnsLevels, lastRow, ReplaceCommas, FormulaSplitter, ts);  _x000D_
  KudaNado.setFormula(formula);_x000D_
_x000D_
  _x000D_
  // get response_x000D_
  var Response = getResponse_(ChtoNado, lastRow, ReplaceCommas);_x000D_
  var Variants = Response.length;_x000D_
_x000D_
_x000D_
  // build data validation rule_x000D_
  if (Variants === 0.0) // empty is found_x000D_
  {_x000D_
return;_x000D_
  }  _x000D_
  if(Variants >= 1.0) // if some variants were found_x000D_
  {_x000D_
_x000D_
var cell = ts.getRange(currentRow, columnsLevels[CurrentLevel - 1]);_x000D_
var rule = SpreadsheetApp_x000D_
.newDataValidation()_x000D_
.requireValueInList(Response, true)_x000D_
.setAllowInvalid(false)_x000D_
.build();_x000D_
// set validation rule_x000D_
cell.setDataValidation(rule);_x000D_
  }    _x000D_
  if (Variants === 1.0) // // set the only value_x000D_
  {      _x000D_
cell.setValue(Response[0]);_x000D_
SearchText = null;_x000D_
Response = null;_x000D_
return X; // continue doing DV_x000D_
  } // the only value_x000D_
  _x000D_
  return 0; // end DV in this row_x000D_
  _x000D_
}_x000D_
_x000D_
_x000D_
function getDVListFormula_(CurrentLevel, currentRow, columnsLevels, lastRow, ReplaceCommas, FormulaSplitter, ts)_x000D_
{_x000D_
  _x000D_
  var checkVals = [];_x000D_
  var Offs = CurrentLevel - 2;_x000D_
  var values = [];_x000D_
  // get values and display values for a formula_x000D_
  for (var s = 0; s <= Offs; s++)_x000D_
  {_x000D_
var checkR = ts.getRange(currentRow, columnsLevels[s]);_x000D_
values.push(checkR.getValue());_x000D_
  }     _x000D_
  _x000D_
  var LookCol = colName(CurrentLevel-1); // gets column name "A,B,C..."_x000D_
  var formula = '=unique(filter(' + LookCol + '2:' + LookCol + lastRow; // =unique(filter(A2:A84_x000D_
_x000D_
  var mathOpPlusVal = ''; _x000D_
  var value = '';_x000D_
_x000D_
  // loop levels for multiple conditions  _x000D_
  for (var i = 0; i < CurrentLevel - 1; i++) {            _x000D_
formula += FormulaSplitter; // =unique(filter(A2:A84;_x000D_
LookCol = colName(i);_x000D_
  _x000D_
value = values[i];_x000D_
_x000D_
mathOpPlusVal = getValueAndMathOpForFunction_(value, FormulaSplitter, ReplaceCommas); // =unique(filter(A2:A84;B2:B84="Text"_x000D_
_x000D_
if ( Array.isArray(mathOpPlusVal) )_x000D_
{_x000D_
  formula += mathOpPlusVal[0];_x000D_
  formula += LookCol + '2:' + LookCol + lastRow; // =unique(filter(A2:A84;ROUND(B2:B84_x000D_
  formula += mathOpPlusVal[1];_x000D_
}_x000D_
else_x000D_
{_x000D_
  formula += LookCol + '2:' + LookCol + lastRow; // =unique(filter(A2:A84;B2:B84_x000D_
  formula += mathOpPlusVal;_x000D_
}_x000D_
_x000D_
_x000D_
  }  _x000D_
  _x000D_
  formula += "))"; //=unique(filter(A2:A84;B2:B84="Text"))_x000D_
_x000D_
  return formula;_x000D_
}_x000D_
_x000D_
_x000D_
function getValueAndMathOpForFunction_(value, FormulaSplitter, ReplaceCommas)_x000D_
{_x000D_
  var result = '';_x000D_
  var splinter = ''; _x000D_
_x000D_
  var type = typeof value;_x000D_
  _x000D_
 _x000D_
  // strings_x000D_
  if (type === 'string') return '="' + value + '"';_x000D_
  // date_x000D_
  if(value instanceof Date)_x000D_
  {_x000D_
return ['ROUND(', FormulaSplitter +'5)=ROUND(DATE(' + value.getFullYear() + FormulaSplitter + (value.getMonth() + 1) + FormulaSplitter + value.getDate() + ')' + '+' _x000D_
      + 'TIME(' + value.getHours() + FormulaSplitter + value.getMinutes() + FormulaSplitter + value.getSeconds() + ')' + FormulaSplitter + '5)'];   _x000D_
  }  _x000D_
  // numbers_x000D_
  if (type === 'number')_x000D_
  {_x000D_
if (ReplaceCommas)_x000D_
{_x000D_
 return '+0=' + value.toString().replace('.', ',');  _x000D_
}_x000D_
else_x000D_
{_x000D_
 return '+0=' + value;_x000D_
}_x000D_
  }_x000D_
  // booleans_x000D_
  if (type === 'boolean')_x000D_
  {_x000D_
  return '=' + value;_x000D_
  }  _x000D_
  // other_x000D_
  return '=' + value;_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function getResponse_(allRange, l, ReplaceCommas)_x000D_
{_x000D_
  var data = allRange.getValues();_x000D_
  var data_ = allRange.getDisplayValues();_x000D_
  _x000D_
  var response = [];_x000D_
  var val = '';_x000D_
  for (var i = 0; i < l; i++)_x000D_
  {_x000D_
val = data[i][0];_x000D_
if (val !== '') _x000D_
{_x000D_
  var type = typeof val;_x000D_
  if (type === 'boolean' || val instanceof Date) val = String(data_[i][0]);_x000D_
  if (type === 'number' && ReplaceCommas) val = val.toString().replace('.', ',')_x000D_
  response.push(val);  _x000D_
}_x000D_
  }_x000D_
  _x000D_
  return response;  _x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
function colName(n) {_x000D_
var ordA = 'a'.charCodeAt(0);_x000D_
var ordZ = 'z'.charCodeAt(0);_x000D_
_x000D_
var len = ordZ - ordA + 1;_x000D_
_x000D_
var s = "";_x000D_
while(n >= 0) {_x000D_
    s = String.fromCharCode(n % len + ordA) + s;_x000D_
    n = Math.floor(n / len) - 1;_x000D_
}_x000D_
return s; _x000D_
}_x000D_
_x000D_
_x000D_
function getDecimalMarkIsCommaLocals() {_x000D_
_x000D_
_x000D_
// list of Locals Decimal mark = comma_x000D_
var LANGUAGE_BY_LOCALE = {_x000D_
af_NA: "Afrikaans (Namibia)",_x000D_
af_ZA: "Afrikaans (South Africa)",_x000D_
af: "Afrikaans",_x000D_
sq_AL: "Albanian (Albania)",_x000D_
sq: "Albanian",_x000D_
ar_DZ: "Arabic (Algeria)",_x000D_
ar_BH: "Arabic (Bahrain)",_x000D_
ar_EG: "Arabic (Egypt)",_x000D_
ar_IQ: "Arabic (Iraq)",_x000D_
ar_JO: "Arabic (Jordan)",_x000D_
ar_KW: "Arabic (Kuwait)",_x000D_
ar_LB: "Arabic (Lebanon)",_x000D_
ar_LY: "Arabic (Libya)",_x000D_
ar_MA: "Arabic (Morocco)",_x000D_
ar_OM: "Arabic (Oman)",_x000D_
ar_QA: "Arabic (Qatar)",_x000D_
ar_SA: "Arabic (Saudi Arabia)",_x000D_
ar_SD: "Arabic (Sudan)",_x000D_
ar_SY: "Arabic (Syria)",_x000D_
ar_TN: "Arabic (Tunisia)",_x000D_
ar_AE: "Arabic (United Arab Emirates)",_x000D_
ar_YE: "Arabic (Yemen)",_x000D_
ar: "Arabic",_x000D_
hy_AM: "Armenian (Armenia)",_x000D_
hy: "Armenian",_x000D_
eu_ES: "Basque (Spain)",_x000D_
eu: "Basque",_x000D_
be_BY: "Belarusian (Belarus)",_x000D_
be: "Belarusian",_x000D_
bg_BG: "Bulgarian (Bulgaria)",_x000D_
bg: "Bulgarian",_x000D_
ca_ES: "Catalan (Spain)",_x000D_
ca: "Catalan",_x000D_
tzm_Latn: "Central Morocco Tamazight (Latin)",_x000D_
tzm_Latn_MA: "Central Morocco Tamazight (Latin, Morocco)",_x000D_
tzm: "Central Morocco Tamazight",_x000D_
da_DK: "Danish (Denmark)",_x000D_
da: "Danish",_x000D_
nl_BE: "Dutch (Belgium)",_x000D_
nl_NL: "Dutch (Netherlands)",_x000D_
nl: "Dutch",_x000D_
et_EE: "Estonian (Estonia)",_x000D_
et: "Estonian",_x000D_
fi_FI: "Finnish (Finland)",_x000D_
fi: "Finnish",_x000D_
fr_BE: "French (Belgium)",_x000D_
fr_BJ: "French (Benin)",_x000D_
fr_BF: "French (Burkina Faso)",_x000D_
fr_BI: "French (Burundi)",_x000D_
fr_CM: "French (Cameroon)",_x000D_
fr_CA: "French (Canada)",_x000D_
fr_CF: "French (Central African Republic)",_x000D_
fr_TD: "French (Chad)",_x000D_
fr_KM: "French (Comoros)",_x000D_
fr_CG: "French (Congo - Brazzaville)",_x000D_
fr_CD: "French (Congo - Kinshasa)",_x000D_
fr_CI: "French (Côte d’Ivoire)",_x000D_
fr_DJ: "French (Djibouti)",_x000D_
fr_GQ: "French (Equatorial Guinea)",_x000D_
fr_FR: "French (France)",_x000D_
fr_GA: "French (Gabon)",_x000D_
fr_GP: "French (Guadeloupe)",_x000D_
fr_GN: "French (Guinea)",_x000D_
fr_LU: "French (Luxembourg)",_x000D_
fr_MG: "French (Madagascar)",_x000D_
fr_ML: "French (Mali)",_x000D_
fr_MQ: "French (Martinique)",_x000D_
fr_MC: "French (Monaco)",_x000D_
fr_NE: "French (Niger)",_x000D_
fr_RW: "French (Rwanda)",_x000D_
fr_RE: "French (Réunion)",_x000D_
fr_BL: "French (Saint Barthélemy)",_x000D_
fr_MF: "French (Saint Martin)",_x000D_
fr_SN: "French (Senegal)",_x000D_
fr_CH: "French (Switzerland)",_x000D_
fr_TG: "French (Togo)",_x000D_
fr: "French",_x000D_
gl_ES: "Galician (Spain)",_x000D_
gl: "Galician",_x000D_
ka_GE: "Georgian (Georgia)",_x000D_
ka: "Georgian",_x000D_
de_AT: "German (Austria)",_x000D_
de_BE: "German (Belgium)",_x000D_
de_DE: "German (Germany)",_x000D_
de_LI: "German (Liechtenstein)",_x000D_
de_LU: "German (Luxembourg)",_x000D_
de_CH: "German (Switzerland)",_x000D_
de: "German",_x000D_
el_CY: "Greek (Cyprus)",_x000D_
el_GR: "Greek (Greece)",_x000D_
el: "Greek",_x000D_
hu_HU: "Hungarian (Hungary)",_x000D_
hu: "Hungarian",_x000D_
is_IS: "Icelandic (Iceland)",_x000D_
is: "Icelandic",_x000D_
id_ID: "Indonesian (Indonesia)",_x000D_
id: "Indonesian",_x000D_
it_IT: "Italian (Italy)",_x000D_
it_CH: "Italian (Switzerland)",_x000D_
it: "Italian",_x000D_
kab_DZ: "Kabyle (Algeria)",_x000D_
kab: "Kabyle",_x000D_
kl_GL: "Kalaallisut (Greenland)",_x000D_
kl: "Kalaallisut",_x000D_
lv_LV: "Latvian (Latvia)",_x000D_
lv: "Latvian",_x000D_
lt_LT: "Lithuanian (Lithuania)",_x000D_
lt: "Lithuanian",_x000D_
mk_MK: "Macedonian (Macedonia)",_x000D_
mk: "Macedonian",_x000D_
naq_NA: "Nama (Namibia)",_x000D_
naq: "Nama",_x000D_
pl_PL: "Polish (Poland)",_x000D_
pl: "Polish",_x000D_
pt_BR: "Portuguese (Brazil)",_x000D_
pt_GW: "Portuguese (Guinea-Bissau)",_x000D_
pt_MZ: "Portuguese (Mozambique)",_x000D_
pt_PT: "Portuguese (Portugal)",_x000D_
pt: "Portuguese",_x000D_
ro_MD: "Romanian (Moldova)",_x000D_
ro_RO: "Romanian (Romania)",_x000D_
ro: "Romanian",_x000D_
ru_MD: "Russian (Moldova)",_x000D_
ru_RU: "Russian (Russia)",_x000D_
ru_UA: "Russian (Ukraine)",_x000D_
ru: "Russian",_x000D_
seh_MZ: "Sena (Mozambique)",_x000D_
seh: "Sena",_x000D_
sk_SK: "Slovak (Slovakia)",_x000D_
sk: "Slovak",_x000D_
sl_SI: "Slovenian (Slovenia)",_x000D_
sl: "Slovenian",_x000D_
es_AR: "Spanish (Argentina)",_x000D_
es_BO: "Spanish (Bolivia)",_x000D_
es_CL: "Spanish (Chile)",_x000D_
es_CO: "Spanish (Colombia)",_x000D_
es_CR: "Spanish (Costa Rica)",_x000D_
es_DO: "Spanish (Dominican Republic)",_x000D_
es_EC: "Spanish (Ecuador)",_x000D_
es_SV: "Spanish (El Salvador)",_x000D_
es_GQ: "Spanish (Equatorial Guinea)",_x000D_
es_GT: "Spanish (Guatemala)",_x000D_
es_HN: "Spanish (Honduras)",_x000D_
es_419: "Spanish (Latin America)",_x000D_
es_MX: "Spanish (Mexico)",_x000D_
es_NI: "Spanish (Nicaragua)",_x000D_
es_PA: "Spanish (Panama)",_x000D_
es_PY: "Spanish (Paraguay)",_x000D_
es_PE: "Spanish (Peru)",_x000D_
es_PR: "Spanish (Puerto Rico)",_x000D_
es_ES: "Spanish (Spain)",_x000D_
es_US: "Spanish (United States)",_x000D_
es_UY: "Spanish (Uruguay)",_x000D_
es_VE: "Spanish (Venezuela)",_x000D_
es: "Spanish",_x000D_
sv_FI: "Swedish (Finland)",_x000D_
sv_SE: "Swedish (Sweden)",_x000D_
sv: "Swedish",_x000D_
tr_TR: "Turkish (Turkey)",_x000D_
tr: "Turkish",_x000D_
uk_UA: "Ukrainian (Ukraine)",_x000D_
uk: "Ukrainian",_x000D_
vi_VN: "Vietnamese (Vietnam)",_x000D_
vi: "Vietnamese"_x000D_
}_x000D_
_x000D_
_x000D_
var SS = SpreadsheetApp.getActiveSpreadsheet();_x000D_
var LocalS = SS.getSpreadsheetLocale();_x000D_
_x000D_
_x000D_
if (LANGUAGE_BY_LOCALE[LocalS] == undefined) {_x000D_
  return false;_x000D_
  _x000D_
}_x000D_
  //Logger.log(true);_x000D_
  return true;_x000D_
}_x000D_
_x000D_
/*_x000D_
function ReplaceDotsToCommas(dataIn) {_x000D_
  var dataOut = dataIn.map(function(num) {_x000D_
  if (isNaN(num)) {_x000D_
    return num;_x000D_
  }    _x000D_
  num = num.toString();_x000D_
  return num.replace(".", ",");_x000D_
  });_x000D_
  return dataOut;_x000D_
}_x000D_
*/
_x000D_
_x000D_
_x000D_

Here's set of variables that are to be changed, you'll find them in script:

  var TargetSheet = 'Main'; // name of sheet with data validation
  var LogSheet = 'Data2'; // name of sheet with data
  var NumOfLevels = 7; // number of levels of data validation
  var lcol = 9; // number of column where validation starts; A = 1, B = 2, etc.
  var lrow = 2; // number of row where validation starts
  var offsets = [1,1,1,1,1,1,1]; // offsets for levels

I suggest everyone, who knows scripts well, send your edits to this code. I guess, there's simpler way to find validation list and make script run faster.

String.replaceAll single backslashes with double backslashes

You'll need to escape the (escaped) backslash in the first argument as it is a regular expression. Replacement (2nd argument - see Matcher#replaceAll(String)) also has it's special meaning of backslashes, so you'll have to replace those to:

theString.replaceAll("\\\\", "\\\\\\\\");

Add button to a layout programmatically

This line:

layout = (LinearLayout) findViewById(R.id.statsviewlayout);

Looks for the "statsviewlayout" id in your current 'contentview'. Now you've set that here:

setContentView(new GraphTemperature(getApplicationContext()));

And i'm guessing that new "graphTemperature" does not set anything with that id.

It's a common mistake to think you can just find any view with findViewById. You can only find a view that is in the XML (or appointed by code and given an id).

The nullpointer will be thrown because the layout you're looking for isn't found, so

layout.addView(buyButton);

Throws that exception.

addition: Now if you want to get that view from an XML, you should use an inflater:

layout = (LinearLayout) View.inflate(this, R.layout.yourXMLYouWantToLoad, null);

assuming that you have your linearlayout in a file called "yourXMLYouWantToLoad.xml"

What is the difference between == and equals() in Java?

Just remember that .equals(...) has to be implemented by the class you are trying to compare. Otherwise, there isn't much of a point; the version of the method for the Object class does the same thing as the comparison operation: Object#equals.

The only time you really want to use the comparison operator for objects is wen you are comparing Enums. This is because there is only one instance of an Enum value at a time. For instance, given the enum

enum FooEnum {A, B, C}

You will never have more than one instance of A at a time, and the same for B and C. This means that you can actually write a method like so:

public boolean compareFoos(FooEnum x, FooEnum y)
{
    return (x == y);
}

And you will have no problems whatsoever.

How do I install Python OpenCV through Conda?

I think the easiest option that should work cross-platform and across various versions of Anaconda is

#Run Anaconda Prompt as an Administrator (on Windows) & execute the command below
#(you may need to use   sudo   on a Unix-Based or Mac system 
#to have the needed permissions)

conda install -c conda-forge opencv

How to check if variable's type matches Type stored in a variable

In order to check if an object is compatible with a given type variable, instead of writing

u is t

you should write

typeof(t).IsInstanceOfType(u)

How do I get the serial key for Visual Studio Express?

The question is about VS 2008 Express.

Microsoft's web page for registering Visual Studio 2008 Express has been dead (404) for some time, so registering it is not possible.

Instead, as a workaround, you can temporarily remove the requirement to register VS2008Exp by deleting (or renaming) the registry key:

HKEY_CURRENT_USER/Software/Microsoft/VCExpress/9.0/Registration

To ensure that this is working beforehand, click Help -> register product within VS2008.

You should see text like

"You have not yet registered your copy of Visual C++ 2008 Express Edition. This product will run for 10 more days before you will be required to register it."

Close the application, delete that key, reopen, click help->register product.

The text should now say

"You have not yet registered your copy of Visual C++ 2008 Express Edition. This product will run for 30 more days before you will be required to register it."

So you have two options - delete that key manually every 30 days, or run it from a batch file that also contains a line like:

reg delete HKCU\Software\Microsoft\VCExpress\9.0\Registration /f

[Edit: User @i486 confirms on testing that this workaround works even after the expiration period has expired]

[Edit2: User @Wyatt8740 has a much more elegant way to prevent the value from reappearing.]

How do I convert an array object to a string in PowerShell?

$a = "This", "Is", "a", "cat"

foreach ( $word in $a ) { $sent = "$sent $word" }
$sent = $sent.Substring(1)

Write-Host $sent

How to use the ConfigurationManager.AppSettings

Your web.config file should have this structure:

<configuration>
    <connectionStrings>
        <add name="MyConnectionString" connectionString="..." />
    </connectionStrings>
</configuration>

Then, to create a SQL connection using the connection string named MyConnectionString:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);

If you'd prefer to keep your connection strings in the AppSettings section of your configuration file, it would look like this:

<configuration>
    <appSettings>
        <add key="MyConnectionString" value="..." />
    </appSettings>
</configuration>

And then your SqlConnection constructor would look like this:

SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["MyConnectionString"]);

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

My issue was that the root element actually has a xmlns="abc123"

So had to make XmlRoot("elementname",NameSpace="abc123")

How to update Xcode from command line

@Vel Genov's answer is correct, except when the version of Xcode can't be updated because it is the latest version for your current version of Mac OS. If you know there is a newer Xcode (for example, it won't load an app onto a device with a recent version of iOS) then it's necessary to first upgrade Mac OS.


Further note for those like me with old Mac Pro 5.1. Upgrading to Mojave required installing the metal gpu (Sapphire AMD Radeon RX 560 in my case) but make sure only HDMI monitor is installed (not 4K! 1080 only). Only then did install Mojave say firmware update required and shut computer down. Long 2 minute power button hold and it all upgraded fine after that!


Catalina update - softwareupdate --install -a won't upgrade xcode from command line if there is a pending update (say you selected update xcode overnight)

Why does instanceof return false for some literals?

https://www.npmjs.com/package/typeof

Returns a string-representation of instanceof (the constructors name)

function instanceOf(object) {
  var type = typeof object

  if (type === 'undefined') {
    return 'undefined'
  }

  if (object) {
    type = object.constructor.name
  } else if (type === 'object') {
    type = Object.prototype.toString.call(object).slice(8, -1)
  }

  return type.toLowerCase()
}

instanceOf(false)                  // "boolean"
instanceOf(new Promise(() => {}))  // "promise"
instanceOf(null)                   // "null"
instanceOf(undefined)              // "undefined"
instanceOf(1)                      // "number"
instanceOf(() => {})               // "function"
instanceOf([])                     // "array"

Show a message box from a class in c#?

Try this:

System.Windows.Forms.MessageBox.Show("Here's a message!");

How to make ng-repeat filter out duplicate results

Create your own array.

<select name="cmpPro" ng-model="test3.Product" ng-options="q for q in productArray track by q">
    <option value="" >Plans</option>
</select>

 productArray =[];
angular.forEach($scope.leadDetail, function(value,key){
    var index = $scope.productArray.indexOf(value.Product);
    if(index === -1)
    {
        $scope.productArray.push(value.Product);
    }
});

How to generate unique IDs for form labels in React?

I create a uniqueId generator module (Typescript):

const uniqueId = ((): ((prefix: string) => string) => {
  let counter = 0;
  return (prefix: string): string => `${prefix}${++counter}`;
})();

export default uniqueId;

And use top module to generate unique ids:

import React, { FC, ReactElement } from 'react'
import uniqueId from '../../modules/uniqueId';

const Component: FC = (): ReactElement => {
  const [inputId] = useState(uniqueId('input-'));
  return (
    <label htmlFor={inputId}>
      <span>text</span>
      <input id={inputId} type="text" />
    </label>
  );
};     

Is it possible to cherry-pick a commit from another git repository?

You can do it, but it requires two steps. Here's how:

git fetch <remote-git-url> <branch> && git cherry-pick FETCH_HEAD

Replace <remote-git-url> with the url or path to the repository you want cherry-pick from.

Replace <branch> with the branch or tag name you want to cherry-pick from the remote repository.

You can replace FETCH_HEAD with a git SHA from the branch.

Updated: modified based on @pkalinow's feedback.

Issue with background color and Google Chrome

Never heard of it. Try:

html, body {
  width: 100%;
  height: 100%;
  background-color: #000;
  color: #fff;
  font-family: ...;
}

percentage of two int?

One of them has to be a float going in. One possible way of ensuring that is:

float percent = (float) n/v * 100;

Otherwise, you're doing integer division, which truncates the numbers. Also, you should be using double unless there's a good reason for the float.

The next issue you'll run into is that some of your percentages might look like 24.9999999999999% instead of 25%. This is due to precision loss in floating point representation. You'll have to decide how to deal with that, too. Options include a DecimalFormat to "fix" the formatting or BigDecimal to represent exact values.

binning data in python with scipy/numpy

The numpy_indexed package (disclaimer: I am its author) contains functionality to efficiently perform operations of this type:

import numpy_indexed as npi
print(npi.group_by(np.digitize(data, bins)).mean(data))

This is essentially the same solution as the one I posted earlier; but now wrapped in a nice interface, with tests and all :)

Calculate average in java

 System.out.println(result/count) 

you can't do this because result/count is not a String type, and System.out.println() only takes a String parameter. perhaps try:

double avg = (double)result / (double)args.length

How to make Excel VBA variables available to multiple macros?

Declare them outside the subroutines, like this:

Public wbA as Workbook
Public wbB as Workbook
Sub MySubRoutine()
    Set wbA = Workbooks.Open("C:\file.xlsx")
    Set wbB = Workbooks.Open("C:\file2.xlsx")
    OtherSubRoutine
End Sub
Sub OtherSubRoutine()
    MsgBox wbA.Name, vbInformation
End Sub

Alternately, you can pass variables between subroutines:

Sub MySubRoutine()
Dim wbA as Workbook
Dim wbB as Workbook
    Set wbA = Workbooks.Open("C:\file.xlsx")
    Set wbB = Workbooks.Open("C:\file2.xlsx")
    OtherSubRoutine wbA, wbB
End Sub
Sub OtherSubRoutine(wb1 as Workbook, wb2 as Workbook)
    MsgBox wb1.Name, vbInformation
    MsgBox wb2.Name, vbInformation
End Sub

Or use Functions to return values:

Sub MySubroutine()
    Dim i as Long
    i = MyFunction()
    MsgBox i
End Sub
Function MyFunction()
    'Lots of code that does something
    Dim x As Integer, y as Double
    For x = 1 to 1000
        'Lots of code that does something
    Next
    MyFunction = y
End Function

In the second method, within the scope of OtherSubRoutine you refer to them by their parameter names wb1 and wb2. Passed variables do not need to use the same names, just the same variable types. This allows you some freedom, for example you have a loop over several workbooks, and you can send each workbook to a subroutine to perform some action on that Workbook, without making all (or any) of the variables public in scope.

A Note About User Forms

Personally I would recommend keeping Option Explicit in all of your modules and forms (this prevents you from instantiating variables with typos in their names, like lCoutn when you meant lCount etc., among other reasons).

If you're using Option Explicit (which you should), then you should qualify module-scoped variables for style and to avoid ambiguity, and you must qualify user-form Public scoped variables, as these are not "public" in the same sense. For instance, i is undefined, though it's Public in the scope of UserForm1:

enter image description here

You can refer to it as UserForm1.i to avoid the compile error, or since forms are New-able, you can create a variable object to contain reference to your form, and refer to it that way:

enter image description here

NB: In the above screenshots x is declared Public x as Long in another standard code module, and will not raise the compilation error. It may be preferable to refer to this as Module2.x to avoid ambiguity and possible shadowing in case you re-use variable names...

Empty set literal?

By all means, please use set() to create an empty set.

But, if you want to impress people, tell them that you can create an empty set using literals and * with Python >= 3.5 (see PEP 448) by doing:

>>> s = {*()}  # or {*{}} or {*[]}
>>> print(s)
set()

this is basically a more condensed way of doing {_ for _ in ()}, but, don't do this.

How to use target in location.href

<a href="url" target="_blank"> <input type="button" value="fake button" /> </a>

How to get the title of HTML page with JavaScript?

Put in the URL bar and then click enter:

javascript:alert(document.title);

You can select and copy the text from the alert depending on the website and the web browser you are using.

How to return a specific status code and no contents from Controller?

The best way to do it is:

return this.StatusCode(StatusCodes.Status418ImATeapot, "Error message");

'StatusCodes' has every kind of return status and you can see all of them in this link https://httpstatuses.com/

Once you choose your StatusCode, return it with a message.

What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

For those, who wonder how it goes in VS.

MSVC 2015 Update 1, cl.exe version 19.00.24215.1:

#include <iostream>

template<typename X, typename Y>
struct A
{
  template<typename Z>
  static void f()
  {
    std::cout << "from A::f():" << std::endl
      << __FUNCTION__ << std::endl
      << __func__ << std::endl
      << __FUNCSIG__ << std::endl;
  }
};

void main()
{
  std::cout << "from main():" << std::endl
    << __FUNCTION__ << std::endl
    << __func__ << std::endl
    << __FUNCSIG__ << std::endl << std::endl;

  A<int, float>::f<bool>();
}

output:

from main():
main
main
int __cdecl main(void)

from A::f():
A<int,float>::f
f
void __cdecl A<int,float>::f<bool>(void)

Using of __PRETTY_FUNCTION__ triggers undeclared identifier error, as expected.

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

sorted_by_second = sorted(data, key=lambda tup: tup[1])

or:

data.sort(key=lambda tup: tup[1])  # sorts in place

How do I install boto?

$ easy_install boto

Edit: pip is now by far the preferred way to install packages

.NET - Get protocol, host, and port

The following (C#) code should do the trick

Uri uri = new Uri("http://www.mywebsite.com:80/pages/page1.aspx");
string requested = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;

Java - Using Accessor and Mutator methods

Let's go over the basics: "Accessor" and "Mutator" are just fancy names fot a getter and a setter. A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.

So first you need to set up a class with some variables to get/set:

public class IDCard
{
    private String mName;
    private String mFileName;
    private int mID;

}

But oh no! If you instantiate this class the default values for these variables will be meaningless. B.T.W. "instantiate" is a fancy word for doing:

IDCard test = new IDCard();

So - let's set up a default constructor, this is the method being called when you "instantiate" a class.

public IDCard()
{
    mName = "";
    mFileName = "";
    mID = -1;
}

But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:

public IDCard(String name, int ID, String filename)
{
    mName = name;
    mID = ID;
    mFileName = filename;
}

Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:

public String getName()
{
    return mName;
}

public void setName( String name )
{
    mName = name;
}

Nice. Now we can access mName. Add the rest of the accessors and mutators and you're now a certified Java newbie. Good luck.

Undoing accidental git stash pop

Try using How to recover a dropped stash in Git? to find the stash you popped. I think there are always two commits for a stash, since it preserves the index and the working copy (so often the index commit will be empty). Then git show them to see the diff and use patch -R to unapply them.

What is the difference between a var and val definition in Scala?

In simple terms:

var = variable

val = variable + final

Converting String to "Character" array in Java

if you are working with JTextField then it can be helpfull..

public JTextField display;
String number=e.getActionCommand();

display.setText(display.getText()+number);

ch=number.toCharArray();
for( int i=0; i<ch.length; i++)
    System.out.println("in array a1= "+ch[i]);

Ruby Arrays: select(), collect(), and map()

When dealing with a hash {}, use both the key and value to the block inside the ||.

details.map {|key,item|"" == item}

=>[false, false, true, false, false]

How to refer to relative paths of resources when working with a code repository

If you are using setup tools or distribute (a setup.py install) then the "right" way to access these packaged resources seem to be using package_resources.

In your case the example would be

import pkg_resources
my_data = pkg_resources.resource_string(__name__, "foo.dat")

Which of course reads the resource and the read binary data would be the value of my_data

If you just need the filename you could also use

resource_filename(package_or_requirement, resource_name)

Example:

resource_filename("MyPackage","foo.dat")

The advantage is that its guaranteed to work even if it is an archive distribution like an egg.

See http://packages.python.org/distribute/pkg_resources.html#resourcemanager-api

How do I print out the value of this boolean? (Java)

System.out.println(isLeapYear);

should work just fine.

Incidentally, in

else if ((year % 4 == 0) && (year % 100 == 0))
    isLeapYear = false;

else if ((year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0))
    isLeapYear = true;

the year % 400 part will never be reached because if (year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0) is true, then (year % 4 == 0) && (year % 100 == 0) must have succeeded.

Maybe swap those two conditions or refactor them:

else if ((year % 4 == 0) && (year % 100 == 0))
    isLeapYear = (year % 400 == 0);

How do I use variables in Oracle SQL Developer?

You can read up elsewhere on substitution variables; they're quite handy in SQL Developer. But I have fits trying to use bind variables in SQL Developer. This is what I do:

SET SERVEROUTPUT ON
declare
  v_testnum number;
  v_teststring varchar2(1000);

begin
   v_testnum := 2;
   DBMS_OUTPUT.put_line('v_testnum is now ' || v_testnum);

   SELECT 36,'hello world'
   INTO v_testnum, v_teststring
   from dual;

   DBMS_OUTPUT.put_line('v_testnum is now ' || v_testnum);
   DBMS_OUTPUT.put_line('v_teststring is ' || v_teststring);
end;

SET SERVEROUTPUT ON makes it so text can be printed to the script output console.

I believe what we're doing here is officially called PL/SQL. We have left the pure SQL land and are using a different engine in Oracle. You see the SELECT above? In PL/SQL you always have to SELECT ... INTO either variable or a refcursor. You can't just SELECT and return a result set in PL/SQL.

accepting HTTPS connections with self-signed certificates

Simplest way for create SSL certificate

Open Firefox (I suppose it's also possible with Chrome, but it's easier for me with FF)

Visit your development site with a self-signed SSL certificate.

Click on the certificate (next to the site name)

Click on "More information"

Click on "View certificate"

Click on "Details"

Click on "Export..."

Choose "X.509 Certificate whith chain (PEM)", select the folder and name to save it and click "Save"

Go to command line, to the directory where you downloaded the pem file and execute "openssl x509 -inform PEM -outform DM -in .pem -out .crt"

Copy the .crt file to the root of the /sdcard folder inside your Android device Inside your Android device, Settings > Security > Install from storage.

It should detect the certificate and let you add it to the device Browse to your development site.

The first time it should ask you to confirm the security exception. That's all.

The certificate should work with any browser installed on your Android (Browser, Chrome, Opera, Dolphin...)

Remember that if you're serving your static files from a different domain (we all are page speed bitches) you also need to add the certificate for that domain.

Identifying and removing null characters in UNIX

Use the following sed command for removing the null characters in a file.

sed -i 's/\x0//g' null.txt

this solution edits the file in place, important if the file is still being used. passing -i'ext' creates a backup of the original file with 'ext' suffix added.

Converting an int to a binary string representation in Java?

You can use while loop as well to convert an int to binary. Like this,

import java.util.Scanner;

public class IntegerToBinary
{
   public static void main(String[] args)
   {
      int num;
      String str = "";
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter the a number : ");
      num = sc.nextInt();
      while(num > 0)
      {
         int y = num % 2;
         str = y + str;
         num = num / 2;
      }
      System.out.println("The binary conversion is : " + str);
      sc.close();
   }
}

Source and reference - convert int to binary in java example.

Unable to find a @SpringBootConfiguration when doing a JpaTest

It is worth to check if you have refactored package name of your main class annotated with @SpringBootApplication. In that case the testcase should be in an appropriate package otherwise it will be looking for it in the older package . this was the case for me.

Filter an array using a formula (without VBA)

This will do it if you only want the first "B" value, you can sub a cell address for "B" if you want to make it more generic.

=INDEX(A2:A6,SUMPRODUCT(MATCH(TRUE,(B2:B6)="B",0)),1)

To use this based on two columns, just concatenate inside the match:

=INDEX(A2:A6,SUMPRODUCT(MATCH(TRUE,(A2:A6&B2:B6)=("3"&"B"),0)),1)

Access denied for user 'homestead'@'localhost' (using password: YES)

in my case (laravel 5+) i had to wrap my password in single quotation marks and clear config cache:

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=user_name
DB_PASSWORD='password'

and then run:

php artisan config:clear

How to create a laravel hashed password

In the BcryptHasher.php you can find the hash code:

public function make($value, array $options = array())
{
    $cost = isset($options['rounds']) ? $options['rounds'] : $this->rounds;

    $hash = password_hash($value, PASSWORD_BCRYPT, array('cost' => $cost));

            $hash = password_hash($value, PASSWORD_BCRYPT, array('cost' => $cost));
            echo $value.' '.PASSWORD_BCRYPT.' '.$cost.' ';
            echo $hash;die();
    if ($hash === false)
    {
        throw new RuntimeException("Bcrypt hashing not supported.");
    }

    return $hash;
}

What does the "yield" keyword do?

To understand what yield does, you must understand what generators are. And before you can understand generators, you must understand iterables.

Iterables

When you create a list, you can read its items one by one. Reading its items one by one is called iteration:

>>> mylist = [1, 2, 3]
>>> for i in mylist:
...    print(i)
1
2
3

mylist is an iterable. When you use a list comprehension, you create a list, and so an iterable:

>>> mylist = [x*x for x in range(3)]
>>> for i in mylist:
...    print(i)
0
1
4

Everything you can use "for... in..." on is an iterable; lists, strings, files...

These iterables are handy because you can read them as much as you wish, but you store all the values in memory and this is not always what you want when you have a lot of values.

Generators

Generators are iterators, a kind of iterable you can only iterate over once. Generators do not store all the values in memory, they generate the values on the fly:

>>> mygenerator = (x*x for x in range(3))
>>> for i in mygenerator:
...    print(i)
0
1
4

It is just the same except you used () instead of []. BUT, you cannot perform for i in mygenerator a second time since generators can only be used once: they calculate 0, then forget about it and calculate 1, and end calculating 4, one by one.

Yield

yield is a keyword that is used like return, except the function will return a generator.

>>> def createGenerator():
...    mylist = range(3)
...    for i in mylist:
...        yield i*i
...
>>> mygenerator = createGenerator() # create a generator
>>> print(mygenerator) # mygenerator is an object!
<generator object createGenerator at 0xb7555c34>
>>> for i in mygenerator:
...     print(i)
0
1
4

Here it's a useless example, but it's handy when you know your function will return a huge set of values that you will only need to read once.

To master yield, you must understand that when you call the function, the code you have written in the function body does not run. The function only returns the generator object, this is a bit tricky :-)

Then, your code will continue from where it left off each time for uses the generator.

Now the hard part:

The first time the for calls the generator object created from your function, it will run the code in your function from the beginning until it hits yield, then it'll return the first value of the loop. Then, each subsequent call will run another iteration of the loop you have written in the function and return the next value. This will continue until the generator is considered empty, which happens when the function runs without hitting yield. That can be because the loop has come to an end, or because you no longer satisfy an "if/else".


Your code explained

Generator:

# Here you create the method of the node object that will return the generator
def _get_child_candidates(self, distance, min_dist, max_dist):

    # Here is the code that will be called each time you use the generator object:

    # If there is still a child of the node object on its left
    # AND if the distance is ok, return the next child
    if self._leftchild and distance - max_dist < self._median:
        yield self._leftchild

    # If there is still a child of the node object on its right
    # AND if the distance is ok, return the next child
    if self._rightchild and distance + max_dist >= self._median:
        yield self._rightchild

    # If the function arrives here, the generator will be considered empty
    # there is no more than two values: the left and the right children

Caller:

# Create an empty list and a list with the current object reference
result, candidates = list(), [self]

# Loop on candidates (they contain only one element at the beginning)
while candidates:

    # Get the last candidate and remove it from the list
    node = candidates.pop()

    # Get the distance between obj and the candidate
    distance = node._get_dist(obj)

    # If distance is ok, then you can fill the result
    if distance <= max_dist and distance >= min_dist:
        result.extend(node._values)

    # Add the children of the candidate in the candidate's list
    # so the loop will keep running until it will have looked
    # at all the children of the children of the children, etc. of the candidate
    candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))

return result

This code contains several smart parts:

  • The loop iterates on a list, but the list expands while the loop is being iterated :-) It's a concise way to go through all these nested data even if it's a bit dangerous since you can end up with an infinite loop. In this case, candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) exhaust all the values of the generator, but while keeps creating new generator objects which will produce different values from the previous ones since it's not applied on the same node.

  • The extend() method is a list object method that expects an iterable and adds its values to the list.

Usually we pass a list to it:

>>> a = [1, 2]
>>> b = [3, 4]
>>> a.extend(b)
>>> print(a)
[1, 2, 3, 4]

But in your code, it gets a generator, which is good because:

  1. You don't need to read the values twice.
  2. You may have a lot of children and you don't want them all stored in memory.

And it works because Python does not care if the argument of a method is a list or not. Python expects iterables so it will work with strings, lists, tuples, and generators! This is called duck typing and is one of the reasons why Python is so cool. But this is another story, for another question...

You can stop here, or read a little bit to see an advanced use of a generator:

Controlling a generator exhaustion

>>> class Bank(): # Let's create a bank, building ATMs
...    crisis = False
...    def create_atm(self):
...        while not self.crisis:
...            yield "$100"
>>> hsbc = Bank() # When everything's ok the ATM gives you as much as you want
>>> corner_street_atm = hsbc.create_atm()
>>> print(corner_street_atm.next())
$100
>>> print(corner_street_atm.next())
$100
>>> print([corner_street_atm.next() for cash in range(5)])
['$100', '$100', '$100', '$100', '$100']
>>> hsbc.crisis = True # Crisis is coming, no more money!
>>> print(corner_street_atm.next())
<type 'exceptions.StopIteration'>
>>> wall_street_atm = hsbc.create_atm() # It's even true for new ATMs
>>> print(wall_street_atm.next())
<type 'exceptions.StopIteration'>
>>> hsbc.crisis = False # The trouble is, even post-crisis the ATM remains empty
>>> print(corner_street_atm.next())
<type 'exceptions.StopIteration'>
>>> brand_new_atm = hsbc.create_atm() # Build a new one to get back in business
>>> for cash in brand_new_atm:
...    print cash
$100
$100
$100
$100
$100
$100
$100
$100
$100
...

Note: For Python 3, useprint(corner_street_atm.__next__()) or print(next(corner_street_atm))

It can be useful for various things like controlling access to a resource.

Itertools, your best friend

The itertools module contains special functions to manipulate iterables. Ever wish to duplicate a generator? Chain two generators? Group values in a nested list with a one-liner? Map / Zip without creating another list?

Then just import itertools.

An example? Let's see the possible orders of arrival for a four-horse race:

>>> horses = [1, 2, 3, 4]
>>> races = itertools.permutations(horses)
>>> print(races)
<itertools.permutations object at 0xb754f1dc>
>>> print(list(itertools.permutations(horses)))
[(1, 2, 3, 4),
 (1, 2, 4, 3),
 (1, 3, 2, 4),
 (1, 3, 4, 2),
 (1, 4, 2, 3),
 (1, 4, 3, 2),
 (2, 1, 3, 4),
 (2, 1, 4, 3),
 (2, 3, 1, 4),
 (2, 3, 4, 1),
 (2, 4, 1, 3),
 (2, 4, 3, 1),
 (3, 1, 2, 4),
 (3, 1, 4, 2),
 (3, 2, 1, 4),
 (3, 2, 4, 1),
 (3, 4, 1, 2),
 (3, 4, 2, 1),
 (4, 1, 2, 3),
 (4, 1, 3, 2),
 (4, 2, 1, 3),
 (4, 2, 3, 1),
 (4, 3, 1, 2),
 (4, 3, 2, 1)]

Understanding the inner mechanisms of iteration

Iteration is a process implying iterables (implementing the __iter__() method) and iterators (implementing the __next__() method). Iterables are any objects you can get an iterator from. Iterators are objects that let you iterate on iterables.

There is more about it in this article about how for loops work.

How to execute 16-bit installer on 64-bit Win7?

You can't run 16-bit applications (or components) on 64-bit versions of Windows. That emulation layer no longer exists. The 64-bit versions already have to provide a compatibility layer for 32-bit applications.

Support for 16-bit had to be dropped eventually, even in a culture where backwards-compatibility is of sacred import. The transition to 64-bit seemed like as good a time as any. It's hard to imagine anyone out there in the wild that is still using 16-bit applications and seeking to upgrade to 64-bit OSes.

What would be the best way to get round this problem?

If the component itself is 16-bit, then using a virtual machine running a 32-bit version of Windows is your only real choice. Oracle's VirtualBox is free, and a perennial favorite.

If only the installer is 16-bit (and it installs a 32-bit component), then you might be able to use a program like 7-Zip to extract the contents of the installer and install them manually. Let's just say this "solution" is high-risk and you should have few, if any, expectations.

It's high time to upgrade away from 16-bit stuff, like Turbo C++ and Sheridan controls. I've yet to come across anything that the Sheridan controls can do that the built-in controls can't do and haven't been able to do since Windows 95.

Synchronous Requests in Node.js

Though asynchronous style may be the nature of node.js and generally you should not do this, there are some times you want to do this.

I'm writing a handy script to check an API and want not to mess it up with callbacks.

Javascript cannot execute synchronous requests, but C libraries can.

https://github.com/dhruvbird/http-sync

What are .a and .so files?

.a are static libraries. If you use code stored inside them, it's taken from them and embedded into your own binary. In Visual Studio, these would be .lib files.

.so are dynamic libraries. If you use code stored inside them, it's not taken and embedded into your own binary. Instead it's just referenced, so the binary will depend on them and the code from the so file is added/loaded at runtime. In Visual Studio/Windows these would be .dll files (with small .lib files containing linking information).

How to Display blob (.pdf) in an AngularJS app

Adding responseType to the request that is made from angular is indeed the solution, but for me it didn't work until I've set responseType to blob, not to arrayBuffer. The code is self explanatory:

    $http({
            method : 'GET',
            url : 'api/paperAttachments/download/' + id,
            responseType: "blob"
        }).then(function successCallback(response) {
            console.log(response);
             var blob = new Blob([response.data]);
             FileSaver.saveAs(blob, getFileNameFromHttpResponse(response));
        }, function errorCallback(response) {   
        });

Difference between TCP and UDP?

This sentence is a UDP joke, but I'm not sure that you'll get it. The below conversation is a TCP/IP joke:

A: Do you want to hear a TCP/IP joke?
B: Yes, I want to hear a TCP/IP joke.
A: Ok, are you ready to hear a TCP/IP joke?
B: Yes, I'm ready to hear a TCP/IP joke.
A: Well, here is the TCP/IP joke.
A: Did you receive a TCP/IP joke?
B: Yes, I **did** receive a TCP/IP joke.

change array size

In C#, arrays cannot be resized dynamically.

  • One approach is to use System.Collections.ArrayList instead of a native array.

  • Another (faster) solution is to re-allocate the array with a different size and to copy the contents of the old array to the new array.

    The generic function resizeArray (below) can be used to do that.

    public static System.Array ResizeArray (System.Array oldArray, int newSize)  
        {
          int oldSize = oldArray.Length;
          System.Type elementType = oldArray.GetType().GetElementType();
          System.Array newArray = System.Array.CreateInstance(elementType,newSize);
    
          int preserveLength = System.Math.Min(oldSize,newSize);
    
          if (preserveLength > 0)
          System.Array.Copy (oldArray,newArray,preserveLength);
    
         return newArray; 
      }  
    
     public static void Main ()  
           {
            int[] a = {1,2,3};
            a = (int[])ResizeArray(a,5);
            a[3] = 4;
            a[4] = 5;
    
            for (int i=0; i<a.Length; i++)
                  System.Console.WriteLine (a[i]); 
            }
    

Use FontAwesome or Glyphicons with css :before

The accepted answer (as of 2019 JULY 29) is only still valid if you have not started using the more recent SVG-with-JS approach of FontAwesome. In which case you need to follow the instructions on their CSS Pseudo-Elements HowTo. Basically there are three things to watch out for:

  • place the data-attribute on the SCRIPT-Tag "data-search-pseudo-elements" loading the fontawesome.min.js
  • make the pseudo-element itself have display:none
  • proper font-family & font-weight combination for the icon you need: "Font Awesome 5 Free" and 300 (fal/light), 400 (far/regular) or 900 (fas/solid)

How to delete mysql database through shell command

Another suitable way:

$ mysql -u you -p
<enter password>

>>> DROP DATABASE foo;

Can jQuery read/write cookies to a browser?

To answer your question, yes. The other have answered that part, but it also seems like you're asking if that's the best way to do it.

It would probably depend on what you are doing. Typically you would have a user click what items they want to buy (ordering for example). Then they would hit a buy or checkout button. Then the form would send off to a page and process the result. You could do all of that with a cookie but I would find it to be more difficult.

You may want to consider posting your second question in another topic.

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

You should make sure that all the activities in your application are properly defined in the AndroidManifest.xml file.

Also, if they start with a path make sure this path exists.

E.g. this will not work:

<activity android:name=".com.example.android.networkusage.NetworkActivity" android:label="@string/app_name" >

If your application's name is com.example.networkusage (note the missing .android.)

Or better yet, don't include paths when defining an activity inside the manifest. Only put their name (with a dot in front of it).

<activity android:name=".NetworkActivity" android:label="@string/app_name" >

Should I use Python 32bit or Python 64bit

I had trouble running python app (running large dataframes) in 32 - got MemoryError message, while on 64 it worked fine.

How can I rename a conda environment?

Based upon dwanderson's helpful comment, I was able to do this in a Bash one-liner:

conda create --name envpython2 --file <(conda list -n env1 -e )

My badly named env was "env1" and the new one I wish to clone from it is "envpython2".

Disable PHP in directory (including all sub-directories) with .htaccess

<Directory /your/directorypath/>
     php_admin_value engine Off
</Directory>

Mockito verify order / sequence of method calls

With BDD it's

@Test
public void testOrderWithBDD() {


    // Given
    ServiceClassA firstMock = mock(ServiceClassA.class);
    ServiceClassB secondMock = mock(ServiceClassB.class);

    //create inOrder object passing any mocks that need to be verified in order
    InOrder inOrder = inOrder(firstMock, secondMock);

    willDoNothing().given(firstMock).methodOne();
    willDoNothing().given(secondMock).methodTwo();

    // When
    firstMock.methodOne();
    secondMock.methodTwo();

    // Then
    then(firstMock).should(inOrder).methodOne();
    then(secondMock).should(inOrder).methodTwo();


}

"Could not find a version that satisfies the requirement opencv-python"

We were getting the same error.For us, it solved by upgrading pip version (also discussed in FAQ of OpenCV GitHub). Earlier we had pip-7.1.0, post upgrading it to "pip-9.0.2", it successfully installed.

pip install --upgrade pip
pip install opencv-python

What's the difference between unit, functional, acceptance, and integration tests?

unit test: testing of individual module or independent component in an application is known to be unit testing , the unit testing will be done by developer.

integration test: combining all the modules and testing the application to verify the communication and the data flow between the modules are working properly or not , this testing also performed by developers.

funcional test checking the individual functionality of an application is mean to be functional testing

acceptance testing this testing is done by end user or customer whether the build application is according to the customer requirement , and customer specification this is known to be acceptance testing

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

C++ calling base class constructors

The short answer for this is, "because that's what the C++ standard specifies".

Note that you can always specify a constructor that's different from the default, like so:

class Shape  {

  Shape()  {...} //default constructor
  Shape(int h, int w) {....} //some custom constructor


};

class Rectangle : public Shape {
  Rectangle(int h, int w) : Shape(h, w) {...} //you can specify which base class constructor to call

}

The default constructor of the base class is called only if you don't specify which one to call.

How to make grep only match if the entire line matches?

This is with HPUX, if the content of the files has space between words, use this:

egrep "[[:space:]]ABC\.log[[:space:]]" a.tmp

Sublime Text 3 how to change the font size of the file sidebar?

I'm using Sublime Text 3.2.1, a 4k display and a Mac. Tab titles and the sidebar are difficult to read with default ST3 settings. I used the menus Sublime Text -> Preferences -> Settings which opens two files: Preferences.sublime-settings--Default and Preferences.sublime-settings--User.

You can only edit the User file. The Default file is useful for showing what variables you can set. Around line 350 of the Default file are two variables as shown below:

// Magnifies the entire user interface. Sublime Text must be restarted for
// this to take effect.
"ui_scale": 1.0,

// Linux only. Sets the app DPI scale - a decimal number such as 1.0, 1.5,
// 2.0, etc. A value of 0 auto-detects the DPI scale. Sublime Text must be
// restarted for this to take effect.
"dpi_scale": 0,

"dpi_scale": 3.0 did nothing on my Mac "ui_scale": 1.5 worked well. The following is my User file.

{
    "dictionary": "Packages/Language - English/en_US.dic",
    "font_size": 17,
    "ignored_packages":
    [
        "Vintage"
    ],
    "theme": "Default.sublime-theme",
    "ui_scale": 1.5
}

How to add header data in XMLHttpRequest when using formdata?

Check to see if the key-value pair is actually showing up in the request:

In Chrome, found somewhere like: F12: Developer Tools > Network Tab > Whatever request you have sent > "view source" under Response Headers

Depending on your testing workflow, if whatever pair you added isn't there, you may just need to clear your browser cache. To verify that your browser is using your most up-to-date code, you can check the page's sources, in Chrome this is found somewhere like: F12: Developer Tools > Sources Tab > YourJavascriptSrc.js and check your code.

But as other answers have said:

xhttp.setRequestHeader(key, value);

should add a key-value pair to your request header, just make sure to place it after your open() and before your send()

How to make correct date format when writing data to Excel

Old question but still relevant. I've generated a dictionary that gets the appropriate datetime format for each region, here is the helper class I generated:

https://github.com/anakic/ExcelDateTimeFormatHelper/blob/master/FormatHelper.cs

FWIW this is how I went about it:

  1. opened excel, manually entered a datetime into the first cell of a workbook
  2. opened the regions dialog in control panel
  3. used Spy to find out the HWND's of the regions combobox and the apply button so I can use SetForegroundWindow and SendKey to change the region (couldn't find how to change region through the Windows API)
  4. iterated through all regions and for each region asked Excel for the NumberFormat of the cell that contained the date, saved this data to into a file

jQuery UI accordion that keeps multiple sections open?

Simple, create multiple accordian div each representating one anchor tag like:

<div>
<div class="accordion">
<a href = "#">First heading</a>
</div>
<div class="accordion">
<a href = "#">First heading</a>
</div>
</div>

It adds up some markup. But works like a pro...

Eclipse/Java code completion not working

Check the lib of your project. It may be that you have include two such jar files in which same class is available or say one class in code can be refrenced in two jar files. In such case also eclipse stops assisting code as it is totally confused.

Better way to check this is go to the file where assist is not working and comment all imports there, than add imports one by one and check at each import if code-assist is working or not.You can easily find the class with duplicate refrences.

Easy pretty printing of floats in python?

List comps are your friend.

print ", ".join("%.2f" % f for f in list_o_numbers)

Try it:

>>> nums = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999]
>>> print ", ".join("%.2f" % f for f in nums)
9.00, 0.05, 0.03, 0.01

Is there a way to suppress JSHint warning for one given line?

Yes, there is a way. Two in fact. In October 2013 jshint added a way to ignore blocks of code like this:

// Code here will be linted with JSHint.
/* jshint ignore:start */
// Code here will be ignored by JSHint.
/* jshint ignore:end */
// Code here will be linted with JSHint.

You can also ignore a single line with a trailing comment like this:

ignoreThis(); // jshint ignore:line

Can I position an element fixed relative to parent?

It's an old post but i'll leave here my javascript solution just in case someone need it.


_x000D_
_x000D_
// you only need this function_x000D_
function sticky( _el ){_x000D_
  _el.parentElement.addEventListener("scroll", function(){_x000D_
    _el.style.transform = "translateY("+this.scrollTop+"px)";_x000D_
  });_x000D_
}_x000D_
_x000D_
_x000D_
// how to make it work:_x000D_
// get the element you want to be sticky_x000D_
var el = document.querySelector("#blbl > div");_x000D_
// give the element as argument, done._x000D_
sticky(el);
_x000D_
#blbl{_x000D_
  position:relative;_x000D_
  height:200px;  _x000D_
  overflow: auto;_x000D_
  background: #eee;_x000D_
}_x000D_
_x000D_
#blbl > div{_x000D_
  position:absolute; _x000D_
  padding:50px; _x000D_
  top:10px; _x000D_
  left:10px; _x000D_
  background: #f00_x000D_
}
_x000D_
<div id="blbl" >_x000D_
    <div><!-- sticky div --></div> _x000D_
_x000D_
    <br><br><br><br><br><br><br><br><br><br><br><br><br>_x000D_
    <br><br><br><br><br><br><br><br><br><br><br><br><br>_x000D_
    <br><br><br><br><br><br><br><br><br><br><br><br><br>_x000D_
    <br><br><br><br><br><br><br><br><br><br><br><br><br>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Notes

  1. I used transform: translateY(@px) because it should be lightweight to compute, high-performance-animations

  2. I only tried this function with modern browsers, it won't work for old browsers where vendors are required (and IE of course)

Can enums be subclassed to add new elements?

No, you can't do this in Java. Aside from anything else, d would then presumably be an instance of A (given the normal idea of "extends"), but users who only knew about A wouldn't know about it - which defeats the point of an enum being a well-known set of values.

If you could tell us more about how you want to use this, we could potentially suggest alternative solutions.

How to set timeout for a line of c# code

You can use the Task Parallel Library. To be more exact, you can use Task.Wait(TimeSpan):

using System.Threading.Tasks;

var task = Task.Run(() => SomeMethod(input));
if (task.Wait(TimeSpan.FromSeconds(10)))
    return task.Result;
else
    throw new Exception("Timed out");

Is it possible to insert multiple rows at a time in an SQLite database?

If you use the Sqlite manager firefox plugin, it supports bulk inserts from INSERT SQL statements.

Infact it doesn't support this, but Sqlite Browser does (works on Windows, OS X, Linux)

'cannot find or open the pdb file' Visual Studio C++ 2013

There are no problems here this is perfectly normal - it shows informational messages about what debug-info was loaded (and which wasn't) and also that your program executed and exited normally - a zero return code means success.

If you don't see anything on the screen thry running your program with CTRL-F5 instead of just F5.

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

How to avoid pressing Enter with getchar() for reading a single character only?

You could include the 'ncurses' library, and use getch() instead of getchar().

This Handler class should be static or leaks might occur: IncomingHandler

This way worked well for me, keeps code clean by keeping where you handle the message in its own inner class.

The handler you wish to use

Handler mIncomingHandler = new Handler(new IncomingHandlerCallback());

The inner class

class IncomingHandlerCallback implements Handler.Callback{

        @Override
        public boolean handleMessage(Message message) {

            // Handle message code

            return true;
        }
}

Where can I read the Console output in Visual Studio 2015

My problem was that I needed to Reset Window Layout.

Reset Window Layout

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

Why do people make it so hard.

This should be sufficient.

Do not implement the onPostExecute on the async task, rather implement it on the Activity:

public class MainActivity extends Activity 
{

@Override
public void onCreate(Bundle savedInstanceState) {

    //execute the async task 
    MyAsyncTask task = new MyAsyncTask(){
            protected void onPostExecute(String result) {
                //Do your thing
            }       

    }

    task.execute("Param");

}


}

Passing properties by reference in C#

This is not possible. You could say

Client.WorkPhone = GetString(inputString, Client.WorkPhone);

where WorkPhone is a writeable string property and the definition of GetString is changed to

private string GetString(string input, string current) { 
    if (!string.IsNullOrEmpty(input)) {
        return input;
    }
    return current;
}

This will have the same semantics that you seem to be trying for.

This isn't possible because a property is really a pair of methods in disguise. Each property makes available getters and setters that are accessible via field-like syntax. When you attempt to call GetString as you've proposed, what you're passing in is a value and not a variable. The value that you are passing in is that returned from the getter get_WorkPhone.

Merging two arrays in .NET

In case someone else is looking for how to merge two image byte arrays:

        private void LoadImage()
        {
            string src = string.empty;
            byte[] mergedImageData = new byte[0];

            mergedImageData = MergeTwoImageByteArrays(watermarkByteArray, backgroundImageByteArray);
            src = "data:image/png;base64," + Convert.ToBase64String(mergedImageData);
            MyImage.ImageUrl = src;
        }

        private byte[] MergeTwoImageByteArrays(byte[] imageBytes, byte[] imageBaseBytes)
        {
            byte[] mergedImageData = new byte[0];
            using (var msBase = new MemoryStream(imageBaseBytes))
            {
                System.Drawing.Image imgBase = System.Drawing.Image.FromStream(msBase);
                Graphics gBase = Graphics.FromImage(imgBase);
                using (var msInfo = new MemoryStream(imageBytes))
                {
                    System.Drawing.Image imgInfo = System.Drawing.Image.FromStream(msInfo);
                    Graphics gInfo = Graphics.FromImage(imgInfo);
                    gBase.DrawImage(imgInfo, new Point(0, 0));
                    //imgBase.Save(Server.MapPath("_____testImg.png"), ImageFormat.Png);
                    MemoryStream mergedImageStream = new MemoryStream();
                    imgBase.Save(mergedImageStream, ImageFormat.Png);
                    mergedImageData = mergedImageStream.ToArray();
                    mergedImageStream.Close();
                }
            }
            return mergedImageData;
        }

Downloading all maven dependencies to a directory NOT in repository?

Based on @Raghuram answer, I find a tutorial on Copying project dependencies, Just:

  1. Open your project pom.xml file and find this:

    <project>
      [...]
      <build>
        <plugins>
          ...
        </plugins>
      </build>
      [...]
    </project>
    
  2. Than replace the <plugins> ... </plugins> with:

    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>3.0.0</version>
        <executions>
          <execution>
            <id>copy-dependencies</id>
            <phase>package</phase>
            <goals>
              <goal>copy-dependencies</goal>
            </goals>
            <configuration>
              <outputDirectory>${project.build.directory}/alternateLocation</outputDirectory>
              <overWriteReleases>false</overWriteReleases>
              <overWriteSnapshots>false</overWriteSnapshots>
              <overWriteIfNewer>true</overWriteIfNewer>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
    
  3. And call maven within the command line mvn dependency:copy-dependencies

After it finishes, it will create the folder target/dependency within all the jar's dependencies on the current directory where the pom.xml lives.

ADB Android Device Unauthorized

Try forcing ADB to create new keys.

  • On Linux:

    $ mv ~/.android/adbkey ~/.android/adbkey.old
    $ mv ~/.android/adbkey.pub ~/.android/adbkey.pub.old
    $ adb kill-server
    $ adb start-server
    
  • On Windows 10 (thank you, Pau Coma Ramirez, Naveen and d4c0d312!):

    • Go to %HOMEPATH%\Android\.android\
    • Look for files called adbkey or adbkey.pub.
    • Delete these files. Or, if you want to be on the safe side, move them to another directory.
    • Repeat the above steps in %USERPROFILE%\.android\
    • Try again

After this I didn't even need to unplug my phone: the authorization prompt was already there. Good luck!

Python regex to match dates

Well, from my understanding, simply for matching this format in a given string, I prefer this regular expression:

pattern='[0-9|/]+'

to match the format in a more strict way, the following works:

pattern='(?:[0-9]{2}/){2}[0-9]{2}'

Personally, I cannot agree with unutbu's answer since sometimes we use regular expression for "finding" and "extract", not only "validating".

Difference between Fact table and Dimension table?

This is to answer the part:

I was trying to understand whether dimension tables can be fact table as well or not?

The short answer (INMO) is No.That is because the 2 types of tables are created for different reasons. However, from a database design perspective, a dimension table could have a parent table as the case with the fact table which always has a dimension table (or more) as a parent. Also, fact tables may be aggregated, whereas Dimension tables are not aggregated. Another reason is that fact tables are not supposed to be updated in place whereas Dimension tables could be updated in place in some cases.

More details:

Fact and dimension tables appear in a what is commonly known as a Star Schema. A primary purpose of star schema is to simplify a complex normalized set of tables and consolidate data (possibly from different systems) into one database structure that can be queried in a very efficient way.

On its simplest form, it contains a fact table (Example: StoreSales) and a one or more dimension tables. Each Dimension entry has 0,1 or more fact tables associated with it (Example of dimension tables: Geography, Item, Supplier, Customer, Time, etc.). It would be valid also for the dimension to have a parent, in which case the model is of type "Snow Flake". However, designers attempt to avoid this kind of design since it causes more joins that slow performance. In the example of StoreSales, The Geography dimension could be composed of the columns (GeoID, ContenentName, CountryName, StateProvName, CityName, StartDate, EndDate)

In a Snow Flakes model, you could have 2 normalized tables for Geo information, namely: Content Table, Country Table.

You can find plenty of examples on Star Schema. Also, check this out to see an alternative view on the star schema model Inmon vs. Kimball. Kimbal has a good forum you may also want to check out here: Kimball Forum.

Edit: To answer comment about examples for 4NF:

  • Example for a fact table violating 4NF:

Sales Fact (ID, BranchID, SalesPersonID, ItemID, Amount, TimeID)

  • Example for a fact table not violating 4NF:

AggregatedSales (BranchID, TotalAmount)

Here the relation is in 4NF

The last example is rather uncommon.

IF/ELSE Stored Procedure

Nick is right. The next error is the else should be else if (you currently have a boolean expression in your else which makes no sense). Here is what it should be

ELSE IF(@Trans_type = 'subscr_cancel')
    BEGIN
    SET @tmpType = 'basic'
    END

You currently have the following (which is wrong):

ELSE(@Trans_type = 'subscr_cancel')
    BEGIN
    SET @tmpType = 'basic'
    END

Here's a tip for the future- double click on the error and SQL Server management Studio will go to the line where the error resides. If you think SQL Server gives cryptic errors (which I don't think it does), then you haven't worked with Oracle!

How do I iterate through children elements of a div using jQuery?

If you need to loop through child elements recursively:

function recursiveEach($element){
    $element.children().each(function () {
        var $currentElement = $(this);
        // Show element
        console.info($currentElement);
        // Show events handlers of current element
        console.info($currentElement.data('events'));
        // Loop her children
        recursiveEach($currentElement);
    });
}

// Parent div
recursiveEach($("#div"));   

NOTE: In this example I show the events handlers registered with an object.

PowerShell: Comparing dates

Late but more complete answer in point of getting the most advanced date from $Output

## Q:\test\2011\02\SO_5097125.ps1
## simulate object input with a here string 
$Output = @"
"Date"
"Monday, April 08, 2013 12:00:00 AM"
"Friday, April 08, 2011 12:00:00 AM"
"@ -split '\r?\n' | ConvertFrom-Csv

## use Get-Date and calculated property in a pipeline
$Output | Select-Object @{n='Date';e={Get-Date $_.Date}} |
    Sort-Object Date | Select-Object -Last 1 -Expand Date

## use Get-Date in a ForEach-Object
$Output.Date | ForEach-Object{Get-Date $_} |
    Sort-Object | Select-Object -Last 1

## use [datetime]::ParseExact
## the following will only work if your locale is English for day, month day abbrev.
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',$Null)
} | Sort-Object | Select-Object -Last 1

## for non English locales
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',[cultureinfo]::InvariantCulture)
} | Sort-Object | Select-Object -Last 1

## in case the day month abbreviations are in other languages, here German
## simulate object input with a here string 
$Output = @"
"Date"
"Montag, April 08, 2013 00:00:00"
"Freidag, April 08, 2011 00:00:00"
"@ -split '\r?\n' | ConvertFrom-Csv
$CIDE = New-Object System.Globalization.CultureInfo("de-DE")
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy HH:mm:ss',$CIDE)
} | Sort-Object | Select-Object -Last 1

Use superscripts in R axis labels

The other option in this particular case would be to type the degree symbol: °

R seems to handle it fine. Type Option-k on a Mac to get it. Not sure about other platforms.

Jquery Open in new Tab (_blank)

Setting links on the page woud require a combination of @Ravi and @ncksllvn's answers:

// Find link in $(".product-item") and set "target" attribute to "_blank".
$(this).find("a").attr("target", "_blank");

For opening the page in another window, see this question: jQuery click _blank And see this reference for window.open options for customization.

Update:

You would need something along:

$(document).ready(function() {
  $(".product-item").click(function() {
    var productLink = $(this).find("a");

    productLink.attr("target", "_blank");
    window.open(productLink.attr("href"));

    return false;
  });
});

Note the usage of .attr():

$element.attr("attribute_name")                   // Get value of attribute.
$element.attr("attribute_name", attribute_value)  // Set value of attribute.