Programs & Examples On #Console output

How do I write output in same place on the console?

Python 2

I like the following:

print 'Downloading File FooFile.txt [%d%%]\r'%i,

Demo:

import time

for i in range(100):
    time.sleep(0.1)
    print 'Downloading File FooFile.txt [%d%%]\r'%i,

Python 3

print('Downloading File FooFile.txt [%d%%]\r'%i, end="")

Demo:

import time

for i in range(100):
    time.sleep(0.1)
    print('Downloading File FooFile.txt [%d%%]\r'%i, end="")

PyCharm Debugger Console with Python 3

# On PyCharm Debugger console, \r needs to come before the text.
# Otherwise, the text may not appear at all, or appear inconsistently.
# tested on PyCharm 2019.3, Python 3.6

import time

print('Start.')
for i in range(100):
    time.sleep(0.02)
    print('\rDownloading File FooFile.txt [%d%%]'%i, end="")
print('\nDone.')

How do you implement a re-try-catch?

If not all exceptions warrant a retry, only some. And if at least one try has to be made, Here is an alternative utility method:

void runWithRetry(Runnable runnable, Class<Exception> exClass, int maxRetries) {
        Exception err = null;
        do {
            maxRetries--;
            try {
                runnable.run();
                err = null;
            } catch (Exception e) {
                if(exClass.isAssignableFrom(e.getClass())){
                    err = e;
                }else {
                    throw e;
                }
            }
        } while (err != null && maxRetries > 0);

        if (err != null) {
            throw err;
        }
    }

Usage:

    runWithRetry(() -> {
       // do something
    }, TimeoutException.class, 5)

Java : Accessing a class within a package, which is the better way?

No, it doesn't save you memory.

Also note that you don't have to import Math at all. Everything in java.lang is imported automatically.

A better example would be something like an ArrayList

import java.util.ArrayList;
....
ArrayList<String> i = new ArrayList<String>();

Note I'm importing the ArrayList specifically. I could have done

import java.util.*; 

But you generally want to avoid large wildcard imports to avoid the problem of collisions between packages.

how to pass value from one php page to another using session

Solution using just POST - no $_SESSION

page1.php

<form action="page2.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
</form>

page2.php

<?php
    // this page outputs the contents of the textarea if posted
    $textarea1 = ""; // set var to avoid errors
    if(isset($_POST['textarea1'])){
        $textarea1 = $_POST['textarea1']
    }
?>
<textarea><?php echo $textarea1;?></textarea>

Solution using $_SESSION and POST

page1.php

<?php

    session_start(); // needs to be before anything else on page to use $_SESSION
    $textarea1 = "";
    if(isset($_POST['textarea1'])){
        $_SESSION['textarea1'] = $_POST['textarea1'];
    }

?>


<form action="page1.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
</form>
<br /><br />
<a href="page2.php">Go to page2</a>

page2.php

<?php
    session_start(); // needs to be before anything else on page to use $_SESSION
    // this page outputs the textarea1 from the session IF it exists
    $textarea1 = ""; // set var to avoid errors
    if(isset($_SESSION['textarea1'])){
        $textarea1 = $_SESSION['textarea1']
    }
?>
<textarea><?php echo $textarea1;?></textarea>

WARNING!!! - This contains no validation!!!

Obtain smallest value from array in Javascript?

The tersest expressive code to find the minimum value is probably rest parameters:

_x000D_
_x000D_
const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]_x000D_
const min = Math.min(...arr)_x000D_
console.log(min)
_x000D_
_x000D_
_x000D_


Rest parameters are essentially a convenient shorthand for Function.prototype.apply when you don't need to change the function's context:

_x000D_
_x000D_
var arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]_x000D_
var min = Math.min.apply(Math, arr)_x000D_
console.log(min)
_x000D_
_x000D_
_x000D_


This is also a great use case for Array.prototype.reduce:

_x000D_
_x000D_
const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]_x000D_
const min = arr.reduce((a, b) => Math.min(a, b))_x000D_
console.log(min)
_x000D_
_x000D_
_x000D_

It may be tempting to pass Math.min directly to reduce, however the callback receives additional parameters:

callback (accumulator, currentValue, currentIndex, array)

In this particular case it may be a bit verbose. reduce is particularly useful when you have a collection of complex data that you want to aggregate into a single value:

_x000D_
_x000D_
const arr = [{name: 'Location 1', distance: 14}, {name: 'Location 2', distance: 58}, {name: 'Location 3', distance: 20}, {name: 'Location 4', distance: 77}, {name: 'Location 5', distance: 66}, {name: 'Location 6', distance: 82}, {name: 'Location 7', distance: 42}, {name: 'Location 8', distance: 67}, {name: 'Location 9', distance: 42}, {name: 'Location 10', distance: 4}]_x000D_
const closest = arr.reduce(_x000D_
  (acc, loc) =>_x000D_
    acc.distance < loc.distance_x000D_
      ? acc_x000D_
      : loc_x000D_
)_x000D_
console.log(closest)
_x000D_
_x000D_
_x000D_


And of course you can always use classic iteration:

_x000D_
_x000D_
var arr,_x000D_
  i,_x000D_
  l,_x000D_
  min_x000D_
_x000D_
arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]_x000D_
min = Number.POSITIVE_INFINITY_x000D_
for (i = 0, l = arr.length; i < l; i++) {_x000D_
  min = Math.min(min, arr[i])_x000D_
}_x000D_
console.log(min)
_x000D_
_x000D_
_x000D_

...but even classic iteration can get a modern makeover:

_x000D_
_x000D_
const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]_x000D_
let min = Number.POSITIVE_INFINITY_x000D_
for (const value of arr) {_x000D_
  min = Math.min(min, value)_x000D_
}_x000D_
console.log(min)
_x000D_
_x000D_
_x000D_

How can I use querySelector on to pick an input element by name?

I know this is old, but I recently faced the same issue and I managed to pick the element by accessing only the attribute like this: document.querySelector('[name="your-selector-name-here"]');

Just in case anyone would ever need this :)

Change status bar color with AppCompat ActionBarActivity

I'm not sure I understand the problem.

I you want to change the status bar color programmatically (and provided the device has Android 5.0) then you can use Window.setStatusBarColor(). It shouldn't make a difference whether the activity is derived from Activity or ActionBarActivity.

Just try doing:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    window.setStatusBarColor(Color.BLUE);
}

Just tested this with ActionBarActivity and it works alright.


Note: Setting the FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag programmatically is not necessary if your values-v21 styles file has it set already, via:

    <item name="android:windowDrawsSystemBarBackgrounds">true</item>

Git Server Like GitHub?

You might consider Gitblit, an open-source, integrated, pure Java Git server, viewer, and repository manager for small workgroups.

How to set base url for rest in spring boot?

Try using a PathMatchConfigurer (Spring Boot 2.x):

@Configuration
public class WebMvcConfig implements WebMvcConfigurer  {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.addPathPrefix("api", HandlerTypePredicate.forAnnotation(RestController.class));
    }
}

Visual Studio opens the default browser instead of Internet Explorer

For MVC3 you don't have to add any dummy files to set a certain browser. All you have to do is:

  • "Show all files" for the project
  • go to bin folder
  • right click the only .xml file to find the "Browse With..." option

setting MVC3 project default browser

How can I display a pdf document into a Webview?

Opening a pdf using google docs is a bad idea in terms of user experience. It is really slow and unresponsive.

Solution after API 21

Since api 21, we have PdfRenderer which helps converting a pdf to Bitmap. I've never used it but is seems easy enough.

Solution for any api level

Other solution is to download the PDF and pass it via Intent to a dedicated PDF app which will do a banger job displaying it. Fast and nice user experience, especially if this feature is not central in your app.

Use this code to download and open the PDF

public class PdfOpenHelper {

public static void openPdfFromUrl(final String pdfUrl, final Activity activity){
    Observable.fromCallable(new Callable<File>() {
        @Override
        public File call() throws Exception {
            try{
                URL url = new URL(pdfUrl);
                URLConnection connection = url.openConnection();
                connection.connect();

                // download the file
                InputStream input = new BufferedInputStream(connection.getInputStream());
                File dir = new File(activity.getFilesDir(), "/shared_pdf");
                dir.mkdir();
                File file = new File(dir, "temp.pdf");
                OutputStream output = new FileOutputStream(file);

                byte data[] = new byte[1024];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
                return file;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<File>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(File file) {
                    String authority = activity.getApplicationContext().getPackageName() + ".fileprovider";
                    Uri uriToFile = FileProvider.getUriForFile(activity, authority, file);

                    Intent shareIntent = new Intent(Intent.ACTION_VIEW);
                    shareIntent.setDataAndType(uriToFile, "application/pdf");
                    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    if (shareIntent.resolveActivity(activity.getPackageManager()) != null) {
                        activity.startActivity(shareIntent);
                    }
                }
            });
}

}

For the Intent to work, you need to create a FileProvider to grant permission to the receiving app to open the file.

Here is how you implement it: In your Manifest:

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">

        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />

    </provider>

Finally create a file_paths.xml file in the resources foler

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <files-path name="shared_pdf" path="shared_pdf"/>
</paths>

Hope this helps =)

Check if returned value is not null and if so assign it, in one line, with one method call

Since Java 9 you have Objects#requireNonNullElse which does:

public static <T> T requireNonNullElse(T obj, T defaultObj) {
    return (obj != null) ? obj : requireNonNull(defaultObj, "defaultObj");
}

Your code would be

dinner = Objects.requireNonNullElse(cage.getChicken(), getFreeRangeChicken());

Which is 1 line and calls getChicken() only once, so both requirements are satisfied.

Note that the second argument cannot be null as well; this method forces non-nullness of the returned value.

Consider also the alternative Objects#requireNonNullElseGet:

public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier)

which does not even evaluate the second argument if the first is not null, but does have the overhead of creating a Supplier.

How to get the real path of Java application at runtime?

And what about using this.getClass().getProtectionDomain().getCodeSource().getLocation()?

jquery if div id has children

You can also check whether div has specific children or not,

if($('#myDiv').has('select').length>0)
{
   // Do something here.
   console.log("you can log here");

}

Lining up labels with radio buttons in bootstrap

In Bootstrap 4 you can use the form-check-inline class.

<div class="form-check form-check-inline">
  <input class="form-check-input" type="radio" name="queryFieldName" id="option1" value="1">
  <label class="form-check-label" for="option1">First</label>
</div>
<div class="form-check form-check-inline">
  <input class="form-check-input" type="radio" name="queryFieldName" id="option2" value="2">
  <label class="form-check-label" for="option2">Second</label>
</div>

Comparing two files in linux terminal

If you prefer the diff output style from git diff, you can use it with the --no-index flag to compare files not in a git repository:

git diff --no-index a.txt b.txt

Using a couple of files with around 200k file name strings in each, I benchmarked (with the built-in timecommand) this approach vs some of the other answers here:

git diff --no-index a.txt b.txt
# ~1.2s

comm -23 <(sort a.txt) <(sort b.txt)
# ~0.2s

diff a.txt b.txt
# ~2.6s

sdiff a.txt b.txt
# ~2.7s

vimdiff a.txt b.txt
# ~3.2s

comm seems to be the fastest by far, while git diff --no-index appears to be the fastest approach for diff-style output.


Update 2018-03-25 You can actually omit the --no-index flag unless you are inside a git repository and want to compare untracked files within that repository. From the man pages:

This form is to compare the given two paths on the filesystem. You can omit the --no-index option when running the command in a working tree controlled by Git and at least one of the paths points outside the working tree, or when running the command outside a working tree controlled by Git.

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

Hide/Show components in react native

Actually, in iOS development by react-native when I use display: 'none' or something like below:

const styles = StyleSheet.create({
  disappearImage: {
    width: 0,
    height: 0
  }
});

The iOS doesn't load anything else of the Image component like onLoad or etc, so I decided to use something like below:

const styles = StyleSheet.create({
  disappearImage: {
    width: 1,
    height: 1,
    position: 'absolute',
    top: -9000,
    opacity: 0
  }
});

How to check if std::map contains a key without doing insert?

Your desideratum,map.contains(key), is scheduled for the draft standard C++2a. In 2017 it was implemented by gcc 9.2. It's also in the current clang.

Get last key-value pair in PHP array

Another solution cold be:

$value = $arr[count($arr) - 1];

The above will count the amount of array values, substract 1 and then return the value.

Note: This can only be used if your array keys are numeric.

Is it possible to style a select box?

We've found a simple and decent way to do this. It's cross-browser,degradable, and doesn't break a form post. First set the select box's opacity to 0.

.select { 
    opacity : 0;
    width: 200px;
    height: 15px;
}

<select class='select'>
    <option value='foo'>bar</option>    
</select>

this is so you can still click on it

Then make div with the same dimensions as the select box. The div should lay under the select box as the background. Use { position: absolute } and z-index to achieve this.

.div {
    width: 200px;
    height: 15px;
    position: absolute;
    z-index: 0;
}

<div class='.div'>{the text of the the current selection updated by javascript}</div>
<select class='select'>
    <option value='foo'>bar</option>    
</select>

Update the div's innerHTML with javascript. Easypeasy with jQuery:

$('.select').click(function(event)) { 
    $('.div').html($('.select option:selected').val());
}

That's it! Just style your div instead of the select box. I haven't tested the above code so you'll probably need tweak it. But hopefully you get the gist.

I think this solution beats {-webkit-appearance: none;}. What browsers should do at the very most is dictate interaction with form elements, but definitely not how their initially displayed on the page as that breaks site design.

How to generate different random numbers in a loop in C++?

The time function probably returns the same value during each iteration of the loop.

Try initializing the random seed before the loop.

Loop through columns and add string lengths as new columns

You need to use [[, the programmatic equivalent of $. Otherwise, for example, when i is col1, R will look for df$i instead of df$col1.

for(i in names(df)){
  df[[paste(i, 'length', sep="_")]] <- str_length(df[[i]])
}

Disable double-tap "zoom" option in browser on touch devices

* {
    -ms-touch-action: manipulation;
    touch-action: manipulation;
}

Disable double tap to zoom on touch screens. Internet explorer included.

Simple way to create matrix of random numbers

random_matrix = [[random.random for j in range(collumns)] for i in range(rows)
for i in range(rows):
    print random_matrix[i]

How to mark a build unstable in Jenkins when running shell scripts

The TextFinder is good only if the job status hasn't been changed from SUCCESS to FAILED or ABORTED. For such cases, use a groovy script in the PostBuild step:

errpattern = ~/TEXT-TO-LOOK-FOR-IN-JENKINS-BUILD-OUTPUT.*/;
manager.build.logFile.eachLine{ line ->
    errmatcher=errpattern.matcher(line)
    if (errmatcher.find()) {
        manager.build.@result = hudson.model.Result.NEW-STATUS-TO-SET
    }
 }

See more details in a post I've wrote about it: http://www.tikalk.com/devops/JenkinsJobStatusChange/

Left-pad printf with spaces

If you want exactly 40 spaces before the string then you should just do:

printf("                                        %s\n", myStr );

If that is too dirty, you can do (but it will be slower than manually typing the 40 spaces): printf("%40s%s", "", myStr );

If you want the string to be lined up at column 40 (that is, have up to 39 spaces proceeding it such that the right most character is in column 40) then do this: printf("%40s", myStr);

You can also put "up to" 40 spaces AfTER the string by doing: printf("%-40s", myStr);

document.getElementById().value doesn't set the value

Your response is almost certainly a string. You need to make sure it gets converted to a number:

document.getElementById("points").value= new Number(request.responseText);

You might take a closer look at your responseText. It sound like you are getting a string that contains quotes. If you are getting JSON data via AJAX, you might have more consistent results running it through JSON.parse().

document.getElementById("points").value= new Number(JSON.parse(request.responseText));

appending list but error 'NoneType' object has no attribute 'append'

You are not supposed to assign it to any variable, when you append something in the list, it updates automatically. use only:-

last_list.append(p.last)

if you assign this to a variable "last_list" again, it will no more be a list (will become a none type variable since you haven't declared the type for that) and append will become invalid in the next run.

Docker remove <none> TAG images

docker rmi $(docker images -a -q)

Stated the following images where in use. I think this command gets rid of unwanted images.

'module' object has no attribute 'DataFrame'

The code presented here doesn't show this discrepancy, but sometimes I get stuck when invoking dataframe in all lower case.

Switching to camel-case (pd.DataFrame()) cleans up the problem.

Parse time of format hh:mm:ss

If you want to extract the hours, minutes and seconds, try this:

String inputDate = "12:00:00";
String[] split = inputDate.split(":");
int hours = Integer.valueOf(split[0]);
int minutes = Integer.valueOf(split[1]);
int seconds = Integer.valueOf(split[2]);

APT command line interface-like yes/no input?

I modified fmark's answer to by python 2/3 compatible more pythonic.

See ipython's utility module if you are interested in something with more error handling

# PY2/3 compatibility
from __future__ import print_function
# You could use the six package for this
try:
    input_ = raw_input
except NameError:
    input_ = input

def query_yes_no(question, default=True):
    """Ask a yes/no question via standard input and return the answer.

    If invalid input is given, the user will be asked until
    they acutally give valid input.

    Args:
        question(str):
            A question that is presented to the user.
        default(bool|None):
            The default value when enter is pressed with no value.
            When None, there is no default value and the query
            will loop.
    Returns:
        A bool indicating whether user has entered yes or no.

    Side Effects:
        Blocks program execution until valid input(y/n) is given.
    """
    yes_list = ["yes", "y"]
    no_list = ["no", "n"]

    default_dict = {  # default => prompt default string
        None: "[y/n]",
        True: "[Y/n]",
        False: "[y/N]",
    }

    default_str = default_dict[default]
    prompt_str = "%s %s " % (question, default_str)

    while True:
        choice = input_(prompt_str).lower()

        if not choice and default is not None:
            return default
        if choice in yes_list:
            return True
        if choice in no_list:
            return False

        notification_str = "Please respond with 'y' or 'n'"
        print(notification_str)

WPF MVVM ComboBox SelectedItem or SelectedValue not working

I solved the problem by adding dispatcher in UserControl_Loaded event

 Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() =>
 {
     combobox.SelectedIndex = 0;
 }));

Best way to convert IList or IEnumerable to Array

Which version of .NET are you using? If it's .NET 3.5, I'd just call ToArray() and be done with it.

If you only have a non-generic IEnumerable, do something like this:

IEnumerable query = ...;
MyEntityType[] array = query.Cast<MyEntityType>().ToArray();

If you don't know the type within that method but the method's callers do know it, make the method generic and try this:

public static void T[] PerformQuery<T>()
{
    IEnumerable query = ...;
    T[] array = query.Cast<T>().ToArray();
    return array;
}

GCM with PHP (Google Cloud Messaging)

<?php
    // Replace with the real server API key from Google APIs
    $apiKey = "your api key";

    // Replace with the real client registration IDs
    $registrationIDs = array( "reg id1","reg id2");

    // Message to be sent
    $message = "hi Shailesh";

    // Set POST variables
    $url = 'https://android.googleapis.com/gcm/send';

    $fields = array(
        'registration_ids' => $registrationIDs,
        'data' => array( "message" => $message ),
    );
    $headers = array(
        'Authorization: key=' . $apiKey,
        'Content-Type: application/json'
    );

    // Open connection
    $ch = curl_init();

    // Set the URL, number of POST vars, POST data
    curl_setopt( $ch, CURLOPT_URL, $url);
    curl_setopt( $ch, CURLOPT_POST, true);
    curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
    //curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields));

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    // curl_setopt($ch, CURLOPT_POST, true);
    // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields));

    // Execute post
    $result = curl_exec($ch);

    // Close connection
    curl_close($ch);
    echo $result;
    //print_r($result);
    //var_dump($result);
?>

How do I find out which keystore was used to sign an app?

There are many freewares to examine the certificates and key stores such as KeyStore Explorer.

Unzip the apk and open the META-INF/?.RSA file. ? shall be CERT or ANDROID or may be something else. It will display all the information associated with your apk.

Failed to authenticate on SMTP server error using gmail

If you still get this error when sending email: "Failed to authenticate on SMTP server with username "[email protected]" using 3 possible authenticators"

You may try one of these methods:

  1. Go to https://accounts.google.com/UnlockCaptcha, click continue and unlock your account for access through other media/sites.

  2. Using a double quote password: "your password" <-- this one also solved my problem.

Correct owner/group/permissions for Apache 2 site files/folders under Mac OS X?

This is the most restrictive and safest way I've found, as explained here for hypothetical ~/my/web/root/ directory for your web content:

  • For each parent directory leading to your web root (e.g. ~/my, ~/my/web, ~/my/web/root):
    • chmod go-rwx DIR (nobody other than owner can access content)
    • chmod go+x DIR (to allow "users" including _www to "enter" the dir)
  • sudo chgrp -R _www ~/my/web/root (all web content is now group _www)
  • chmod -R go-rwx ~/my/web/root (nobody other than owner can access web content)
  • chmod -R g+rx ~/my/web/root (all web content is now readable/executable/enterable by _www)

All other solutions leave files open to other local users (who are part of the "staff" group as well as obviously being in the "o"/others group). These users may then freely browse and access DB configurations, source code, or other sensitive details in your web config files and scripts if such are part of your content. If this is not an issue for you, then by all means go with one of the simpler solutions.

How to initialize HashSet values by construction?

This is an elegant solution:

public static final <T> Set<T> makeSet(@SuppressWarnings("unchecked") T... o) {
        return new HashSet<T>() {
            private static final long serialVersionUID = -3634958843858172518L;
            {
                for (T x : o)
                   add(x);
            }
        };
}

How to load image to WPF in runtime?

Make sure that your sas.png is marked as Build Action: Content and Copy To Output Directory: Copy Always in its Visual Studio Properties...

I think the C# source code goes like this...

Image image = new Image();
image.Source = (new ImageSourceConverter()).ConvertFromString("pack://application:,,,/Bilder/sas.png") as ImageSource;

and XAML should be

<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0" 
       Name="image1" Stretch="Fill" VerticalAlignment="Top" 
       Source="../Bilder/sas.png"
       Width="350" />  

EDIT

Dynamically I think XAML would provide best way to load Images ...

<Image Source="{Binding Converter={StaticResource MyImageSourceConverter}}"
       x:Name="MyImage"/>

where image.DataContext is string path.

MyImage.DataContext = "pack://application:,,,/Bilder/sas.png";

public class MyImageSourceConverter : IValueConverter
{
    public object Convert(object value_, Type targetType_, 
    object parameter_, System.Globalization.CultureInfo culture_)
    {
        return (new ImageSourceConverter()).ConvertFromString (value.ToString());
    }

    public object ConvertBack(object value, Type targetType, 
    object parameter, CultureInfo culture)
    {
          throw new NotImplementedException();
    }
}

Now as you set a different data context, Image would be automatically loaded at runtime.

Setting a JPA timestamp column to be generated by the database?

@Column(nullable = false, updatable = false)
@CreationTimestamp
private Date created_at;

this worked for me. more info

How to add property to a class dynamically?

This is a little different than what OP wanted, but I rattled my brain until I got a working solution, so I'm putting here for the next guy/gal

I needed a way to specify dynamic setters and getters.

class X:
    def __init__(self, a=0, b=0, c=0):
        self.a = a
        self.b = b
        self.c = c

    @classmethod
    def _make_properties(cls, field_name, inc):
        _inc = inc

        def _get_properties(self):
            if not hasattr(self, '_%s_inc' % field_name):
                setattr(self, '_%s_inc' % field_name, _inc)
                inc = _inc
            else:
                inc = getattr(self, '_%s_inc' % field_name)

            return getattr(self, field_name) + inc

        def _set_properties(self, value):
            setattr(self, '_%s_inc' % field_name, value)

        return property(_get_properties, _set_properties)

I know my fields ahead of time so im going to create my properties. NOTE: you cannot do this PER instance, these properties will exist on the class!!!

for inc, field in enumerate(['a', 'b', 'c']):
    setattr(X, '%s_summed' % field, X._make_properties(field, inc))

Let's test it all now..

x = X()
assert x.a == 0
assert x.b == 0
assert x.c == 0

assert x.a_summed == 0  # enumerate() set inc to 0 + 0 = 0
assert x.b_summed == 1  # enumerate() set inc to 1 + 0 = 1
assert x.c_summed == 2  # enumerate() set inc to 2 + 0 = 2

# we set the variables to something
x.a = 1
x.b = 2
x.c = 3

assert x.a_summed == 1  # enumerate() set inc to 0 + 1 = 1
assert x.b_summed == 3  # enumerate() set inc to 1 + 2 = 3
assert x.c_summed == 5  # enumerate() set inc to 2 + 3 = 5

# we're changing the inc now
x.a_summed = 1 
x.b_summed = 3 
x.c_summed = 5

assert x.a_summed == 2  # we set inc to 1 + the property was 1 = 2
assert x.b_summed == 5  # we set inc to 3 + the property was 2 = 5
assert x.c_summed == 8  # we set inc to 5 + the property was 3 = 8

Is it confusing? Yes, sorry I couldn't come up with any meaningful real world examples. Also, this is not for the light hearted.

How can I delete (not disable) ActiveX add-ons in Internet Explorer (7 and 8 Beta 2)?

Start -> Control Panel -> Programs and Features, search for the Add-ons you would like to uninstall and click on particular one to uninstall.

Yes, I tried uninstalling from IE, Tools -> Manage Add-ons and then click "More Information" link at the bottom, however the "Remove" button was disabled. This didn't work.

Above mentioned solution for uninstalling from "Programs and Features" works.

Credit card expiration dates - Inclusive or exclusive?

In my experience, it has expired at the end of that month. That is based on the fact that I can use it during that month, and that month is when my bank sends a new one.

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

best way to get the key of a key/value javascript object

for showing as a string, simply use:

console.log("they are: " + JSON.stringify(foo));

Spring - download response as a file

I've wrestled with this myself, trying to make it work from the server. Couldn't. Instead...

  1. To clarify on @dnc253's answer, $window.open(URL) is a method for having an Angular application open a given URL in another window. (It's really just a testable angular proxy for the universal window.open().) This is a great solution, preserves your history, and gets the file downloaded and possibly renders it in that fresh browser window if that's supported. But it often runs into popup blockers, which is a huge problem for reliability. Users often simply don't understand what's going on with them. So, if you don't mind immediately downloading the file with the current window, you can simply use the equally effective universal javascript method: location.href = "uriString", which works like a charm for me. Angular doesn't even realize anything has happened. I call it in a promise handler for once my POST/PUT operation has completed. If need be, have the POST/PUT return the URL to call, if you can't already infer it. You'll get the same behavior for the user as if it had downloaded in response to the PUT/POST. For example:

    $http.post(url, payload).then(function(returnData){
        var uriString = parseReturn(returnData);
        location.href="uriString"
    })
    
  2. You can, in fact, download something directly from an XHR request, but it requires full support for the HTML5 file API and is usually more trouble than it's worth unless you need to perform local transformations upon the file before you make it available to the user. (Sadly, I lack the time to provide details on that but there are other SO posts about using it.)

Develop Android app using C#

You could use Mono for Android:

http://xamarin.com/monoforandroid

An alternative is dot42:

http://www.dot42.com/

dot42 provides a free community licence as well as a professional licence for $399.

Git fast forward VS no fast forward merge

When we work on development environment and merge our code to staging/production branch then Git no fast forward can be a better option. Usually when we work in development branch for a single feature we tend to have multiple commits. Tracking changes with multiple commits can be inconvenient later on. If we merge with staging/production branch using Git no fast forward then it will have only 1 commit. Now anytime we want to revert the feature, just revert that commit. Life is easy.

Ansible: How to delete files and folders inside a directory?

Below code worked for me :

- name: Get directory listing
  become: yes
  find:
    paths: /applications/cache
    patterns: '*'
    hidden: yes
  register: directory_content_result

- name: Remove directory content
  become: yes
  file:
    path: "{{ item.path }}"
    state: absent
  with_items: "{{ directory_content_result.files }}"

jQuery return ajax result into outside variable

So this is long after the initial question, and technically it isn't a direct answer to how to use Ajax call to populate exterior variable as the question asks. However in research and responses it's been found to be extremely difficult to do this without disabling asynchronous functions within the call, or by descending into what seems like the potential for callback hell. My solution for this has been to use Axios. Using this has dramatically simplified my usages of asynchronous calls getting in the way of getting at data.

For example if I were trying to access session variables in PHP, like the User ID, via a call from JS this might be a problem. Doing something like this..

async function getSession() {
 'use strict';
 const getSession = await axios("http:" + url + "auth/" + "getSession");
 log(getSession.data);//test
 return getSession.data;
}

Which calls a PHP function that looks like this.

public function getSession() {
 $session = new SessionController();
 $session->Session();
 $sessionObj = new \stdClass();
 $sessionObj->user_id = $_SESSION["user_id"];
 echo json_encode($sessionObj);
}

To invoke this using Axios do something like this.

getSession().then(function (res) {
 log(res);//test
 anyVariable = res;
 anyFunction(res);//set any variable or populate another function waiting for the data
});

The result would be, in this case a Json object from PHP.

{"user_id":"1111111-1111-1111-1111-111111111111"}

Which you can either use in a function directly in the response section of the Axios call or set a variable or invoke another function.

Proper syntax for the Axios call would actually look like this.

getSession().then(function (res) {
 log(res);//test
 anyVariable = res;
 anyFunction(res);//set any variable or populate another function waiting for the data
}).catch(function (error) {
 console.log(error);
});

For proper error handling.

I hope this helps anyone having these issues. And yes I am aware this technically is not a direct answer to the question but given the answers supplied already I felt the need to provide this alternative solution which dramatically simplified my code on the client and server sides.

Perform curl request in javascript?

curl is a command in linux (and a library in php). Curl typically makes an HTTP request.

What you really want to do is make an HTTP (or XHR) request from javascript.

Using this vocab you'll find a bunch of examples, for starters: Sending authorization headers with jquery and ajax

Essentially you will want to call $.ajax with a few options for the header, etc.

$.ajax({
        url: 'https://api.wit.ai/message?v=20140826&q=',
        beforeSend: function(xhr) {
             xhr.setRequestHeader("Authorization", "Bearer 6QXNMEMFHNY4FJ5ELNFMP5KRW52WFXN5")
        }, success: function(data){
            alert(data);
            //process the JSON data etc
        }
})

How do I kill all the processes in Mysql "show processlist"?

mysqladmin pr -u 'USERNAME' -p'PASSWORD' | awk '$2~/^[0-9]+/{print $2}' | xargs -i mysqladmin -u 'USERNAME' -p'PASSWORD' kill {}

How do I format XML in Notepad++?

You can't, granted you don't have access to install plugins. But you probably have or can get Eclipse (Visual Studio can do this too).

Ctrl + N (new file) ? (choose XML file) ? (paste your XML content) ? Ctrl + Shift + K (format)

If you want to format JSON NotePad++ can do this by default with Ctrl + Alt + m

VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range

You have to go to the sheet of db to get the first blank row, you could try this method.

Sub DesdeColombia ()    
  Dim LastRowFull As Long

  'Here we will define the first blank row in the column number 1 of sheet number 1:
  LastRowFull = Sheet1.Cells(Rows.Count,1).End(xlUp).Offset(1,0).Row

  'Now we are going to insert information
  Sheet1.Cells(LastRowFull, 1).Value = "We got it"    
End Sub

Checking session if empty or not

If It is simple Session you can apply NULL Check directly Session["emp_num"] != null

But if it's a session of a list Item then You need to apply any one of the following option

Option 1:

if (((List<int>)(Session["emp_num"])) != null && (List<int>)Session["emp_num"])).Count > 0)
 {
 //Your Logic here
 }

Option 2:

List<int> val= Session["emp_num"] as List<int>;  //Get the value from Session.

if (val.FirstOrDefault() != null)
 {
 //Your Logic here
 }

Accessing an SQLite Database in Swift

You can easlity configure SQLite with swift using single ton class as well.

Refer

https://github.com/hasyapanchasara/SQLite_SingleManagerClass

Method to create database

func methodToCreateDatabase() -> NSURL?{} 

Method to insert, update and delete data

func methodToInsertUpdateDeleteData(strQuery : String) -> Bool{}

Method to select data

func methodToSelectData(strQuery : String) -> NSMutableArray{}

High CPU Utilization in java application - why?

You may be victim of a garbage collection problem.

When your application requires memory and it's getting low on what it's configured to use the garbage collector will run often which consume a lot of CPU cycles. If it can't collect anything your memory will stay low so it will be run again and again. When you redeploy your application the memory is cleared and the garbage collection won't happen more than required so the CPU utilization stays low until it's full again.

You should check that there is no possible memory leak in your application and that it's well configured for memory (check the -Xmx parameter, see What does Java option -Xmx stand for?)

Also, what are you using as web framework? JSF relies a lot on sessions and consumes a lot of memory, consider being stateless at most!

How do I calculate a trendline for a graph?

Regarding a previous answer

if (B) y = offset + slope*x

then (C) offset = y/(slope*x) is wrong

(C) should be:

offset = y-(slope*x)

See: http://zedgraph.org/wiki/index.php?title=Trend

How to build a DataTable from a DataGridView?

Well, you can do

DataTable data = (DataTable)(dgvMyMembers.DataSource);

and then use

data.Columns.Remove(...);

I think it's the fastest way. This will modify data source table, if you don't want it, then copy of table is reqired. Also be aware that DataGridView.DataSource is not necessarily of DataTable type.

Bring a window to the front in WPF

To show ANY currently opened window import those DLL:

public partial class Form1 : Form
{
    [DllImportAttribute("User32.dll")]
    private static extern int FindWindow(String ClassName, String WindowName);
    [DllImportAttribute("User32.dll")]
    private static extern int SetForegroundWindow(int hWnd);

and in program We search for app with specified title (write title without first letter (index > 0))

  foreach (Process proc in Process.GetProcesses())
                {
                    tx = proc.MainWindowTitle.ToString();
                    if (tx.IndexOf("Title of Your app WITHOUT FIRST LETTER") > 0)
                    {
                        tx = proc.MainWindowTitle;
                        hWnd = proc.Handle.ToInt32(); break;
                    }
                }
                hWnd = FindWindow(null, tx);
                if (hWnd > 0)
                {
                    SetForegroundWindow(hWnd);
                }

Undoing a git rebase

If you don't want to do a hard reset...

You can checkout the commit from the reflog, and then save it as a new branch:

git reflog

Find the commit just before you started rebasing. You may need to scroll further down to find it (press Enter or PageDown). Take note of the HEAD number and replace 57:

git checkout HEAD@{57}

Review the branch/commits, and if it's correct then create a new branch using this HEAD:

git checkout -b new_branch_name

How to copy Outlook mail message into excel using VBA or Macros

Since you have not mentioned what needs to be copied, I have left that section empty in the code below.

Also you don't need to move the email to the folder first and then run the macro in that folder. You can run the macro on the incoming mail and then move it to the folder at the same time.

This will get you started. I have commented the code so that you will not face any problem understanding it.

First paste the below mentioned code in the outlook module.

Then

  1. Click on Tools~~>Rules and Alerts
  2. Click on "New Rule"
  3. Click on "start from a blank rule"
  4. Select "Check messages When they arrive"
  5. Under conditions, click on "with specific words in the subject"
  6. Click on "specific words" under rules description.
  7. Type the word that you want to check in the dialog box that pops up and click on "add".
  8. Click "Ok" and click next
  9. Select "move it to specified folder" and also select "run a script" in the same box
  10. In the box below, specify the specific folder and also the script (the macro that you have in module) to run.
  11. Click on finish and you are done.

When the new email arrives not only will the email move to the folder that you specify but data from it will be exported to Excel as well.

UNTESTED

Const xlUp As Long = -4162

Sub ExportToExcel(MyMail As MailItem)
    Dim strID As String, olNS As Outlook.Namespace
    Dim olMail As Outlook.MailItem
    Dim strFileName As String

    '~~> Excel Variables
    Dim oXLApp As Object, oXLwb As Object, oXLws As Object
    Dim lRow As Long

    strID = MyMail.EntryID
    Set olNS = Application.GetNamespace("MAPI")
    Set olMail = olNS.GetItemFromID(strID)

    '~~> Establish an EXCEL application object
    On Error Resume Next
    Set oXLApp = GetObject(, "Excel.Application")

    '~~> If not found then create new instance
    If Err.Number <> 0 Then
        Set oXLApp = CreateObject("Excel.Application")
    End If
    Err.Clear
    On Error GoTo 0

    '~~> Show Excel
    oXLApp.Visible = True

    '~~> Open the relevant file
    Set oXLwb = oXLApp.Workbooks.Open("C:\Sample.xls")

    '~~> Set the relevant output sheet. Change as applicable
    Set oXLws = oXLwb.Sheets("Sheet1")

    lRow = oXLws.Range("A" & oXLApp.Rows.Count).End(xlUp).Row + 1

    '~~> Write to outlook
    With oXLws
        '
        '~~> Code here to output data from email to Excel File
        '~~> For example
        '
        .Range("A" & lRow).Value = olMail.Subject
        .Range("B" & lRow).Value = olMail.SenderName
        '
    End With

    '~~> Close and Clean up Excel
    oXLwb.Close (True)
    oXLApp.Quit
    Set oXLws = Nothing
    Set oXLwb = Nothing
    Set oXLApp = Nothing

    Set olMail = Nothing
    Set olNS = Nothing
End Sub

FOLLOWUP

To extract the contents from your email body, you can split it using SPLIT() and then parsing out the relevant information from it. See this example

Dim MyAr() As String

MyAr = Split(olMail.body, vbCrLf)

For i = LBound(MyAr) To UBound(MyAr)
    '~~> This will give you the contents of your email
    '~~> on separate lines
    Debug.Print MyAr(i)
Next i

Android Studio - Device is connected but 'offline'

I tried most of the things on this page and none of them worked for my Samsung S5. However, when I switched the cable to a USB-C type the problem seemed to be solved...until next time.

Problems when trying to load a package in R due to rJava

Answer in link resolved my issue.

Before resolution, I tried by adding JAVA_HOME to windows environments. It resolved this error but created another issue. The solution in above link resolves this issue without creating additional issues.

CSS align one item right with flexbox

For a terse, pure flexbox option, group the left-aligned items and the right-aligned items:

<div class="wrap">
  <div>
    <span>One</span>
    <span>Two</span>
  </div>
  <div>Three</div>
</div>

and use space-between:

.wrap {
  display: flex;
  background: #ccc;
  justify-content: space-between;
}

This way you can group multiple items to the right(or just one).

https://jsfiddle.net/c9mkewwv/3/

Pass array to ajax request in $.ajax()

Just use the JSON.stringify method and pass it through as the "data" parameter for the $.ajax function, like follows:

$.ajax({
    type: "POST",
    url: "index.php",
    dataType: "json",
    data: JSON.stringify({ paramName: info }),
    success: function(msg){
        $('.answer').html(msg);
    }
});

You just need to make sure you include the JSON2.js file in your page...

Get public/external IP address?

I do it using HttpClient from System.Net.Http:

public static string PublicIPAddress()
{
    string uri = "http://checkip.dyndns.org/";
    string ip = String.Empty;

    using (var client = new HttpClient())
    {
        var result = client.GetAsync(uri).Result.Content.ReadAsStringAsync().Result;

        ip = result.Split(':')[1].Split('<')[0];
    }

    return ip;
}

Disable submit button ONLY after submit

I faced the same problem. Customers could submit a form and then multiple e-mail addresses will receive a mail message. If the response of the page takes too long, sometimes the button was pushed twice or even more times..

I tried disable the button in the onsubmit handler, but the form wasn't submitted at all. Above solutions work probably fine, but for me it was a little bit too tricky, so I decided to try something else.

To the left side of the submit button, I placed a second button, which is not displayed and is disabled at start up:

<button disabled class="btn btn-primary" type=button id="btnverzenden2" style="display: none"><span class="glyphicon glyphicon-refresh"></span> Sending mail</button>   
<button class="btn btn-primary" type=submit name=verzenden id="btnverzenden">Send</button>

In the onsubmit handler attached to the form, the 'real' submit is hidden and the 'fake' submit is shown with a message that the messages are being sent.

function checkinput // submit handler
{
    ..
    ...
    $("#btnverzenden").hide(); <= real submit button will be hidden
    $("#btnverzenden2").show(); <= fake submit button gets visible
    ...
    ..
}

This worked for us. I hope it will help you.

org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/CollegeWebsite]]

You have a version conflict, please verify whether compiled version and JVM of Tomcat version are same. you can do it by examining tomcat startup .bat , looking for JAVA_HOME

How can I find the maximum value and its index in array in MATLAB?

For a matrix you can use this:

[M,I] = max(A(:))

I is the index of A(:) containing the largest element.

Now, use the ind2sub function to extract the row and column indices of A corresponding to the largest element.

[I_row, I_col] = ind2sub(size(A),I)

source: https://www.mathworks.com/help/matlab/ref/max.html

Maximum call stack size exceeded on npm install

I have also faced the same problem and this is how i resolved it.

  1. First of all you need to make sure that your node and npm versions are up to date. if not please upgrade your node and npm packages to latest versions.

    nvm install 12.18.3 // update node version through node version manager
    
    npm install npm // update your npm version to latest
    
  2. Delete your node_modules folder and package-lock.json file.

  3. Force clean the entire NPM cache by using following comand.

    npm cache clean --force
    
  4. Re-Install all the dependencies.

    npm install
    
  5. If above step didn't resolve your problem, try to re-install your dependencies after executing following command.

    npm rebuild
    

How to order a data frame by one descending and one ascending column?

Let df be the data frame with 2 fields A and B

Case 1: if your field A and B are numeric

df[order(df[,1],df[,2]),] - sorts fields A and B in ascending order
df[order(df[,1],-df[,2]),] - sorts fields A in ascending and B in descending order
priority is given to A.

Case 2: if field A or B is non numeric say factor or character

In our case if B is character and we want to sort in reverse order
df[order(df[,1],-as.numeric(as.factor(df[,2]))),] -> this sorts field A(numerical) in ascending and field B(character) in descending.
priority is given to A.

The idea is that you can apply -sign in order function ony on numericals. So for sorting character strings in descending order you have to coerce them to numericals.

check if file exists in php

You can also use PHP get_headers() function.

Example:

function check_file_exists_here($url){
   $result=get_headers($url);
   return stripos($result[0],"200 OK")?true:false; //check if $result[0] has 200 OK
}

if(check_file_exists_here("http://www.mywebsite.com/file.pdf"))
   echo "This file exists";
else
   echo "This file does not exist";

Make Bootstrap's Carousel both center AND responsive?

add this

.carousel .item img {
   left: -9999px;  /*important */
   right: -9999px;  /*important */
   margin: 0 auto;  /*important */
   max-width: none;  /*important */
   min-width: 100%;
   position: absolute;
}

And of course one of the parent divs needs to have a position:relative, but I believe it does by default.

See it here: http://paginacrestinului.ro/

How to perform grep operation on all files in a directory?

grep $PATTERN * would be sufficient. By default, grep would skip all subdirectories. However, if you want to grep through them, grep -r $PATTERN * is the case.

How do I vertically center an H1 in a div?

Just use padding top and bottom, it will automatically center the content vertically.

What does it mean when the size of a VARCHAR2 in Oracle is declared as 1 byte?

it means ONLY one byte will be allocated per character - so if you're using multi-byte charsets, your 1 character won't fit

if you know you have to have at least room enough for 1 character, don't use the BYTE syntax unless you know exactly how much room you'll need to store that byte

when in doubt, use VARCHAR2(1 CHAR)

same thing answered here Difference between BYTE and CHAR in column datatypes

Also, in 12c the max for varchar2 is now 32k, not 4000. If you need more than that, use CLOB

in Oracle, don't use VARCHAR

How to edit log message already committed in Subversion?

If your repository enables setting revision properties via the pre-revprop-change hook you can change log messages much easier.

svn propedit --revprop -r 1234 svn:log url://to/repository

Or in TortoiseSVN, AnkhSVN and probably many other subversion clients by right clicking on a log entry and then 'change log message'.

angular.service vs angular.factory

Here are the primary differences:

Services

Syntax: module.service( 'serviceName', function );

Result: When declaring serviceName as an injectable argument you will be provided with the instance of a function passed to module.service.

Usage: Could be useful for sharing utility functions that are useful to invoke by simply appending ( ) to the injected function reference. Could also be run with injectedArg.call( this ) or similar.

Factories

Syntax: module.factory( 'factoryName', function );

Result: When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.

Usage: Could be useful for returning a 'class' function that can then be new'ed to create instances.

Here is example using services and factory. Read more about AngularJS Service vs Factory.

You can also check the AngularJS documentation and similar question on stackoverflow confused about service vs factory.

How to read strings from a Scanner in a Java console application?

What you can do is use delimeter as new line. Till you press enter key you will be able to read it as string.

Scanner sc = new Scanner(System.in);
sc.useDelimiter(System.getProperty("line.separator"));

Hope this helps.

Iterate over array of objects in Typescript

In Typescript and ES6 you can also use for..of:

for (var product of products) {
     console.log(product.product_desc)
}

which will be transcoded to javascript:

for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {
    var product = products_1[_i];
    console.log(product.product_desc);
}

Reset C int array to zero : the fastest way?

You can use memset, but only because our selection of types is restricted to integral types.

In general case in C it makes sense to implement a macro

#define ZERO_ANY(T, a, n) do{\
   T *a_ = (a);\
   size_t n_ = (n);\
   for (; n_ > 0; --n_, ++a_)\
     *a_ = (T) { 0 };\
} while (0)

This will give you C++-like functionality that will let you to "reset to zeros" an array of objects of any type without having to resort to hacks like memset. Basically, this is a C analog of C++ function template, except that you have to specify the type argument explicitly.

On top of that you can build a "template" for non-decayed arrays

#define ARRAY_SIZE(a) (sizeof (a) / sizeof *(a))
#define ZERO_ANY_A(T, a) ZERO_ANY(T, (a), ARRAY_SIZE(a))

In your example it would be applied as

int a[100];

ZERO_ANY(int, a, 100);
// or
ZERO_ANY_A(int, a);

It is also worth noting that specifically for objects of scalar types one can implement a type-independent macro

#define ZERO(a, n) do{\
   size_t i_ = 0, n_ = (n);\
   for (; i_ < n_; ++i_)\
     (a)[i_] = 0;\
} while (0)

and

#define ZERO_A(a) ZERO((a), ARRAY_SIZE(a))

turning the above example into

 int a[100];

 ZERO(a, 100);
 // or
 ZERO_A(a);

How to do a subquery in LINQ?

There is no subquery needed with this statement, which is better written as

select u.* 
from Users u, CompanyRolesToUsers c
where u.Id = c.UserId        --join just specified here, perfectly fine
and u.lastname like '%fra%'
and c.CompanyRoleId in (2,3,4)

or

select u.* 
from Users u inner join CompanyRolesToUsers c
             on u.Id = c.UserId    --explicit "join" statement, no diff from above, just preference
where u.lastname like '%fra%'
  and c.CompanyRoleId in (2,3,4)

That being said, in LINQ it would be

from u in Users
from c in CompanyRolesToUsers 
where u.Id == c.UserId &&
      u.LastName.Contains("fra") &&
      selectedRoles.Contains(c.CompanyRoleId)
select u

or

from u in Users
join c in CompanyRolesToUsers 
       on u.Id equals c.UserId
where u.LastName.Contains("fra") &&
      selectedRoles.Contains(c.CompanyRoleId)
select u

Which again, are both respectable ways to represent this. I prefer the explicit "join" syntax in both cases myself, but there it is...

Can I add and remove elements of enumeration at runtime in Java

I faced this problem on the formative project of my young career.

The approach I took was to save the values and the names of the enumeration externally, and the end goal was to be able to write code that looked as close to a language enum as possible.

I wanted my solution to look like this:

enum HatType
{
    BASEBALL,
    BRIMLESS,
    INDIANA_JONES
}

HatType mine = HatType.BASEBALL;

// prints "BASEBALL"
System.out.println(mine.toString());

// prints true
System.out.println(mine.equals(HatType.BASEBALL));

And I ended up with something like this:

// in a file somewhere:
// 1 --> BASEBALL
// 2 --> BRIMLESS
// 3 --> INDIANA_JONES

HatDynamicEnum hats = HatEnumRepository.retrieve();

HatEnumValue mine = hats.valueOf("BASEBALL");

// prints "BASEBALL"
System.out.println(mine.toString());

// prints true
System.out.println(mine.equals(hats.valueOf("BASEBALL"));

Since my requirements were that it had to be possible to add members to the enum at run-time, I also implemented that functionality:

hats.addEnum("BATTING_PRACTICE");

HatEnumRepository.storeEnum(hats);

hats = HatEnumRepository.retrieve();

HatEnumValue justArrived = hats.valueOf("BATTING_PRACTICE");
// file now reads:
// 1 --> BASEBALL
// 2 --> BRIMLESS
// 3 --> INDIANA_JONES
// 4 --> BATTING_PRACTICE

I dubbed it the Dynamic Enumeration "pattern", and you read about the original design and its revised edition.

The difference between the two is that the revised edition was designed after I really started to grok OO and DDD. The first one I designed when I was still writing nominally procedural DDD, under time pressure no less.

Java: Finding the highest value in an array

void FindMax()
{
    int lessonNum;

    System.out.print("Enter your lesson numbers : ");
    lessonNum = input.nextInt();
    int[] numbers = new int[lessonNum];
    for (int i = 0; i < numbers.length; i++)
    {
        System.out.print("Please enter " + (i + 1) + " number : ");
        numbers[i] = input.nextInt();
    }
    double max = numbers[0];
    for (int i = 1; i < numbers.length; i++)
    {
        if (numbers[i] > max)
        {
            max = numbers[i];
        }
    }
    System.out.println("Maximum number is : " + max);
}

how to place last div into right top corner of parent div? (css)

Displaying left middle and right of there parents. If you have more then 3 elements then use nth-child() for them.

enter image description here

HTML sample:

<body>
    <ul class="nav-tabs">
        <li><a  id="btn-tab-business" class="btn-tab nav-tab-selected"  onclick="openTab('business','btn-tab-business')"><i class="fas fa-th"></i>Business</a></li>
        <li><a  id="btn-tab-expertise" class="btn-tab" onclick="openTab('expertise', 'btn-tab-expertise')"><i class="fas fa-th"></i>Expertise</a></li>
        <li><a  id="btn-tab-quality" class="btn-tab" onclick="openTab('quality', 'btn-tab-quality')"><i class="fas fa-th"></i>Quality</a></li>
    </ul>
</body>

CSS sample:

.nav-tabs{
  position: relative;
  padding-bottom: 50px;
}
.nav-tabs li {
  display: inline-block;  
  position: absolute;
  list-style: none;
}
.nav-tabs li:first-child{
  top: 0px;
  left: 0px;
}
.nav-tabs li:last-child{
  top: 0px;
  right: 0px;
}
.nav-tabs li:nth-child(2){
  top: 0px;
  left: 50%;
  transform: translate(-50%, 0%);
}

Posting array from form

You can use the built-in function:

extract($_POST);

it will create a variable for each entry in $_POST.

Concatenate rows of two dataframes in pandas

call concat and pass param axis=1 to concatenate column-wise:

In [5]:

pd.concat([df_a,df_b], axis=1)
Out[5]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

There is a useful guide to the various methods of merging, joining and concatenating online.

For example, as you have no clashing columns you can merge and use the indices as they have the same number of rows:

In [6]:

df_a.merge(df_b, left_index=True, right_index=True)
Out[6]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

And for the same reasons as above a simple join works too:

In [7]:

df_a.join(df_b)
Out[7]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

How to rename array keys in PHP?

You could use array_map() to do it.

$tags = array_map(function($tag) {
    return array(
        'name' => $tag['name'],
        'value' => $tag['url']
    );
}, $tags);

Execute JavaScript using Selenium WebDriver in C#

How about a slightly simplified version of @Morten Christiansen's nice extension method idea:

public static object Execute(this IWebDriver driver, string script)
{
    return ((IJavaScriptExecutor)driver).ExecuteScript(script);
}

// usage
var title = (string)driver.Execute("return document.title");

or maybe the generic version:

public static T Execute<T>(this IWebDriver driver, string script)
{
    return (T)((IJavaScriptExecutor)driver).ExecuteScript(script);
}

// usage
var title = driver.Execute<string>("return document.title");

How can I delete an item from an array in VB.NET?

As Heinzi said, an array has a fixed size. In order to 'remove an item' or 'resize' it, you'll have to create a new array with the desired size and copy the items you need as appropriate.

Here's code to remove an item from an array:

<System.Runtime.CompilerServices.Extension()> _
Function RemoveAt(Of T)(ByVal arr As T(), ByVal index As Integer) As T()
    Dim uBound = arr.GetUpperBound(0)
    Dim lBound = arr.GetLowerBound(0)
    Dim arrLen = uBound - lBound

    If index < lBound OrElse index > uBound Then
        Throw New ArgumentOutOfRangeException( _
        String.Format("Index must be from {0} to {1}.", lBound, uBound))

    Else
        'create an array 1 element less than the input array
        Dim outArr(arrLen - 1) As T
        'copy the first part of the input array
        Array.Copy(arr, 0, outArr, 0, index)
        'then copy the second part of the input array
        Array.Copy(arr, index + 1, outArr, index, uBound - index)

        Return outArr
    End If
End Function

You can use it as such:

Module Module1

    Sub Main()
        Dim arr = New String() {"abc", "mno", "xyz"}
        arr.RemoveAt(1)
    End Sub
End Module

The code above removes the second element ("mno") [which has an index of 1] from the array.

You need to be developing in .NET 3.5 or higher in order to use the extension method. If you're using .NET 2.0 or 3.0, you can call the method as such

arr = RemoveAt(arr, 1)

I hope this is what you need.

Update

After running tests based on ToolMakerSteve's comment it appears the initial code does not modify the array you want to update because of the ByVal used in the function's declaration. However, writing code like arr = arr.RemoveAt(1) or arr = RemoveAt(arr, 1) does modify the array because it reassigns the modified array to the original.

Find below the updated method (subroutine) for removing an element from an array.

<System.Runtime.CompilerServices.Extension()> _
Public Sub RemoveAt(Of T)(ByRef arr As T(), ByVal index As Integer)
    Dim uBound = arr.GetUpperBound(0)
    Dim lBound = arr.GetLowerBound(0)
    Dim arrLen = uBound - lBound

    If index < lBound OrElse index > uBound Then
        Throw New ArgumentOutOfRangeException( _
        String.Format("Index must be from {0} to {1}.", lBound, uBound))

    Else
        'create an array 1 element less than the input array
        Dim outArr(arrLen - 1) As T
        'copy the first part of the input array
        Array.Copy(arr, 0, outArr, 0, index)
        'then copy the second part of the input array
        Array.Copy(arr, index + 1, outArr, index, uBound - index)

        arr = outArr
    End If
End Sub

Usage of the method is similar to the original, except there is no return value this time so trying to assign an array from the return value will not work because nothing is returned.

Dim arr = New String() {"abc", "mno", "xyz"}
arr.RemoveAt(1)  ' Output: {"abc", "mno"} (works on .NET 3.5 and higher)
RemoveAt(arr, 1) ' Output: {"abc", "mno"} (works on all versions of .NET fx)
arr = arr.RemoveAt(1)  'will not work; no return value
arr = RemoveAt(arr, 1) 'will not work; no return value

Note:

  1. I use a temporary array for the process because it makes my intentions clear and that is exactly what VB.NET does behind the scenes when you do Redim Preserve. If you would like to modify the array in-place using Redim Preserve, see ToolmakerSteve's answer.

  2. The RemoveAt methods written here are extension methods. In order for them to work, you will have to paste them in a Module. Extension methods will not work in VB.NET if they are placed in a Class.

  3. Important If you will be modifying your array with lots of 'removes', it is highly recommended to use a different data structure such as List(Of T) as suggested by other answerers to this question.

Detecting when a div's height changes using jQuery

In response to user007:

If the height of your element is changing due to items being appended to it using .append() you shouldn't need to detect the change in height. Simply add the reposition of your second element in the same function where you are appending the new content to your first element.

As in:

Working Example

$('.class1').click(function () {
    $('.class1').append("<div class='newClass'><h1>This is some content</h1></div>");
    $('.class2').css('top', $('.class1').offset().top + $('.class1').outerHeight());
});

How to get dictionary values as a generic list

Another variant:

    List<MyType> items = new List<MyType>();
    items.AddRange(myDico.values);

Converting binary to decimal integer output

I started working on this problem a long time ago, trying to write my own binary to decimal converter function. I don't actually know how to convert decimal to binary though! I just revisited it today and figured it out and this is what I came up with. I'm not sure if this is what you need, but here it is:

def __degree(number):
    power = 1

    while number % (10**power) != number:
        power += 1

    return power

def __getDigits(number):
    digits = []
    degree = __degree(number)

    for x in range(0, degree):
        digits.append(int(((number % (10**(degree-x))) - (number % (10**(degree-x-1)))) / (10**(degree-x-1))))
    return digits

def binaryToDecimal(number):
    list = __getDigits(number)
    decimalValue = 0
    for x in range(0, len(list)):
        if (list[x] is 1):
            decimalValue += 2**(len(list) - x - 1)
    return decimalValue

Again, I'm still learning Python just on my own, hopefully this helps. The first function determines how many digits there are, the second function actually figures out they are and returns them in a list, and the third function is the only one you actually need to call, and it calculates the decimal value. If your teacher actually wanted you to write your own converter, this works, I haven't tested it with every number, but it seems to work perfectly! I'm sure you'll all find the bugs for me! So anyway, I just called it like:

binaryNum = int(input("Enter a binary number: "))

print(binaryToDecimal(binaryNum))

This prints out the correct result. Cheers!

Execution failed for task ':app:compileDebugAidl': aidl is missing

Quick fix that worked for me:

Right click on project->"Open Module Settings"->Build Tools Version change to: 22.0.1

enter image description here

git index.lock File exists when I try to commit, but cannot delete the file

On Linux, Unix, Git Bash, or Cygwin, try:

rm -f .git/index.lock

On Windows Command Prompt, try:

del .git\index.lock


For Windows:

  • From a PowerShell console opened as administrator, try

    rm -Force ./.git/index.lock
    
  • If that does not work, you must kill all git.exe processes

    taskkill /F /IM git.exe
    

    SUCCESS: The process "git.exe" with PID 20448 has been terminated.
    SUCCESS: The process "git.exe" with PID 11312 has been terminated.
    SUCCESS: The process "git.exe" with PID 23868 has been terminated.
    SUCCESS: The process "git.exe" with PID 27496 has been terminated.
    SUCCESS: The process "git.exe" with PID 33480 has been terminated.
    SUCCESS: The process "git.exe" with PID 28036 has been terminated. \

    rm -Force ./.git/index.lock
    

Smooth scroll to specific div on click

There are many examples of smooth scrolling using JS libraries like jQuery, Mootools, Prototype, etc.

The following example is on pure JavaScript. If you have no jQuery/Mootools/Prototype on page or you don't want to overload page with heavy JS libraries the example will be of help.

http://jsfiddle.net/rjSfP/

HTML Part:

<div class="first"><button type="button" onclick="smoothScroll(document.getElementById('second'))">Click Me!</button></div>
<div class="second" id="second">Hi</div>

CSS Part:

.first {
    width: 100%;
    height: 1000px;
    background: #ccc;
}

.second {
    width: 100%;
    height: 1000px;
    background: #999;
}

JS Part:

window.smoothScroll = function(target) {
    var scrollContainer = target;
    do { //find scroll container
        scrollContainer = scrollContainer.parentNode;
        if (!scrollContainer) return;
        scrollContainer.scrollTop += 1;
    } while (scrollContainer.scrollTop == 0);

    var targetY = 0;
    do { //find the top of target relatively to the container
        if (target == scrollContainer) break;
        targetY += target.offsetTop;
    } while (target = target.offsetParent);

    scroll = function(c, a, b, i) {
        i++; if (i > 30) return;
        c.scrollTop = a + (b - a) / 30 * i;
        setTimeout(function(){ scroll(c, a, b, i); }, 20);
    }
    // start scrolling
    scroll(scrollContainer, scrollContainer.scrollTop, targetY, 0);
}

How do I use sudo to redirect output to a location I don't have permission to write to?

How about writing a script?

Filename: myscript

#!/bin/sh

/bin/ls -lah /root > /root/test.out

# end script

Then use sudo to run the script:

sudo ./myscript

Removing all empty elements from a hash / YAML?

I made a deep_compact method for this that recursively filters out nil records (and optionally, blank records as well):

class Hash
  # Recursively filters out nil (or blank - e.g. "" if exclude_blank: true is passed as an option) records from a Hash
  def deep_compact(options = {})
    inject({}) do |new_hash, (k,v)|
      result = options[:exclude_blank] ? v.blank? : v.nil?
      if !result
        new_value = v.is_a?(Hash) ? v.deep_compact(options).presence : v
        new_hash[k] = new_value if new_value
      end
      new_hash
    end
  end
end

iOS application: how to clear notifications?

If you're coming here wondering the opposite (as I was), this post may be for you.

I couldn't figure out why my notifications were clearing when I cleared the badge...I manually increment the badge and then want to clear it when the user enters the app. That's no reason to clear out the notification center, though; they may still want to see or act on those notifications.

Negative 1 does the trick, luckily:

[UIApplication sharedApplication].applicationIconBadgeNumber = -1;

Is it possible to set ENV variables for rails development environment in my code?

[Update]

While the solution under "old answer" will work for general problems, this section is to answer your specific question after clarification from your comment.

You should be able to set environment variables exactly like you specify in your question. As an example, I have a Heroku app that uses HTTP basic authentication.

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :authenticate

  def authenticate
    authenticate_or_request_with_http_basic do |username, password|
      username == ENV['HTTP_USER'] && password == ENV['HTTP_PASS']
    end
  end
end

# config/initializers/dev_environment.rb
unless Rails.env.production?
  ENV['HTTP_USER'] = 'testuser'
  ENV['HTTP_PASS'] = 'testpass'
end

So in your case you would use

unless Rails.env.production?
  ENV['admin_password'] = "secret"
end

Don't forget to restart the server so the configuration is reloaded!

[Old Answer]

For app-wide configuration, you might consider a solution like the following:

Create a file config/application.yml with a hash of options you want to be able to access:

admin_password: something_secret
allow_registration: true
facebook:
  app_id: application_id_here
  app_secret: application_secret_here
  api_key: api_key_here

Now, create the file config/initializers/app_config.rb and include the following:

require 'yaml'

yaml_data = YAML::load(ERB.new(IO.read(File.join(Rails.root, 'config', 'application.yml'))).result)
APP_CONFIG = HashWithIndifferentAccess.new(yaml_data)

Now, anywhere in your application, you can access APP_CONFIG[:admin_password], along with all your other data. (Note that since the initializer includes ERB.new, your YAML file can contain ERB markup.)

Do I need to compile the header files in a C program?

You don't need to compile header files. It doesn't actually do anything, so there's no point in trying to run it. However, it is a great way to check for typos and mistakes and bugs, so it'll be easier later.

Force Internet Explorer to use a specific Java Runtime Environment install?

I'd give all the responses here a try first. But I wanted to just throw in what I do, just in case these do not work for you.

I've tried to solve the same problem you're having before, and in the end, what I decided on doing is to have only one JRE installed on my system at a given time. I do have about 10 different JDKs (1.3 through 1.6, and from various vendors - Sun, Oracle, IBM), since I do need it for development, but only one standalone JRE.

This has worked for me on my Windows 2000 + IE 6 computer at home, as well as my Windows XP + Multiple IE computer at work.

Force youtube embed to start in 720p

Use this, it works 100% _your_videocode?rel=0&vq=hd1080"

How to layout multiple panels on a jFrame? (java)

You'll want to use a number of layout managers to help you achieve the basic results you want.

Check out A Visual Guide to Layout Managers for a comparision.

You could use a GridBagLayout but that's one of the most complex (and powerful) layout managers available in the JDK.

You could use a series of compound layout managers instead.

I'd place the graphics component and text area on a single JPanel, using a BorderLayout, with the graphics component in the CENTER and the text area in the SOUTH position.

I'd place the text field and button on a separate JPanel using a GridBagLayout (because it's the simplest I can think of to achieve the over result you want)

I'd place these two panels onto a third, master, panel, using a BorderLayout, with the first panel in the CENTER and the second at the SOUTH position.

But that's me

How do I compute the intersection point of two lines?

The most concise solution I have found uses Sympy: https://www.geeksforgeeks.org/python-sympy-line-intersection-method/

# import sympy and Point, Line 
from sympy import Point, Line 
  
p1, p2, p3 = Point(0, 0), Point(1, 1), Point(7, 7) 
l1 = Line(p1, p2) 
  
# using intersection() method 
showIntersection = l1.intersection(p3) 
  
print(showIntersection) 

VBA: Counting rows in a table (list object)

You can use:

Sub returnname(ByVal TableName As String)

MsgBox (Range("Table15").Rows.count)

End Sub

and call the function as below

Sub called()

returnname "Table15"

End Sub

How to get the MD5 hash of a file in C++?

A rework of impementation by @D'Nabre for C++. Don't forget to compile with -lcrypto at the end: gcc md5.c -o md5 -lcrypto.

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>

#include <openssl/md5.h>
using namespace std;

unsigned char result[MD5_DIGEST_LENGTH];

// function to print MD5 correctly
void printMD5(unsigned char* md, long size = MD5_DIGEST_LENGTH) {
    for (int i=0; i<size; i++) {
        cout<< hex << setw(2) << setfill('0') << (int) md[i];
    }
}

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

if(argc != 2) {
    cout << "Specify the file..." << endl;
    return 0;
}

ifstream::pos_type fileSize;
char * memBlock;

ifstream file (argv[1], ios::ate);

//check if opened
if (file.is_open() ) { cout<< "Using file\t"<< argv[1]<<endl; }
else {
    cout<< "Unnable to open\t"<< argv[1]<<endl;
    return 0;
}

//get file size & copy file to memory
//~ file.seekg(-1,ios::end); // exludes EOF
fileSize = file.tellg();
cout << "File size \t"<< fileSize << endl;
memBlock = new char[fileSize];
file.seekg(0,ios::beg);
file.read(memBlock, fileSize);
file.close();

//get md5 sum
MD5((unsigned char*) memBlock, fileSize, result);

//~ cout << "MD5_DIGEST_LENGTH = "<< MD5_DIGEST_LENGTH << endl;
printMD5(result);
cout<<endl;

return 0;
}

What is the path for the startup folder in windows 2008 server

In Server 2008 the startup folder for individual users is here:

C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

For All Users it's here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup

Hope that helps

Key value pairs using JSON

var object = {
    key1 : {
        name : 'xxxxxx',
        value : '100.0'
    },
    key2 : {
        name : 'yyyyyyy',
        value : '200.0'
    },
    key3 : {
        name : 'zzzzzz',
        value : '500.0'
    },
}

If thats how your object looks and you want to loop each name and value then I would try and do something like.

$.each(object,function(key,innerjson){
    /*
        key would be key1,key2,key3
        innerjson would be the name and value **
    */

    //Alerts and logging of the variable.
    console.log(innerjson); //should show you the value    
    alert(innerjson.name); //Should say xxxxxx,yyyyyy,zzzzzzz
});

Alternative for <blink>

can use this

@keyframes blinkingText
{
    0%{     opacity: 1;    }
    40%{    opacity: 0; }
    60%{    opacity: 0; }
    100%{   opacity: 1;    }
}

.blinking
{
    animation:blinkingText 2s reverse infinite;
}

make image( not background img) in div repeat?

(DEMO)
Codes:

.backimage {width:99%;  height:98%;  position:absolute;    background:transparent url("http://upload.wikimedia.org/wikipedia/commons/4/41/Brickwall_texture.jpg") repeat scroll 0% 0%;  }

and

<div>
    <div class="backimage"></div>
    YOUR OTHER CONTENTTT
</div>

Left function in c#

use substring function:

yourString.Substring(0, length);

Make a div fill the height of the remaining screen space

This is my own minimal version of Pebbl's solution. Took forever to find the trick to get it to work in IE11. (Also tested in Chrome, Firefox, Edge, and Safari.)

_x000D_
_x000D_
html {
  height: 100%;
}

body {
  height: 100%;
  margin: 0;
}

section {
  display: flex;
  flex-direction: column;
  height: 100%;
}

div:first-child {
  background: gold;
}

div:last-child {
  background: plum;
  flex-grow: 1;
}
_x000D_
<body>
  <section>
    <div>FIT</div>
    <div>GROW</div>
  </section>
</body>
_x000D_
_x000D_
_x000D_

Why is NULL undeclared?

Don't use NULL, C++ allows you to use the unadorned 0 instead:

previous = 0;
next = 0;

And, as at C++11, you generally shouldn't be using either NULL or 0 since it provides you with nullptr of type std::nullptr_t, which is better suited to the task.

How do I use an INSERT statement's OUTPUT clause to get the identity value?

You can either have the newly inserted ID being output to the SSMS console like this:

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar() (instead of .ExecuteNonQuery()) to read the resulting ID back.

Or if you need to capture the newly inserted ID inside T-SQL (e.g. for later further processing), you need to create a table variable:

DECLARE @OutputTbl TABLE (ID INT)

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

This way, you can put multiple values into @OutputTbl and do further processing on those. You could also use a "regular" temporary table (#temp) or even a "real" persistent table as your "output target" here.

How do I set default terminal to terminator?

change Settings Manager >> Preferred Applications >> Utilities

Create space at the beginning of a UITextField

This one line of code saved me:

For Xamarin.iOS:

textField.Layer.SublayerTransform = CATransform3D.MakeTranslation(5, 0, 0);

For Swift:

textField.layer.sublayerTransform = CATransform3DMakeTranslation(5, 0, 0);

Why does the jquery change event not trigger when I set the value of a select using val()?

In case you don't want to mix up with default change event you can provide your custom event

$('input.test').on('value_changed', function(e){
    console.log('value changed to '+$(this).val());
});

to trigger the event on value set, you can do

$('input.test').val('I am a new value').trigger('value_changed');

How to add a jar in External Libraries in android studio

Step 1: Download any JAR file for your Project.enter image description here

Step 2: Copy .jar file and past in libs folder.

enter image description here enter image description here

Step 3: Click on File > Project Structure >Select app > Dependencies

enter image description here

Step 4:

enter image description here

Step 5:

enter image description here

Step 6: After click Ok button then we can see the Dependencies add like this way:

enter image description here

Why do we not have a virtual constructor in C++?

Unlike object oriented languages such as Smalltalk or Python, where the constructor is a virtual method of the object representing the class (which means you don't need the GoF abstract factory pattern, as you can pass the object representing the class around instead of making your own), C++ is a class based language, and does not have objects representing any of the language's constructs. The class does not exist as an object at runtime, so you can't call a virtual method on it.

This fits with the 'you don't pay for what you don't use' philosophy, though every large C++ project I've seen has ended up implementing some form of abstract factory or reflection.

Hide keyboard in react-native

Wrapping your components in a TouchableWithoutFeedback can cause some weird scroll behavior and other issues. I prefer to wrap my topmost app in a View with the onStartShouldSetResponder property filled in. This will allow me to handle all unhandled touches and then dismiss the keyboard. Importantly, since the handler function returns false the touch event is propagated up like normal.

 handleUnhandledTouches(){
   Keyboard.dismiss
   return false;
 }

 render(){
    <View style={{ flex: 1 }} onStartShouldSetResponder={this.handleUnhandledTouches}>
       <MyApp>
    </View>
  }

Replace text in HTML page with jQuery

Like others mentioned in this thread, replacing the entire body HTML is a bad idea because it reinserts the entire DOM and can potentially break any other javascript that was acting on those elements.

Instead, replace just the text on your page and not the DOM elements themselves using jQuery filter:

  $('body :not(script)').contents().filter(function() {
    return this.nodeType === 3;
  }).replaceWith(function() {
      return this.nodeValue.replace('-9o0-9909','The new string');
  });

this.nodeType is the type of node we are looking to replace the contents of. nodeType 3 is text. See the full list here.

Is Java "pass-by-reference" or "pass-by-value"?

Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.

Take the badSwap() method for example:

    public void badSwap(int var1, int
 var2{ int temp = var1; var1 = var2; var2 =
 temp; }

When badSwap() returns, the variables passed as arguments will still hold their original values. The method will also fail if we change the arguments type from int to Object, since Java passes object references by value as well. Now, here is where it gets tricky:

public void tricky(Point arg1, Point   arg2)
{ arg1.x = 100; arg1.y = 100; Point temp = arg1; arg1 = arg2; arg2 = temp; }
public static void main(String [] args) { 

 Point pnt1 = new Point(0,0); Point pnt2
 = new Point(0,0); System.out.println("X:
 " + pnt1.x + " Y: " +pnt1.y);

     System.out.println("X: " + pnt2.x + " Y:
 " +pnt2.y); System.out.println(" ");

     tricky(pnt1,pnt2);
 System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);

     System.out.println("X: " + pnt2.x + " Y: " +pnt2.y); }

If we execute this main() method, we see the following output:

X: 0 Y: 0 X: 0 Y: 0 X: 100 Y: 100 X: 0 Y: 0

The method successfully alters the value ofpnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In themain() method, pnt1 and pnt2 are nothing more than object references. When you passpnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references. Figure 1 below shows two references pointing to the same object after Java passes an object to a method.

Java copies and passes the reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail. As Figure 2 illustrates, the method references swap, but not the original references. Unfortunately, after a method call, you are left with only the unswapped original references. For a swap to succeed outside of the method call, we need to swap the original references, not the copies.

How to handle notification when app in background in Firebase

you want to work onMessageReceived(RemoteMessage remoteMessage) in background send only data part notification part this:

"data":    "image": "",    "message": "Firebase Push Message Using API", 

"AnotherActivity": "True", "to" : "device id Or Device token"

By this onMessageRecivied is call background and foreground no need to handle notification using notification tray on your launcher activity. Handle data payload in using this:

  public void onMessageReceived(RemoteMessage remoteMessage)
    if (remoteMessage.getData().size() > 0) 
    Log.d(TAG, "Message data payload: " + remoteMessage.getData());      

How to install OpenSSL in windows 10?

If you have chocolatey installed you can install openssl via a single command i.e.

choco install openssl

How can I find the last element in a List<>?

Change

for (int cnt3 = 0 ; cnt3 <= integerList.FindLastIndex ; cnt3++)

to

for (int cnt3 = 0 ; cnt3 < integerList.Count; cnt3++)

What is the difference between exit(0) and exit(1) in C?

The difference is the value returned to the environment is 0 in the former case and 1 in the latter case:

$ ./prog_with_exit_0
$ echo $?
0
$

and

$ ./prog_with_exit_1
$ echo $?
1
$

Also note that the macros value EXIT_SUCCESS and EXIT_FAILURE used as an argument to exit function are implementation defined but are usually set to respectively 0 and a non-zero number. (POSIX requires EXIT_SUCCESS to be 0). So usually exit(0) means a success and exit(1) a failure.

An exit function call with an argument in main function is equivalent to the statement return with the same argument.

How do I stretch a background image to cover the entire HTML element?

Not sure that stretching a background image is possible. If you find that it's not possible, or not reliable in all of your target browsers, you could try using a stretched img tag with z-index set lower, and position set to absolute so that other content appears on top of it.

Let us know what you end up doing.

Edit: What I suggested is basically what's in gabriel's link. So try that :)

How to make html table vertically scrollable

Try this one.. It is working... Here JSBIN

table tbody { height:300px; overflow-y:scroll; display:block; }
table thead { display:block; }

Class name does not name a type in C++

when you define the class A, in A.h, you explicitely say that the class has a member B.

You MUST include "B.h" in "A.h"

python: creating list from string

If you need to convert some of them to numbers and don't know in advance which ones, some additional code will be needed. Try something like this:

b = []
for x in a:
    temp = []
    items = x.split(",")
    for item in items:
        try:
            n = int(item)
        except ValueError:
            temp.append(item)
        else:
            temp.append(n)
    b.append(temp)

This is longer than the other answers, but it's more versatile.

How does JavaScript .prototype work?

The seven Koans of prototype

As Ciro San descended Mount Fire Fox after deep meditation, his mind was clear and peaceful.

His hand however, was restless, and by itself grabbed a brush and jotted down the following notes.


0) Two different things can be called "prototype":

  • the prototype property, as in obj.prototype

  • the prototype internal property, denoted as [[Prototype]] in ES5.

    It can be retrieved via the ES5 Object.getPrototypeOf().

    Firefox makes it accessible through the __proto__ property as an extension. ES6 now mentions some optional requirements for __proto__.


1) Those concepts exist to answer the question:

When I do obj.property, where does JS look for .property?

Intuitively, classical inheritance should affect property lookup.


2)

  • __proto__ is used for the dot . property lookup as in obj.property.
  • .prototype is not used for lookup directly, only indirectly as it determines __proto__ at object creation with new.

Lookup order is:

  • obj properties added with obj.p = ... or Object.defineProperty(obj, ...)
  • properties of obj.__proto__
  • properties of obj.__proto__.__proto__, and so on
  • if some __proto__ is null, return undefined.

This is the so-called prototype chain.

You can avoid . lookup with obj.hasOwnProperty('key') and Object.getOwnPropertyNames(f)


3) There are two main ways to set obj.__proto__:

  • new:

    var F = function() {}
    var f = new F()
    

    then new has set:

    f.__proto__ === F.prototype
    

    This is where .prototype gets used.

  • Object.create:

     f = Object.create(proto)
    

    sets:

    f.__proto__ === proto
    

4) The code:

var F = function(i) { this.i = i }
var f = new F(1)

Corresponds to the following diagram (some Number stuff is omitted):

(Function)       (  F  )                                      (f)----->(1)
 |  ^             | | ^                                        |   i    |
 |  |             | | |                                        |        |
 |  |             | | +-------------------------+              |        |
 |  |constructor  | |                           |              |        |
 |  |             | +--------------+            |              |        |
 |  |             |                |            |              |        |
 |  |             |                |            |              |        |
 |[[Prototype]]   |[[Prototype]]   |prototype   |constructor   |[[Prototype]]
 |  |             |                |            |              |        |
 |  |             |                |            |              |        |
 |  |             |                | +----------+              |        |
 |  |             |                | |                         |        |
 |  |             |                | | +-----------------------+        |
 |  |             |                | | |                                |
 v  |             v                v | v                                |
(Function.prototype)              (F.prototype)                         |
 |                                 |                                    |
 |                                 |                                    |
 |[[Prototype]]                    |[[Prototype]]          [[Prototype]]|
 |                                 |                                    |
 |                                 |                                    |
 | +-------------------------------+                                    |
 | |                                                                    |
 v v                                                                    v
(Object.prototype)                                       (Number.prototype)
 | | ^
 | | |
 | | +---------------------------+
 | |                             |
 | +--------------+              |
 |                |              |
 |                |              |
 |[[Prototype]]   |constructor   |prototype
 |                |              |
 |                |              |
 |                | -------------+
 |                | |
 v                v |
(null)           (Object)

This diagram shows many language predefined object nodes:

  • null
  • Object
  • Object.prototype
  • Function
  • Function.prototype
  • 1
  • Number.prototype (can be found with (1).__proto__, parenthesis mandatory to satisfy syntax)

Our 2 lines of code only created the following new objects:

  • f
  • F
  • F.prototype

i is now a property of f because when you do:

var f = new F(1)

it evaluates F with this being the value that new will return, which then gets assigned to f.


5) .constructor normally comes from F.prototype through the . lookup:

f.constructor === F
!f.hasOwnProperty('constructor')
Object.getPrototypeOf(f) === F.prototype
F.prototype.hasOwnProperty('constructor')
F.prototype.constructor === f.constructor

When we write f.constructor, JavaScript does the . lookup as:

  • f does not have .constructor
  • f.__proto__ === F.prototype has .constructor === F, so take it

The result f.constructor == F is intuitively correct, since F is used to construct f, e.g. set fields, much like in classic OOP languages.


6) Classical inheritance syntax can be achieved by manipulating prototypes chains.

ES6 adds the class and extends keywords, which are mostly syntax sugar for previously possible prototype manipulation madness.

class C {
    constructor(i) {
        this.i = i
    }
    inc() {
        return this.i + 1
    }
}

class D extends C {
    constructor(i) {
        super(i)
    }
    inc2() {
        return this.i + 2
    }
}
// Inheritance syntax works as expected.
c = new C(1)
c.inc() === 2
(new D(1)).inc() === 2
(new D(1)).inc2() === 3
// "Classes" are just function objects.
C.constructor === Function
C.__proto__ === Function.prototype
D.constructor === Function
// D is a function "indirectly" through the chain.
D.__proto__ === C
D.__proto__.__proto__ === Function.prototype
// "extends" sets up the prototype chain so that base class
// lookups will work as expected
var d = new D(1)
d.__proto__ === D.prototype
D.prototype.__proto__ === C.prototype
// This is what `d.inc` actually does.
d.__proto__.__proto__.inc === C.prototype.inc
// Class variables
// No ES6 syntax sugar apparently:
// http://stackoverflow.com/questions/22528967/es6-class-variable-alternatives
C.c = 1
C.c === 1
// Because `D.__proto__ === C`.
D.c === 1
// Nothing makes this work.
d.c === undefined

Simplified diagram without all predefined objects:

(c)----->(1)
 |   i
 |
 |
 |[[Prototype]]
 |
 |
 v    __proto__
(C)<--------------(D)         (d)
| |                |           |
| |                |           |
| |prototype       |prototype  |[[Prototype]] 
| |                |           |
| |                |           |
| |                | +---------+
| |                | |
| |                | |
| |                v v
|[[Prototype]]    (D.prototype)--------> (inc2 function object)
| |                |             inc2
| |                |
| |                |[[Prototype]]
| |                |
| |                |
| | +--------------+
| | |
| | |
| v v
| (C.prototype)------->(inc function object)
|                inc
v
Function.prototype

Let's take a moment to study how the following works:

c = new C(1)
c.inc() === 2

The first line sets c.i to 1 as explained in "4)".

On the second line, when we do:

c.inc()
  • .inc is found through the [[Prototype]] chain: c -> C -> C.prototype -> inc
  • when we call a function in Javascript as X.Y(), JavaScript automatically sets this to equal X inside the Y() function call!

The exact same logic also explains d.inc and d.inc2.

This article https://javascript.info/class#not-just-a-syntax-sugar mentions further effects of class worth knowing. Some of them may not be achievable without the class keyword (TODO check which):

Unable to install pyodbc on Linux

I have referenced this question several times, and gone on to actually find the answer I was looking for here: pyodbc wiki

To avoid gcc error on Ubuntu Linux, I did:

sudo aptitude install g++

I also installed the following 2 packages from Synaptic:

  • python-dev

  • tdsodbc

Is there a way to list all resources in AWS

Yes.

I had the same issue, trying to figure out what exactly is going on in my AWS account.

Eventually, I ended up writing AWSRetriver, a desktop tool to list AWS resources on all regions.

It is a simple and straight-forward tool that lists everything... (hopefully) AWS Resources

Why is json_encode adding backslashes?

This happens because the JSON format uses ""(Quotes) and anything in between these quotes is useful information (either key or the data).

Suppose your data was : He said "This is how it is done". Then the actual data should look like "He said \"This is how it is done\".".

This ensures that the \" is treated as "(Quotation mark) and not as JSON formatting. This is called escape character.

This usually happens when one tries to encode an already JSON encoded data, which is a common way I have seen this happen.

Try this

$arr = ['This is a sample','This is also a "sample"']; echo json_encode($arr);

OUTPUT:

["This is a sample","This is also a \"sample\""]

What are DDL and DML?

DDL is Data Definition Language : Specification notation for defining the database schema. It works on Schema level.

DDL commands are:

create,drop,alter,rename

For example:

create table account (
  account_number  char(10),
 balance integer);

DML is Data Manipulation Language .It is used for accessing and manipulating the data.

DML commands are:

select,insert,delete,update,call

For example :

update account set balance = 1000 where account_number = 01;

The ResourceConfig instance does not contain any root resource classes

Probably too late but this is how I resolved this error.

If this solution is not working,

<init-param>
    <param-name>com.sun.jersey.config.property.packages</param-name>
    <param-value>/* Name of Package where your service class exists */</param-value>
</init-param>

In eclipse:

RightClick on your Project Or Select Project and press Alt + Enter On the left-hand side of the opened window find Java Build Path

Select Libraries from the right tab panel: If there is anything which is corrupted or showing cross mark on top of the jars, remove and add the same jar again

Apply and Close

Rebuild your project

java: use StringBuilder to insert at the beginning

You can use the insert method with the offset. as offset set to '0' means you are appending to the front of your StringBuilder.

StringBuilder sb = new StringBuilder();
for(int i=0;i<100;i++){
    sb.insert(0,i);
}

NOTE: as the insert method accept all types of primitives, you can use for int, long, char[] etc.

How do I make a LinearLayout scrollable?

You can implement it using View.scrollTo(..) also.

postDelayed(new Runnable() {
            public void run() {

                counter = (int) (counter + 10);
                handler.postDelayed(this, 100);

                    llParent.scrollTo(counter , 0);
                }

            }
        }, 1000L);

Proper use of 'yield return'

I know this is an old question, but I'd like to offer one example of how the yield keyword can be creatively used. I have really benefited from this technique. Hopefully this will be of assistance to anyone else who stumbles upon this question.

Note: Don't think about the yield keyword as merely being another way to build a collection. A big part of the power of yield comes in the fact that execution is paused in your method or property until the calling code iterates over the next value. Here's my example:

Using the yield keyword (alongside Rob Eisenburg's Caliburn.Micro coroutines implementation) allows me to express an asynchronous call to a web service like this:

public IEnumerable<IResult> HandleButtonClick() {
    yield return Show.Busy();

    var loginCall = new LoginResult(wsClient, Username, Password);
    yield return loginCall;
    this.IsLoggedIn = loginCall.Success;

    yield return Show.NotBusy();
}

What this will do is turn my BusyIndicator on, call the Login method on my web service, set my IsLoggedIn flag to the return value, and then turn the BusyIndicator back off.

Here's how this works: IResult has an Execute method and a Completed event. Caliburn.Micro grabs the IEnumerator from the call to HandleButtonClick() and passes it into a Coroutine.BeginExecute method. The BeginExecute method starts iterating through the IResults. When the first IResult is returned, execution is paused inside HandleButtonClick(), and BeginExecute() attaches an event handler to the Completed event and calls Execute(). IResult.Execute() can perform either a synchronous or an asynchronous task and fires the Completed event when it's done.

LoginResult looks something like this:

public LoginResult : IResult {
    // Constructor to set private members...

    public void Execute(ActionExecutionContext context) {
        wsClient.LoginCompleted += (sender, e) => {
            this.Success = e.Result;
            Completed(this, new ResultCompletionEventArgs());
        };
        wsClient.Login(username, password);
    }

    public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
    public bool Success { get; private set; }
}

It may help to set up something like this and step through the execution to watch what's going on.

Hope this helps someone out! I've really enjoyed exploring the different ways yield can be used.

No submodule mapping found in .gitmodule for a path that's not a submodule

The folder mapping can be found in .git/modules folder (each has config file with reference to its worktree), so make sure these folders correspond to the configuration in .gitmodules and .git/config.

So .gitmodules has the correct path:

[submodule "<path>"]
  path = <path>
  url = [email protected]:foo/bar.git

and in .git/modules/<path>/config in [core] section you've the right path to your <path>, e.g.

[core]
  repositoryformatversion = 0
  filemode = true
  bare = false
  logallrefupdates = true
  worktree = ../../../<path>

If the right folder in .git/modules is missing, then you've to go to your submodule dir and try git reset HEAD --hard or git checkout master -f. If this won't help, you probably want to remove all the references to the broken submodule and add it again, then see: Rename a git submodule.

How do I change the font size of a UILabel in Swift?

Swift-3.1

label.font = UIFont.systemFont(ofSize: 12)

Remove white space below image

You're seeing the space for descenders (the bits that hang off the bottom of 'y' and 'p') because img is an inline element by default. This removes the gap:

.youtube-thumb img { display: block; }

ffprobe or avprobe not found. Please install one

I know the user asked this for Linux, but I had this issue in Windows (10 64bits) and found little information, so this is how I solved it:

  • Download LIBAV, I used libav-11.3-win64.7z. Just copy "avprobe.exe" and all DLLs from "/win64/usr/bin" to where "youtube-dl.exe" is.

In case LIBAV does not help, try with FFMPEG, copying the contents of the "bin" folder to where "youtube-dl.exe" is. That did not help me, but others said it did, so it may worth a try.

Hope this helps someone having the issue in Windows.

Escape invalid XML characters in C#

Use SecurityElement.Escape

using System;
using System.Security;

class Sample {
  static void Main() {
    string text = "Escape characters : < > & \" \'";
    string xmlText = SecurityElement.Escape(text);
//output:
//Escape characters : &lt; &gt; &amp; &quot; &apos;
    Console.WriteLine(xmlText);
  }
}

TypeError: 'int' object is not callable

Somewhere else in your code you have something that looks like this:

round = 42

Then when you write

round((a/b)*0.9*c)

that is interpreted as meaning a function call on the object bound to round, which is an int. And that fails.

The problem is whatever code binds an int to the name round. Find that and remove it.

Deserialize JSON with C#

Serialization:

// Convert an object to JSON string format
string jsonData = JsonConvert.SerializeObject(obj);

Response.Write(jsonData);

Deserialization::

To deserialize a dynamic object

  string json = @"{
      'Name': 'name',
      'Description': 'des'
    }";

var res = JsonConvert.DeserializeObject< dynamic>(json);

Response.Write(res.Name);

Multiple WHERE Clauses with LINQ extension methods

results = context.Orders.Where(o => o.OrderDate <= today && today <= o.OrderDate)

The select is uneeded as you are already working with an order.

form_for with nested resources

You don't need to do special things in the form. You just build the comment correctly in the show action:

class ArticlesController < ActionController::Base
  ....
  def show
    @article = Article.find(params[:id])
    @new_comment = @article.comments.build
  end
  ....
end

and then make a form for it in the article view:

<% form_for @new_comment do |f| %>
   <%= f.text_area :text %>
   <%= f.submit "Post Comment" %>
<% end %>

by default, this comment will go to the create action of CommentsController, which you will then probably want to put redirect :back into so you're routed back to the Article page.

Check if all elements in a list are identical

A solution faster than using set() that works on sequences (not iterables) is to simply count the first element. This assumes the list is non-empty (but that's trivial to check, and decide yourself what the outcome should be on an empty list)

x.count(x[0]) == len(x)

some simple benchmarks:

>>> timeit.timeit('len(set(s1))<=1', 's1=[1]*5000', number=10000)
1.4383411407470703
>>> timeit.timeit('len(set(s1))<=1', 's1=[1]*4999+[2]', number=10000)
1.4765670299530029
>>> timeit.timeit('s1.count(s1[0])==len(s1)', 's1=[1]*5000', number=10000)
0.26274609565734863
>>> timeit.timeit('s1.count(s1[0])==len(s1)', 's1=[1]*4999+[2]', number=10000)
0.25654196739196777

WPF Datagrid Get Selected Cell Value

I struggled with this one for a long time! (Using VB.NET) Basically you get the row index and column index of the selected cell, and then use that to access the value.

Private Sub LineListDataGrid_SelectedCellsChanged(sender As Object, e As SelectedCellsChangedEventArgs) Handles LineListDataGrid.SelectedCellsChanged

    Dim colInd As Integer = LineListDataGrid.CurrentCell.Column.DisplayIndex

    Dim rowInd As Integer = LineListDataGrid.Items.IndexOf(LineListDataGrid.CurrentItem)

    Dim item As String

    Try
        item = LLDB.LineList.Rows(rowInd)(colInd)
    Catch
        Exit Sub
    End Try

End Sub

End Class

How to target the href to div

Put for div same name as in href target.

ex: <div name="link"> and <a href="#link">

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

You can use :+ to append element to array and +: to prepend it:

0 +: array :+ 4

should produce:

res3: Array[Int] = Array(0, 1, 2, 3, 4)

It's the same as with any other implementation of Seq.

Oracle PL Sql Developer cannot find my tnsnames.ora file

I had the same problema, but as described in the manual.pdf, you have to:

You are using an Oracle Instant Client but have not set all required environment variables:

  • PATH: Needs to include the Instant Client directory where oci.dll is located
  • TNS_ADMIN: Needs to point to the directory where tnsnames.ora is located.
  • NLS_LANG: Defines the language, territory, and character set for the client.

Regards

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

There's also AppGyver Steroids that unites PhoneGap and Native UI nicely.

With Steroids you can add things like native tabs, native navigation bar, native animations and transitions, native modal windows, native drawer/panel (facebooks side menu) etc. to your PhoneGap app.

Here's a demo: http://youtu.be/oXWwDMdoTCk?t=20m17s

Linq : select value in a datatable column

If the return value is string and you need to search by Id you can use:

string name = datatable.AsEnumerable().Where(row => Convert.ToInt32(row["Id"]) == Id).Select(row => row.Field<string>("name")).ToString();

or using generic variable:

var name = datatable.AsEnumerable().Where(row => Convert.ToInt32(row["Id"]) == Id).Select(row => row.Field<string>("name"));

How to convert milliseconds into a readable date?

No, you'll need to do it manually.

_x000D_
_x000D_
function prettyDate(date) {_x000D_
  var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',_x000D_
                'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];_x000D_
_x000D_
  return months[date.getUTCMonth()] + ' ' + date.getUTCDate() + ', ' + date.getUTCFullYear();_x000D_
}_x000D_
_x000D_
console.log(prettyDate(new Date(1324339200000)));
_x000D_
_x000D_
_x000D_

What is the Linux equivalent to DOS pause?

read without any parameters will only continue if you press enter. The DOS pause command will continue if you press any key. Use read –n1 if you want this behaviour.

How do ACID and database transactions work?

[Gray] introduced the ACD properties for a transaction in 1981. In 1983 [Haerder] added the Isolation property. In my opinion, the ACD properties would be have a more useful set of properties to discuss. One interpretation of Atomicity (that the transaction should be atomic as seen from any client any time) would actually imply the isolation property. The "isolation" property is useful when the transaction is not isolated; when the isolation property is relaxed. In ANSI SQL speak: if the isolation level is weaker then SERIALIZABLE. But when the isolation level is SERIALIZABLE, the isolation property is not really of interest.

I have written more about this in a blog post: "ACID Does Not Make Sense".

http://blog.franslundberg.com/2013/12/acid-does-not-make-sense.html

[Gray] The Transaction Concept, Jim Gray, 1981. http://research.microsoft.com/en-us/um/people/gray/papers/theTransactionConcept.pdf

[Haerder] Principles of Transaction-Oriented Database Recovery, Haerder and Reuter, 1983. http://www.stanford.edu/class/cs340v/papers/recovery.pdf

Return rows in random order

To be efficient, and random, it might be best to have two different queries.

Something like...

SELECT table_id FROM table

Then, in your chosen language, pick a random id, then pull that row's data.

SELECT * FROM table WHERE table_id = $rand_id

But that's not really a good idea if you're expecting to have lots of rows in the table. It would be better if you put some kind of limit on what you randomly select from. For publications, maybe randomly pick from only items posted within the last year.

How can I make this try_files directive work?

a very common try_files line which can be applied on your condition is

location / {
    try_files $uri $uri/ /test/index.html;
}

you probably understand the first part, location / matches all locations, unless it's matched by a more specific location, like location /test for example

The second part ( the try_files ) means when you receive a URI that's matched by this block try $uri first, for example http://example.com/images/image.jpg nginx will try to check if there's a file inside /images called image.jpg if found it will serve it first.

Second condition is $uri/ which means if you didn't find the first condition $uri try the URI as a directory, for example http://example.com/images/, ngixn will first check if a file called images exists then it wont find it, then goes to second check $uri/ and see if there's a directory called images exists then it will try serving it.

Side note: if you don't have autoindex on you'll probably get a 403 forbidden error, because directory listing is forbidden by default.

EDIT: I forgot to mention that if you have index defined, nginx will try to check if the index exists inside this folder before trying directory listing.

Third condition /test/index.html is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the file index.html inside the folder test and serve it if it exists.

If the third condition fails too, then nginx will serve the 404 error page.

Also there's something called named locations, like this

location @error {
}

You can call it with try_files like this

try_files $uri $uri/ @error;

TIP: If you only have 1 condition you want to serve, like for example inside folder images you only want to either serve the image or go to 404 error, you can write a line like this

location /images {
    try_files $uri =404;
}

which means either serve the file or serve a 404 error, you can't use only $uri by it self without =404 because you need to have a fallback option.
You can also choose which ever error code you want, like for example:

location /images {
    try_files $uri =403;
}

This will show a forbidden error if the image doesn't exist, or if you use 500 it will show server error, etc ..

Determine the size of an InputStream

This is a REALLY old thread, but it was still the first thing to pop up when I googled the issue. So I just wanted to add this:

InputStream inputStream = conn.getInputStream();
int length = inputStream.available();

Worked for me. And MUCH simpler than the other answers here.

Warning This solution does not provide reliable results regarding the total size of a stream. Except from the JavaDoc:

Note that while some implementations of {@code InputStream} will return * the total number of bytes in the stream, many will not.

How to make a countdown timer in Android?

public class Scan extends AppCompatActivity {
int minute;
long min;
TextView tv_timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scan2);
    tv_timer=findViewById(R.id.tv_timer);
    minute=Integer.parseInt("Your time in string form like 10");
    min= minute*60*1000;
    counter(min);
}
private void counter(long min) {
    CountDownTimer timer = new CountDownTimer(min, 1000) {
        public void onTick(long millisUntilFinished) {
            int seconds = (int) (millisUntilFinished / 1000) % 60;
            int minutes = (int) ((millisUntilFinished / (1000 * 60)) % 60);
            int hours = (int) ((millisUntilFinished / (1000 * 60 * 60)) % 24);
            tv_timer.setText(String.format("%d:%d:%d", hours, minutes, seconds));
        }
        public void onFinish() {
            Toast.makeText(getApplicationContext(), "Your time has been completed",
                    Toast.LENGTH_LONG).show();
        }
    };
    timer.start();
}

}

How to set breakpoints in inline Javascript in Google Chrome?

Another intuitive simple trick to debug especially script inside html returned by ajax, is to temporary put console.log("test") inside the script.

Once you have fired the event, open up the console tab inside the developer tools. you will see the source file link shown up at the right side of the "test" debug print statement. just click on the source (something like VM4xxx) and you can now set the break point.

P.S.: besides, you can consider to put "debugger" statement if you are using chrome, like what is being suggested by @Matt Ball

Adding a caption to an equation in LaTeX

You may want to look at http://tug.ctan.org/tex-archive/macros/latex/contrib/float/ which allows you to define new floats using \newfloat

I say this because captions are usually applied to floats.

Straight ahead equations (those written with $ ... $, $$ ... $$, begin{equation}...) are in-line objects that do not support \caption.

This can be done using the following snippet just before \begin{document}

\usepackage{float}
\usepackage{aliascnt}
\newaliascnt{eqfloat}{equation}
\newfloat{eqfloat}{h}{eqflts}
\floatname{eqfloat}{Equation}

\newcommand*{\ORGeqfloat}{}
\let\ORGeqfloat\eqfloat
\def\eqfloat{%
  \let\ORIGINALcaption\caption
  \def\caption{%
    \addtocounter{equation}{-1}%
    \ORIGINALcaption
  }%
  \ORGeqfloat
}

and when adding an equation use something like

\begin{eqfloat}
\begin{equation}
f( x ) = ax + b
\label{eq:linear}
\end{equation}
\caption{Caption goes here}
\end{eqfloat}

Why are you not able to declare a class as static in Java?

So, I'm coming late to the party, but here's my two cents - philosophically adding to Colin Hebert's answer.

At a high level your question deals with the difference between objects and types. While there are many cars (objects), there is only one Car class (type). Declaring something as static means that you are operating in the "type" space. There is only one. The top-level class keyword already defines a type in the "type" space. As a result "public static class Car" is redundant.

Why does HTML think “chucknorris” is a color?

The rules for parsing colors on legacy attributes involves additional steps than those mentioned in existing answers. The truncate component to 2 digits part is described as:

  1. Discard all characters except the last 8
  2. Discard leading zeros one by one as long as all components have a leading zero
  3. Discard all characters except the first 2

Some examples:

oooFoooFoooF
000F 000F 000F                <- replace, pad and chunk
0F 0F 0F                      <- leading zeros truncated
0F 0F 0F                      <- truncated to 2 characters from right

oooFooFFoFFF
000F 00FF 0FFF                <- replace, pad and chunk
00F 0FF FFF                   <- leading zeros truncated
00 0F FF                      <- truncated to 2 characters from right

ABCooooooABCooooooABCoooooo
ABC000000 ABC000000 ABC000000 <- replace, pad and chunk
BC000000 BC000000 BC000000    <- truncated to 8 characters from left
BC BC BC                      <- truncated to 2 characters from right

AoCooooooAoCooooooAoCoooooo
A0C000000 A0C000000 A0C000000 <- replace, pad and chunk
0C000000 0C000000 0C000000    <- truncated to 8 characters from left
C000000 C000000 C000000       <- leading zeros truncated
C0 C0 C0                      <- truncated to 2 characters from right

Below is a partial implementation of the algorithm. It does not handle errors or cases where the user enters a valid color.

_x000D_
_x000D_
function parseColor(input) {_x000D_
  // todo: return error if input is ""_x000D_
  input = input.trim();_x000D_
  // todo: return error if input is "transparent"_x000D_
  // todo: return corresponding #rrggbb if input is a named color_x000D_
  // todo: return #rrggbb if input matches #rgb_x000D_
  // todo: replace unicode code points greater than U+FFFF with 00_x000D_
  if (input.length > 128) {_x000D_
    input = input.slice(0, 128);_x000D_
  }_x000D_
  if (input.charAt(0) === "#") {_x000D_
    input = input.slice(1);_x000D_
  }_x000D_
  input = input.replace(/[^0-9A-Fa-f]/g, "0");_x000D_
  while (input.length === 0 || input.length % 3 > 0) {_x000D_
    input += "0";_x000D_
  }_x000D_
  var r = input.slice(0, input.length / 3);_x000D_
  var g = input.slice(input.length / 3, input.length * 2 / 3);_x000D_
  var b = input.slice(input.length * 2 / 3);_x000D_
  if (r.length > 8) {_x000D_
    r = r.slice(-8);_x000D_
    g = g.slice(-8);_x000D_
    b = b.slice(-8);_x000D_
  }_x000D_
  while (r.length > 2 && r.charAt(0) === "0" && g.charAt(0) === "0" && b.charAt(0) === "0") {_x000D_
    r = r.slice(1);_x000D_
    g = g.slice(1);_x000D_
    b = b.slice(1);_x000D_
  }_x000D_
  if (r.length > 2) {_x000D_
    r = r.slice(0, 2);_x000D_
    g = g.slice(0, 2);_x000D_
    b = b.slice(0, 2);_x000D_
  }_x000D_
  return "#" + r.padStart(2, "0") + g.padStart(2, "0") + b.padStart(2, "0");_x000D_
}_x000D_
_x000D_
$(function() {_x000D_
  $("#input").on("change", function() {_x000D_
    var input = $(this).val();_x000D_
    var color = parseColor(input);_x000D_
    var $cells = $("#result tbody td");_x000D_
    $cells.eq(0).attr("bgcolor", input);_x000D_
    $cells.eq(1).attr("bgcolor", color);_x000D_
_x000D_
    var color1 = $cells.eq(0).css("background-color");_x000D_
    var color2 = $cells.eq(1).css("background-color");_x000D_
    $cells.eq(2).empty().append("bgcolor: " + input, "<br>", "getComputedStyle: " + color1);_x000D_
    $cells.eq(3).empty().append("bgcolor: " + color, "<br>", "getComputedStyle: " + color2);_x000D_
  });_x000D_
});
_x000D_
body { font: medium monospace; }_x000D_
input { width: 20em; }_x000D_
table { table-layout: fixed; width: 100%; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
_x000D_
<p><input id="input" placeholder="Enter color e.g. chucknorris"></p>_x000D_
<table id="result">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Left Color</th>_x000D_
      <th>Right Color</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>&nbsp;</td>_x000D_
      <td>&nbsp;</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>&nbsp;</td>_x000D_
      <td>&nbsp;</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How can I replace non-printable Unicode characters in Java?

methods in blow for your goal

public static String removeNonAscii(String str)
{
    return str.replaceAll("[^\\x00-\\x7F]", "");
}

public static String removeNonPrintable(String str) // All Control Char
{
    return str.replaceAll("[\\p{C}]", "");
}

public static String removeSomeControlChar(String str) // Some Control Char
{
    return str.replaceAll("[\\p{Cntrl}\\p{Cc}\\p{Cf}\\p{Co}\\p{Cn}]", "");
}

public static String removeFullControlChar(String str)
{
    return removeNonPrintable(str).replaceAll("[\\r\\n\\t]", "");
} 

SSL cert "err_cert_authority_invalid" on mobile chrome only

if you're like me who is using AWS and CloudFront, here's how to solve the issue. it's similar to what others have shared except you don't use your domain's crt file, just what comodo emailed you.

cat COMODORSADomainValidationSecureServerCA.crt COMODORSAAddTrustCA.crt AddTrustExternalCARoot.crt > ssl-bundle.crt

this worked for me and my site no longer displays the ssl warning on chrome in android.

How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart

// aspx.cs

// Load CheckBoxList selected items into ListBox

    int status = 1;
    foreach (ListItem  s in chklstStates.Items  )
    {
        if (s.Selected == true)
        {
            if (ListBox1.Items.Count == 0)
            {
                ListBox1.Items.Add(s.Text);

            }
            else
            {
                foreach (ListItem list in ListBox1.Items)
                {
                    if (list.Text == s.Text)
                    {
                        status = status * 0;

                    }
                    else
                    {
                        status = status * 1;
                    }
                }
                if (status == 0)
                { }
               else
                {
                    ListBox1.Items.Add(s.Text);
                }
                status = 1;
            }
        }
    }
}

Utility of HTTP header "Content-Type: application/force-download" for mobile?

To download a file please use the following code ... Store the File name with location in $file variable. It supports all mime type

$file = "location of file to download"
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);

To know about Mime types please refer to this link: http://php.net/manual/en/function.mime-content-type.php

Ways to eliminate switch in code

'switch' is just a language construct and all language constructs can be thought of as tools to get a job done. As with real tools, some tools are better suited to one task than another (you wouldn't use a sledge hammer to put up a picture hook). The important part is how 'getting the job done' is defined. Does it need to be maintainable, does it need to be fast, does it need to scale, does it need to be extendable and so on.

At each point in the programming process there are usually a range of constructs and patterns that can be used: a switch, an if-else-if sequence, virtual functions, jump tables, maps with function pointers and so on. With experience a programmer will instinctively know the right tool to use for a given situation.

It must be assumed that anyone maintaining or reviewing code is at least as skilled as the original author so that any construct can be safely used.

How to close a web page on a button click, a hyperlink or a link button click?

To close a windows form (System.Windows.Forms.Form) when one of its button is clicked: in Visual Studio, open the form in the designer, right click on the button and open its property page, then select the field DialogResult an set it to OK or the appropriate value.

On logout, clear Activity history stack, preventing "back" button from opening logged-in-only Activities

I spent a few hours on this too ... and agree that FLAG_ACTIVITY_CLEAR_TOP sounds like what you'd want: clear the entire stack, except for the activity being launched, so the Back button exits the application. Yet as Mike Repass mentioned, FLAG_ACTIVITY_CLEAR_TOP only works when the activity you're launching is already in the stack; when the activity's not there, the flag doesn't do anything.

What to do? Put the activity being launching in the stack with FLAG_ACTIVITY_NEW_TASK, which makes that activity the start of a new task on the history stack. Then add the FLAG_ACTIVITY_CLEAR_TOP flag.

Now, when FLAG_ACTIVITY_CLEAR_TOP goes to find the new activity in the stack, it'll be there and be pulled up before everything else is cleared.

Here's my logout function; the View parameter is the button to which the function's attached.

public void onLogoutClick(final View view) {
    Intent i = new Intent(this, Splash.class);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(i);
    finish();
}

How to convert 1 to true or 0 to false upon model fetch

Assigning Comparison to property value

JavaScript

You could assign the comparison of the property to "1"

obj["isChecked"] = (obj["isChecked"]==="1");

This only evaluates for a String value of "1" though. Other variables evaulate to false like an actual typeof number would be false. (i.e. obj["isChecked"]=1)

If you wanted to be indiscrimate about "1" or 1, you could use:

obj["isChecked"] = (obj["isChecked"]=="1");

Example Outputs

console.log(obj["isChecked"]==="1"); // true
console.log(obj["isChecked"]===1); // false
console.log(obj["isChecked"]==1); // true
console.log(obj["isChecked"]==="0"); // false
console.log(obj["isChecked"]==="Elephant"); // false

PHP

Same concept in PHP

$obj["isChecked"] = ($obj["isChecked"] == "1");

The same operator limitations as stated above for JavaScript apply.

Double Not

The 'double not' also works. It's confusing when people first read it but it works in both languages for integer/number type values. It however does not work in JavaScript for string type values as they always evaluate to true:

JavaScript

!!"1"; //true
!!"0"; //true
!!1; //true
!!0; //false
!!parseInt("0",10); // false

PHP

echo !!"1"; //true
echo !!"0"; //false
echo !!1; //true
echo !!0; //false

Python: get key of index in dictionary

By definition dictionaries are unordered, and therefore cannot be indexed. For that kind of functionality use an ordered dictionary. Python Ordered Dictionary

Convert date to datetime in Python

There are several ways, although I do believe the one you mention (and dislike) is the most readable one.

>>> t=datetime.date.today()
>>> datetime.datetime.fromordinal(t.toordinal())
datetime.datetime(2009, 12, 20, 0, 0)
>>> datetime.datetime(t.year, t.month, t.day)
datetime.datetime(2009, 12, 20, 0, 0)
>>> datetime.datetime(*t.timetuple()[:-4])
datetime.datetime(2009, 12, 20, 0, 0)

and so forth -- but basically they all hinge on appropriately extracting info from the date object and ploughing it back into the suitable ctor or classfunction for datetime.

Read tab-separated file line into array

If you really want to split every word (bash meaning) into a different array index completely changing the array in every while loop iteration, @ruakh's answer is the correct approach. But you can use the read property to split every read word into different variables column1, column2, column3 like in this code snippet

while IFS=$'\t' read -r column1 column2 column3 ; do
  printf "%b\n" "column1<${column1}>"
  printf "%b\n" "column2<${column2}>"
  printf "%b\n" "column3<${column3}>"
done < "myfile"

to reach a similar result avoiding array index access and improving your code readability by using meaningful variable names (of course using columnN is not a good idea to do so).

Set Background cell color in PHPExcel

Seems like there's a bug with applyFromArray right now that won't accept color, but this worked for me:

$objPHPExcel
    ->getActiveSheet()
    ->getStyle('A1')
    ->getFill()
    ->getStartColor()
    ->setRGB('FF0000');

How do I export an Android Studio project?

In the Android Studio go to File then Close Project. Then take the folder (in the workspace folder) of the project and copy it to a flash memory or whatever. Then when you get comfortable at home, copy this folder in the workspace folder you've already created, open the Android Studio and go to File then Open and import this project into your workspace.

The problem you have with this is that you're searching for the wrong term here, because in Android, exporting a project means compiling it to .apk file (not exporting the project). Import/Export is used for the .apk management, what you need is Open/Close project, the other thing is just copy/paste.

Error on renaming database in SQL Server 2008 R2

That's because someone else is accessing the database. Put the database into single user mode then rename it.

This link might help:
http://msdn.microsoft.com/en-IN/library/ms345378(v=sql.105).aspx

and also:
http://msdn.microsoft.com/en-us/library/ms345378.aspx

What is the meaning of # in URL and how can I use that?

It specifies an "Anchor", or a position on the page, and allows you to "jump" or "scroll" to that position on the page.

Please see this page for more details.

AndroidStudio gradle proxy

For the new android studio 1.2 you find the gradle vm args under:

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

How to run function of parent window when child window closes?

Check following link. This would be helpful too..

In Parent Window:

function OpenChildAsPopup() {
        var childWindow = window.open("ChildWindow.aspx", "_blank",
        "width=200px,height=350px,left=200,top=100");
        childWindow.focus();
 }

function ChangeBackgroudColor() {
        var para = document.getElementById('samplePara');
        if (para !="undefied") {
            para.style.backgroundColor = '#6CDBF5';
        }
 }

Parent Window HTML Markup:

<div>
  <p id="samplePara" style="width: 350px;">
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
  </p><br />
 <asp:Button ID="Button1" Text="Open Child Window" 
         runat="server" OnClientClick="OpenChildAsPopup();"/>
</div>

In Child Window:

// This will be called when the child window is closed.     
  window.onunload = function (e) {
        opener.ChangeBackgroudColor();
        //or you can do
        //var para = opener.document.getElementById('samplePara');
        //if (para != "undefied") {
        //    para.style.backgroundColor = '#6CDBF5';
        //}
    };

Pandas aggregate count distinct

Just adding to the answers already given, the solution using the string "nunique" seems much faster, tested here on ~21M rows dataframe, then grouped to ~2M

%time _=g.agg({"id": lambda x: x.nunique()})
CPU times: user 3min 3s, sys: 2.94 s, total: 3min 6s
Wall time: 3min 20s

%time _=g.agg({"id": pd.Series.nunique})
CPU times: user 3min 2s, sys: 2.44 s, total: 3min 4s
Wall time: 3min 18s

%time _=g.agg({"id": "nunique"})
CPU times: user 14 s, sys: 4.76 s, total: 18.8 s
Wall time: 24.4 s

does linux shell support list data structure?

For make a list, simply do that

colors=(red orange white "light gray")

Technically is an array, but - of course - it has all list features.
Even python list are implemented with array

'ls' is not recognized as an internal or external command, operable program or batch file

We can use ls and many other Linux commands in Windows cmd. Just follow these steps.

Steps:

1) Install Git in your computer - https://git-scm.com/downloads.

2) After installing Git, go to the folder in which Git is installed. Mostly it will be in C drive and then Program Files Folder.

3) In Program Files folder, you will find the folder named Git, find the bin folder which is inside usr folder in the Git folder.

In my case, the location for bin folder was - C:\Program Files\Git\usr\bin

4) Add this location (C:\Program Files\Git\usr\bin) in path variable, in system environment variables.

5) You are done. Restart cmd and try to run ls and other Linux commands.

How to disable an input box using angular.js

I created a directive for this (angular stable 1.0.8)

<input type="text" input-disabled="editableInput" />
<button ng-click="editableInput = !editableInput">enable/disable</button>

app.controller("myController", function(){
  $scope.editableInput = false;
});

app.directive("inputDisabled", function(){
  return function(scope, element, attrs){
    scope.$watch(attrs.inputDisabled, function(val){
      if(val)
        element.removeAttr("disabled");
      else
        element.attr("disabled", "disabled");
    });
  }
});

Changing Java Date one hour back

You can use from bellow code for date and time :

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
       //get current date time with Calendar()
       Calendar cal = Calendar.getInstance();
       System.out.println("Current Date Time : " + dateFormat.format(cal.getTime()));

       cal.add(Calendar.DATE, 1);
       System.out.println("Add one day to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.MONTH, 1);
       System.out.println("Add one month to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.YEAR, 1);
       System.out.println("Add one year to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.HOUR, 1);
       System.out.println("Add one hour to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.MINUTE, 1);
       System.out.println("Add one minute to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.SECOND, 1);
       System.out.println("Add one second to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.DATE, -1);
       System.out.println("Subtract one day from current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.MONTH, -1);
       System.out.println("Subtract one month from current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.YEAR, -1);
       System.out.println("Subtract one year from current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.HOUR, -1);
       System.out.println("Subtract one hour from current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.MINUTE, -1);
       System.out.println("Subtract one minute from current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.SECOND, -1);
       System.out.println("Subtract one second from current date : " + dateFormat.format(cal.getTime()));

Output :

Current Date Time : 2008/12/28 10:24:53
Add one day to current date : 2008/12/29 10:24:53
Add one month to current date : 2009/01/28 10:24:53
Add one year to current date : 2009/12/28 10:24:53
Add one hour to current date : 2008/12/28 11:24:53
Add one minute to current date : 2008/12/28 10:25:53
Add one second to current date : 2008/12/28 10:24:54
Subtract one day from current date : 2008/12/27 10:24:53
Subtract one month from current date : 2008/11/28 10:24:53
Subtract one year from current date : 2007/12/28 10:24:53
Subtract one hour from current date : 2008/12/28 09:24:53
Subtract one minute from current date : 2008/12/28 10:23:53
Subtract one second from current date : 2008/12/28 10:24:52

This link is good : See here

And see : See too

And : Here

And : Here

And : Here

If you need just time :

DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

What generates the "text file busy" message in Unix?

This error means some other process or user is accessing your file. Use lsof to check what other processes are using it. You can use kill command to kill it if needed.

How can I use mySQL replace() to replace strings in multiple records?

This will help you.

UPDATE play_school_data SET title= REPLACE(title, "&#39;", "'") WHERE title = "Elmer&#39;s Parade";

Result:

title = Elmer's Parade

Change background color of selected item on a ListView

use the below xml as listitem background it will solve all the issues. The selected will be highlighted though you scrolled down.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/holo_orange_dark" android:state_pressed="true"/>
<item android:drawable="@android:color/holo_green_light" android:state_selected="true"/>
<item android:drawable="@android:color/holo_green_light" android:state_activated="true"/>

Thanks, Nagendra

Parse strings to double with comma and point

Extension to parse decimal number from string.

  • No matter number will be on the beginning, in the end, or in the middle of a string.
  • No matter if there will be only number or lot of "garbage" letters.
  • No matter what is delimiter configured in the cultural settings on the PC: it will parse dot and comma both correctly.
  • Ability to set decimal symbol manually.

    public static class StringExtension
    {
        public static double DoubleParseAdvanced(this string strToParse, char decimalSymbol = ',')
        {
            string tmp = Regex.Match(strToParse, @"([-]?[0-9]+)([\s])?([0-9]+)?[." + decimalSymbol + "]?([0-9 ]+)?([0-9]+)?").Value;
    
            if (tmp.Length > 0 && strToParse.Contains(tmp))
            {
                var currDecSeparator = System.Windows.Forms.Application.CurrentCulture.NumberFormat.NumberDecimalSeparator;
    
                tmp = tmp.Replace(".", currDecSeparator).Replace(decimalSymbol.ToString(), currDecSeparator);
    
                return double.Parse(tmp);
            }
    
            return 0;
        }
    }
    

How to use:

"It's 4.45 O'clock now".DoubleParseAdvanced(); // will return 4.45
"It's 4,45 O'clock now".DoubleParseAdvanced(); // will return 4.45
"It's 4:45 O'clock now".DoubleParseAdvanced(':'); // will return 4.45

load jquery after the page is fully loaded

It is advised to load your scripts at the bottom of your <body> block to speed up the page load, like this:

<body>
<!-- your content -->
<!-- your scripts -->
<script src=".."></script>
</body>
</html>

Sending "User-agent" using Requests library in Python

The user-agent should be specified as a field in the header.

Here is a list of HTTP header fields, and you'd probably be interested in request-specific fields, which includes User-Agent.

If you're using requests v2.13 and newer

The simplest way to do what you want is to create a dictionary and specify your headers directly, like so:

import requests

url = 'SOME URL'

headers = {
    'User-Agent': 'My User Agent 1.0',
    'From': '[email protected]'  # This is another valid field
}

response = requests.get(url, headers=headers)

If you're using requests v2.12.x and older

Older versions of requests clobbered default headers, so you'd want to do the following to preserve default headers and then add your own to them.

import requests

url = 'SOME URL'

# Get a copy of the default headers that requests would use
headers = requests.utils.default_headers()

# Update the headers with your custom ones
# You don't have to worry about case-sensitivity with
# the dictionary keys, because default_headers uses a custom
# CaseInsensitiveDict implementation within requests' source code.
headers.update(
    {
        'User-Agent': 'My User Agent 1.0',
    }
)

response = requests.get(url, headers=headers)

Export javascript data to CSV file without server interaction

See adeneo's answer, but don't forget encodeURIComponent!

a.href     = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csvString);

Also, I needed to do "\r\n" not just "\n" for the row delimiter.

var csvString = csvRows.join("\r\n");

Revised fiddle: http://jsfiddle.net/7Q3c6/