Programs & Examples On #Servermanager

Formatting Decimal places in R

I'm using this variant for force print K decimal places:

# format numeric value to K decimal places
formatDecimal <- function(x, k) format(round(x, k), trim=T, nsmall=k)

COALESCE with Hive SQL

Hive supports bigint literal since 0.8 version. So, additional "L" is enough:

COALESCE(column, 0L)

Logger slf4j advantages of formatting with {} instead of string concatenation

Another alternative is String.format(). We are using it in jcabi-log (static utility wrapper around slf4j).

Logger.debug(this, "some variable = %s", value);

It's much more maintainable and extendable. Besides, it's easy to translate.

Arrays.asList() of an array

Use java.utils.Arrays:

public int getTheNumber(int[] factors) {
    int[] f = (int[])factors.clone();
    Arrays.sort(f);
    return f[0]*f[(f.length-1];
}

Or if you want to be efficient avoid all the object allocation just actually do the work:

public static int getTheNumber(int[] array) {
    if (array.length == 0)
        throw new IllegalArgumentException();
    int min = array[0];
    int max = array[0];
    for (int i = 1; i< array.length;++i) {
        int v = array[i];
        if (v < min) {
            min = v;
        } else if (v > max) {
            max = v;
        }
    }
    return min * max;
}

fatal: Unable to create temporary file '/home/username/git/myrepo.git/./objects/pack/tmp_pack_XXXXXX': Permission denied

It would seem like your user doesn't have permission to write to that directory on the server. Please make sure that the permissions are correct. The user will need write permissions on that directory.

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

I have just found this pretty solution:

import sys; sys.path.insert(0, '..') # add parent folder path where lib folder is
import lib.store_load # store_load is a file on my library folder

You just want some functions of that file

from lib.store_load import your_function_name

If python version >= 3.3 you do not need init.py file in the folder

New Array from Index Range Swift

This works for me:

var test = [1, 2, 3]
var n = 2
var test2 = test[0..<n]

Your issue could be with how you're declaring your array to begin with.

EDIT:

To fix your function, you have to cast your Slice to an array:

func aFunction(numbers: Array<Int>, position: Int) -> Array<Int> {
    var newNumbers = Array(numbers[0..<position])
    return newNumbers
}

// test
aFunction([1, 2, 3], 2) // returns [1, 2]

Reading a registry key in C#

You're looking for the cunningly named Registry.GetValue method.

Face recognition Library

Here is a list of commercial vendors that provide off-the-shelf packages for facial recognition which run on Windows:

  1. Cybula - Information on their Facial Recognition SDK. This is a company founded by a University Professor and as such their website looks unprofessional. There's no pricing information or demo that you can download. You'll need to contact them for pricing information.

  2. NeuroTechnology - Information on their Facial Recognition SDK. This company has both up-front pricing information as well as an actual 30 day trial of their SDK.

  3. Pittsburgh Pattern Recognition - (Acquired by Google) Information on their Facial Tracking and Recognition SDK. The demos that they provide help you evaluate their technology but not their SDSK. You'll need to contact them for pricing information.

  4. Sensible Vision - Information on their SDK. Their site allows you to easily get a price quote and you can also order an evaluation kit that will help you evaluate their technology.

How can I know which radio button is selected via jQuery?

If you only have 1 set of radio buttons on 1 form, the jQuery code is as simple as this:

$( "input:checked" ).val()

How can I download HTML source in C#

The newest, most recent, up to date answer
This post is really old (it's 7 years old when I answered it), so no one of the other answers used the new and recommended way, which is HttpClient class.


HttpClient is considered the new API and it should replace the old ones (WebClient and WebRequest)

string url = "page url";
HttpClient client = new HttpClient();
using (HttpResponseMessage response = client.GetAsync(url).Result)
{
   using (HttpContent content = response.Content)
   {
      string result = content.ReadAsStringAsync().Result;
   }
}

for more information about how to use the HttpClient class (especially in async cases), you can refer this question


NOTE 1: If you want to use async/await

string url = "page url";
HttpClient client = new HttpClient();   // actually only one object should be created by Application
using (HttpResponseMessage response = await client.GetAsync(url))
{
   using (HttpContent content = response.Content)
   {
      string result = await content.ReadAsStringAsync();
   }
}

NOTE 2: If use C# 8 features

string url = "page url";
HttpClient client = new HttpClient();
using HttpResponseMessage response = await client.GetAsync(url);
using HttpContent content = response.Content;
string result = await content.ReadAsStringAsync();

How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

scrollbars in JTextArea

Simple Way to add JTextArea in JScrollBar with JScrollPan

import javax.swing.*;
public class ScrollingTextArea 
{
     JFrame f;
     JTextArea ta;
     JScrollPane scrolltxt;

     public ScrollingTextArea() 
     {
        // TODO Auto-generated constructor stub

        f=new JFrame();
        f.setLayout(null);
        f.setVisible(true);
        f.setSize(500,500);
        ta=new JTextArea();
        ta.setBounds(5,5,100,200);

        scrolltxt=new JScrollPane(ta);
        scrolltxt.setBounds(3,3,400,400);

         f.add(scrolltxt);

     }

     public static void main(String[] args) 
     {
        new ScrollingTextArea();
     }
}

Call removeView() on the child's parent first

Try remove scrollChildLayout from its parent view first?

scrollview.removeView(scrollChildLayout)

Or remove all the child from the parent view, and add them again.

scrollview.removeAllViews()

Controlling Spacing Between Table Cells

Use the border-spacing property on the table element to set the spacing between cells.

Make sure border-collapse is set to separate (or there will be a single border between each cell instead of a separate border around each one that can have spacing between them).

Difference between binary semaphore and mutex

You obviously use mutex to lock a data in one thread getting accessed by another thread at the same time. Assume that you have just called lock() and in the process of accessing data. This means that you don’t expect any other thread (or another instance of the same thread-code) to access the same data locked by the same mutex. That is, if it is the same thread-code getting executed on a different thread instance, hits the lock, then the lock() should block the control flow there. This applies to a thread that uses a different thread-code, which is also accessing the same data and which is also locked by the same mutex. In this case, you are still in the process of accessing the data and you may take, say, another 15 secs to reach the mutex unlock (so that the other thread that is getting blocked in mutex lock would unblock and would allow the control to access the data). Do you at any cost allow yet another thread to just unlock the same mutex, and in turn, allow the thread that is already waiting (blocking) in the mutex lock to unblock and access the data? Hope you got what I am saying here? As per, agreed upon universal definition!,

  • with “mutex” this can’t happen. No other thread can unlock the lock in your thread
  • with “binary-semaphore” this can happen. Any other thread can unlock the lock in your thread

So, if you are very particular about using binary-semaphore instead of mutex, then you should be very careful in “scoping” the locks and unlocks. I mean that every control-flow that hits every lock should hit an unlock call, also there shouldn’t be any “first unlock”, rather it should be always “first lock”.

Remove all of x axis labels in ggplot

You have to set to element_blank() in theme() elements you need to remove

ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

Remove an onclick listener

mTitleView.setOnClickListener(null) should do the trick.

A better design might be to do a check of the status in the OnClickListener and then determine whether or not the click should do something vs adding and clearing click listeners.

How to remove all leading zeroes in a string

Regex was proposed already, but not correctly:

<?php
    $number = '00000004523423400023402340240';
    $withoutLeadingZeroes = preg_replace('/^0+/', '', $number)
    echo $withoutLeadingZeroes;
?>

output is then:

4523423400023402340240

Background on Regex: the ^ signals beginning of string and the + sign signals more or none of the preceding sign. Therefore, the regex ^0+ matches all zeroes at the beginning of a string.

Regex to validate date format dd/mm/yyyy

For date MM/DD/YYYY you can use

^((((0[13578])|([13578])|(1[02]))[\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\/](([1-9])|([0-2][0-9]))))[\/]\d{4}$|^\d{4}$

It verify proper days and moths.

Remeber that you can check your regular expression at

regex101

which i recommend :)

Have fun!

Parse a URI String into Name-Value Collection

If you come across Android Java SDK;

This solution might be too late but it's the latest solution today.

You can use the below way to get the value of the some query, if there is no value it will return null.

String some = Uri.parse(url).getQueryParameter("some");

In order to get all the names of the query collection.

Set<String> names = Uri.parse(url).getQueryParameterNames();

How to return a file using Web API?

I've been wondering if there was a simple way to download a file in a more ... "generic" way. I came up with this.

It's a simple ActionResult that will allow you to download a file from a controller call that returns an IHttpActionResult. The file is stored in the byte[] Content. You can turn it into a stream if needs be.

I used this to return files stored in a database's varbinary column.

    public class FileHttpActionResult : IHttpActionResult
    {
        public HttpRequestMessage Request { get; set; }

        public string FileName { get; set; }
        public string MediaType { get; set; }
        public HttpStatusCode StatusCode { get; set; }

        public byte[] Content { get; set; }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            HttpResponseMessage response = new HttpResponseMessage(StatusCode);

            response.StatusCode = StatusCode;
            response.Content = new StreamContent(new MemoryStream(Content));
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            response.Content.Headers.ContentDisposition.FileName = FileName;
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(MediaType);

            return Task.FromResult(response);
        }
    }

How to get param from url in angular 4?

import {Router, ActivatedRoute, Params} from '@angular/router';

constructor(private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    this.activatedRoute.paramMap
    .subscribe( params => {
    let id = +params.get('id');
    console.log('id' + id);
    console.log(params);


id12
ParamsAsMap {params: {…}}
keys: Array(1)
0: "id"
length: 1
__proto__: Array(0)
params:
id: "12"
__proto__: Object
__proto__: Object
        }
        )

      }

How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?

You can use the build job step from Jenkins Pipeline (Minimum Jenkins requirement: 2.130).

Here's the full API for the build step: https://jenkins.io/doc/pipeline/steps/pipeline-build-step/

How to use build:

  • job: Name of a downstream job to build. May be another Pipeline job, but more commonly a freestyle or other project.
    • Use a simple name if the job is in the same folder as this upstream Pipeline job;
    • You can instead use relative paths like ../sister-folder/downstream
    • Or you can use absolute paths like /top-level-folder/nested-folder/downstream

Trigger another job using a branch as a param

At my company many of our branches include "/". You must replace any instances of "/" with "%2F" (as it appears in the URL of the job).

In this example we're using relative paths

    stage('Trigger Branch Build') {
        steps {
            script {
                    echo "Triggering job for branch ${env.BRANCH_NAME}"
                    BRANCH_TO_TAG=env.BRANCH_NAME.replace("/","%2F")
                    build job: "../my-relative-job/${BRANCH_TO_TAG}", wait: false
            }
        }
    }

Trigger another job using build number as a param

build job: 'your-job-name', 
    parameters: [
        string(name: 'passed_build_number_param', value: String.valueOf(BUILD_NUMBER)),
        string(name: 'complex_param', value: 'prefix-' + String.valueOf(BUILD_NUMBER))
    ]

Trigger many jobs in parallel

Source: https://jenkins.io/blog/2017/01/19/converting-conditional-to-pipeline/

More info on Parallel here: https://jenkins.io/doc/book/pipeline/syntax/#parallel

    stage ('Trigger Builds In Parallel') {
        steps {
            // Freestyle build trigger calls a list of jobs
            // Pipeline build() step only calls one job
            // To run all three jobs in parallel, we use "parallel" step
            // https://jenkins.io/doc/pipeline/examples/#jobs-in-parallel
            parallel (
                linux: {
                    build job: 'full-build-linux', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
                },
                mac: {
                    build job: 'full-build-mac', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
                },
                windows: {
                    build job: 'full-build-windows', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
                },
                failFast: false)
        }
    }

Or alternatively:

    stage('Build A and B') {
            failFast true
            parallel {
                stage('Build A') {
                    steps {
                            build job: "/project/A/${env.BRANCH}", wait: true
                    }
                }
                stage('Build B') {
                    steps {
                            build job: "/project/B/${env.BRANCH}", wait: true
                    }
                }
            }
    }

Difference between | and || or & and && for comparison

& and | are bitwise operators that can operate on both integer and Boolean arguments, and && and || are logical operators that can operate only on Boolean arguments. In many languages, if both arguments are Boolean, the key difference is that the logical operators will perform short circuit evaluation and not evaluate the second argument if the first argument is enough to determine the answer (e.g. in the case of &&, if the first argument is false, the second argument is irrelevant).

ASP.NET Core Identity - get current user

In .NET Core 2.0 the user already exists as part of the underlying inherited controller. Just use the User as you would normally or pass across to any repository code.

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Policy = "TENANT")]
[HttpGet("issue-type-selection"), Produces("application/json")]
public async Task<IActionResult> IssueTypeSelection()
{
    try
    {
        return new ObjectResult(await _item.IssueTypeSelection(User));
    }
    catch (ExceptionNotFound)
    {
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return Json(new
        {
            error = "invalid_grant",
            error_description = "Item Not Found"
        });
    }
}

This is where it inherits it from

#region Assembly Microsoft.AspNetCore.Mvc.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
// C:\Users\BhailDa\.nuget\packages\microsoft.aspnetcore.mvc.core\2.0.0\lib\netstandard2.0\Microsoft.AspNetCore.Mvc.Core.dll
#endregion

using System;
using System.IO;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.AspNetCore.Routing;
using Microsoft.Net.Http.Headers;

namespace Microsoft.AspNetCore.Mvc
{
    //
    // Summary:
    //     A base class for an MVC controller without view support.
    [Controller]
    public abstract class ControllerBase
    {
        protected ControllerBase();

        //
        // Summary:
        //     Gets the System.Security.Claims.ClaimsPrincipal for user associated with the
        //     executing action.
        public ClaimsPrincipal User { get; }

How to clear memory to prevent "out of memory error" in excel vba?

I had a similar problem that I resolved myself.... I think it was partially my code hogging too much memory while too many "big things"

in my application - the workbook goes out and grabs another departments "daily report".. and I extract out all the information our team needs (to minimize mistakes and data entry).

I pull in their sheets directly... but I hate the fact that they use Merged cells... which I get rid of (ie unmerge, then find the resulting blank cells, and fill with the values from above)

I made my problem go away by

a)unmerging only the "used cells" - rather than merely attempting to do entire column... ie finding the last used row in the column, and unmerging only this range (there is literally 1000s of rows on each of the sheet I grab)

b) Knowing that the undo only looks after the last ~16 events... between each "unmerge" - i put 15 events which clear out what is stored in the "undo" to minimize the amount of memory held up (ie go to some cell with data in it.. and copy// paste special value... I was GUESSING that the accumulated sum of 30sheets each with 3 columns worth of data might be taxing memory set as side for undoing

Yes it doesn't allow for any chance of an Undo... but the entire purpose is to purge the old information and pull in the new time sensitive data for analysis so it wasn't an issue

Sound corny - but my problem went away

Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected'

All methods described here didn't help me. But when I deleted the *.pfx file from my project and added it to the assembly's signing again, I built my project with without any error! I can't explain reasons why. But it worked for me.

VIM Disable Automatic Newline At End Of File

There is another way to approach this if you are using Git for source control. Inspired by an answer here, I wrote my own filter for use in a gitattributes file.

To install this filter, save it as noeol_filter somewhere in your $PATH, make it executable, and run the following commands:

git config --global filter.noeol.clean noeol_filter
git config --global filter.noeol.smudge cat

To start using the filter only for yourself, put the following line in your $GIT_DIR/info/attributes:

*.php filter=noeol

This will make sure you do not commit any newline at eof in a .php file, no matter what Vim does.

And now, the script itself:

#!/usr/bin/python

# a filter that strips newline from last line of its stdin
# if the last line is empty, leave it as-is, to make the operation idempotent
# inspired by: https://stackoverflow.com/questions/1654021/how-can-i-delete-a-newline-if-it-is-the-last-character-in-a-file/1663283#1663283

import sys

if __name__ == '__main__':
    try:
        pline = sys.stdin.next()
    except StopIteration:
        # no input, nothing to do
        sys.exit(0)

    # spit out all but the last line
    for line in sys.stdin:
        sys.stdout.write(pline)
        pline = line

    # strip newline from last line before spitting it out
    if len(pline) > 2 and pline.endswith("\r\n"):
        sys.stdout.write(pline[:-2])
    elif len(pline) > 1 and pline.endswith("\n"):
        sys.stdout.write(pline[:-1])
    else:
        sys.stdout.write(pline)

Kotlin's List missing "add", "remove", Map missing "put", etc?

You can do with create new one like this.

var list1 = ArrayList<Int>()
var list2  = list1.toMutableList()
list2.add(item)

Now you can use list2, Thank you.

How do I remove carriage returns with Ruby?

lines2 = lines.split.join("\n")

How do I disable "missing docstring" warnings at a file-level in Pylint?

I found this here.

You can add "--errors-only" flag for Pylint to disable warnings.

To do this, go to settings. Edit the following line:

"python.linting.pylintArgs": []

As

"python.linting.pylintArgs": ["--errors-only"]

And you are good to go!

Is there a better alternative than this to 'switch on type'?

This is an alternate answer that mixes contributions from JaredPar and VirtLink answers, with the following constraints:

  • The switch construction behaves as a function, and receives functions as parameters to cases.
  • Ensures that it is properly built, and there always exists a default function.
  • It returns after first match (true for JaredPar answer, not true for VirtLink one).

Usage:

 var result = 
   TSwitch<string>
     .On(val)
     .Case((string x) => "is a string")
     .Case((long x) => "is a long")
     .Default(_ => "what is it?");

Code:

public class TSwitch<TResult>
{
    class CaseInfo<T>
    {
        public Type Target { get; set; }
        public Func<object, T> Func { get; set; }
    }

    private object _source;
    private List<CaseInfo<TResult>> _cases;

    public static TSwitch<TResult> On(object source)
    {
        return new TSwitch<TResult> { 
            _source = source,
            _cases = new List<CaseInfo<TResult>>()
        };
    }

    public TResult Default(Func<object, TResult> defaultFunc)
    {
        var srcType = _source.GetType();
       foreach (var entry in _cases)
            if (entry.Target.IsAssignableFrom(srcType))
                return entry.Func(_source);

        return defaultFunc(_source);
    }

    public TSwitch<TResult> Case<TSource>(Func<TSource, TResult> func)
    {
        _cases.Add(new CaseInfo<TResult>
        {
            Func = x => func((TSource)x),
            Target = typeof(TSource)
        });
        return this;
    }
}

Using media breakpoints in Bootstrap 4-alpha

Bootstrap has a way of using media queries to define the different task for different sites. It uses four breakpoints.

we have extra small screen sizes which are less than 576 pixels that small in which I mean it's size from 576 to 768 pixels.

medium screen sizes take up screen size from 768 pixels up to 992 pixels large screen size from 992 pixels up to 1200 pixels.

E.g Small Text

This means that at the small screen between 576px and 768px, center the text For medium screen, change "sm" to "md" and same goes to large "lg"

JS: Uncaught TypeError: object is not a function (onclick)

Please change only the name of the function; no other change is required

<script>
    function totalbandwidthresult() {
        alert("fdf");
        var fps = Number(document.calculator.fps.value);
        var bitrate = Number(document.calculator.bitrate.value);
        var numberofcameras = Number(document.calculator.numberofcameras.value);
        var encoding = document.calculator.encoding.value;
        if (encoding = "mjpeg") {
            storage = bitrate * fps;
        } else {
            storage = bitrate;
        }

        totalbandwidth = (numberofcameras * storage) / 1000;
        alert(totalbandwidth);
        document.calculator.totalbandwidthresult.value = totalbandwidth;
    }
</script>

<form name="calculator" class="formtable">
    <div class="formrow">
        <label for="rcname">RC Name</label>
        <input type="text" name="rcname">
    </div>
    <div class="formrow">
        <label for="fps">FPS</label>
        <input type="text" name="fps">
    </div>
    <div class="formrow">
        <label for="bitrate">Bitrate</label>
        <input type="text" name="bitrate">
    </div>
    <div class="formrow">
        <label for="numberofcameras">Number of Cameras</label>
        <input type="text" name="numberofcameras">
    </div>
    <div class="formrow">
        <label for="encoding">Encoding</label>
        <select name="encoding" id="encodingoptions">
            <option value="h264">H.264</option>
            <option value="mjpeg">MJPEG</option>
            <option value="mpeg4">MPEG4</option>
        </select>
    </div>Total Storage:
    <input type="text" name="totalstorage">Total Bandwidth:
    <input type="text" name="totalbandwidth">
    <input type="button" value="totalbandwidthresult" onclick="totalbandwidthresult();">
</form>

How to negate specific word in regex?

Just thought of something else that could be done. It's very different from my first answer, as it doesn't use regular expressions, so I decided to make a second answer post.

Use your language of choice's split() method equivalent on the string with the word to negate as the argument for what to split on. An example using Python:

>>> text = 'barbarasdbarbar 1234egb ar bar32 sdfbaraadf'
>>> text.split('bar')
['', '', 'asd', '', ' 1234egb ar ', '32 sdf', 'aadf']

The nice thing about doing it this way, in Python at least (I don't remember if the functionality would be the same in, say, Visual Basic or Java), is that it lets you know indirectly when "bar" was repeated in the string due to the fact that the empty strings between "bar"s are included in the list of results (though the empty string at the beginning is due to there being a "bar" at the beginning of the string). If you don't want that, you can simply remove the empty strings from the list.

What is wrong with my SQL here? #1089 - Incorrect prefix key

If you are using a GUI and you are still getting the same problem. Just leave the size value empty, the primary key defaults the value to 11, you should be fine with this. Worked with Bitnami phpmyadmin.

How to remove part of a string?

Do the following

$string = 'REGISTER 11223344 here';

$content = preg_replace('/REGISTER(.*)here/','',$string);

This would return "REGISTERhere"

or

$string = 'REGISTER 11223344 here';

$content = preg_replace('/REGISTER (.*) here/','',$string);

This would return "REGISTER here"

C: How to free nodes in the linked list?

struct node{
    int position;
    char name[30];
    struct node * next;
};

void free_list(node * list){
    node* next_node;

    printf("\n\n Freeing List: \n");
    while(list != NULL)
    {
        next_node = list->next;
        printf("clear mem for: %s",list->name);
        free(list);
        list = next_node;
        printf("->");
    }
}

Get all inherited classes of an abstract class

Assuming they are all defined in the same assembly, you can do:

IEnumerable<AbstractDataExport> exporters = typeof(AbstractDataExport)
    .Assembly.GetTypes()
    .Where(t => t.IsSubclassOf(typeof(AbstractDataExport)) && !t.IsAbstract)
    .Select(t => (AbstractDataExport)Activator.CreateInstance(t));

How do you rebase the current branch's changes on top of changes being merged in?

Another way to look at it is to consider git rebase master as:

Rebase the current branch on top of master

Here , 'master' is the upstream branch, and that explain why, during a rebase, ours and theirs are reversed.

Replace whole line containing a string using Sed

cat find_replace | while read pattern replacement ; do
sed -i "/${pattern}/c ${replacement}" file    
done 

find_replace file contains 2 columns, c1 with pattern to match, c2 with replacement, the sed loop replaces each line conatining one of the pattern of variable 1

Why GDB jumps unpredictably between lines and prints variables as "<value optimized out>"?

Im using QtCreator with gdb.

Adding

QMAKE_CXXFLAGS += -O0
QMAKE_CXXFLAGS -= -O1
QMAKE_CXXFLAGS -= -O2
QMAKE_CXXFLAGS -= -O3

Works well for me

Update TextView Every Second

Use TextSwitcher (for nice text transition animation) and timer instead.

Fast query runs slow in SSRS

I came across a similar issue of my stored procedure executing quickly from Management Studio but executing very slow from SSRS. After a long struggle I solved this issue by deleting the stored procedure physically and recreating it. I am not sure of the logic behind it, but I assume it is because of the change in table structure used in the stored procedure.

horizontal scrollbar on top and bottom of table

You can use a jQuery plugin that will do the job for you :

The plugin will handle all the logic for you.

Return value from nested function in Javascript

Right. The function you pass to getLocations() won't get called until the data is available, so returning "country" before it's been set isn't going to help you.

The way you need to do this is to have the function that you pass to geocoder.getLocations() actually do whatever it is you wanted done with the returned values.

Something like this:

function reverseGeocode(latitude,longitude){
  var geocoder = new GClientGeocoder();
  var latlng = new GLatLng(latitude, longitude);

  geocoder.getLocations(latlng, function(addresses) {
    var address = addresses.Placemark[0].address;
    var country = addresses.Placemark[0].AddressDetails.Country.CountryName;
    var countrycode = addresses.Placemark[0].AddressDetails.Country.CountryNameCode;
    var locality = addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
    do_something_with_address(address, country, countrycode, locality);
  });   
}

function do_something_with_address(address, country, countrycode, locality) {
  if (country==="USA") {
     alert("USA A-OK!"); // or whatever
  }
}

If you might want to do something different every time you get the location, then pass the function as an additional parameter to reverseGeocode:

function reverseGeocode(latitude,longitude, callback){
  // Function contents the same as above, then
  callback(address, country, countrycode, locality);
}
reverseGeocode(latitude, longitude, do_something_with_address);

If this looks a little messy, then you could take a look at something like the Deferred feature in Dojo, which makes the chaining between functions a little clearer.

In c# is there a method to find the max of 3 numbers?

You could try this code:

private float GetBrightestColor(float r, float g, float b) { 
    if (r > g && r > b) {
        return r;
    } else if (g > r && g > b) { 
        return g;
    } else if (b > r && b > g) { 
        return b;
    }
}

Why is it OK to return a 'vector' from a function?

Pre C++11:

The function will not return the local variable, but rather a copy of it. Your compiler might however perform an optimization where no actual copy action is made.

See this question & answer for further details.

C++11:

The function will move the value. See this answer for further details.

Replace first occurrence of string in Python

Use re.sub directly, this allows you to specify a count:

regex.sub('', url, 1)

(Note that the order of arguments is replacement, original not the opposite, as might be suspected.)

JOptionPane Input to int

This because the input that the user inserts into the JOptionPane is a String and it is stored and returned as a String.

Java cannot convert between strings and number by itself, you have to use specific functions, just use:

int ans = Integer.parseInt(JOptionPane.showInputDialog(...))

Mocking static methods with Mockito

I had a similar issue. The accepted answer did not work for me, until I made the change: @PrepareForTest(TheClassThatContainsStaticMethod.class), according to PowerMock's documentation for mockStatic.

And I don't have to use BDDMockito.

My class:

public class SmokeRouteBuilder {
    public static String smokeMessageId() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            log.error("Exception occurred while fetching localhost address", e);
            return UUID.randomUUID().toString();
        }
    }
}

My test class:

@RunWith(PowerMockRunner.class)
@PrepareForTest(SmokeRouteBuilder.class)
public class SmokeRouteBuilderTest {
    @Test
    public void testSmokeMessageId_exception() throws UnknownHostException {
        UUID id = UUID.randomUUID();

        mockStatic(InetAddress.class);
        mockStatic(UUID.class);
        when(InetAddress.getLocalHost()).thenThrow(UnknownHostException.class);
        when(UUID.randomUUID()).thenReturn(id);

        assertEquals(id.toString(), SmokeRouteBuilder.smokeMessageId());
    }
}

Can I replace groups in Java regex?

replace the password fields from the input:

{"_csrf":["9d90c85f-ac73-4b15-ad08-ebaa3fa4a005"],"originPassword":["uaas"],"newPassword":["uaas"],"confirmPassword":["uaas"]}



  private static final Pattern PATTERN = Pattern.compile(".*?password.*?\":\\[\"(.*?)\"\\](,\"|}$)", Pattern.CASE_INSENSITIVE);

  private static String replacePassword(String input, String replacement) {
    Matcher m = PATTERN.matcher(input);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
      Matcher m2 = PATTERN.matcher(m.group(0));
      if (m2.find()) {
        StringBuilder stringBuilder = new StringBuilder(m2.group(0));
        String result = stringBuilder.replace(m2.start(1), m2.end(1), replacement).toString();
        m.appendReplacement(sb, result);
      }
    }
    m.appendTail(sb);
    return sb.toString();
  }

  @Test
  public void test1() {
    String input = "{\"_csrf\":[\"9d90c85f-ac73-4b15-ad08-ebaa3fa4a005\"],\"originPassword\":[\"123\"],\"newPassword\":[\"456\"],\"confirmPassword\":[\"456\"]}";
    String expected = "{\"_csrf\":[\"9d90c85f-ac73-4b15-ad08-ebaa3fa4a005\"],\"originPassword\":[\"**\"],\"newPassword\":[\"**\"],\"confirmPassword\":[\"**\"]}";
    Assert.assertEquals(expected, replacePassword(input, "**"));
  }

How to Upload Image file in Retrofit 2

Using Retrofit 2.0 you may use this:

@Multipart
    @POST("uploadImage")
    Call<ResponseBody> uploadImage(@Part("file\"; fileName=\"myFile.png\" ")RequestBody requestBodyFile, @Part("image") RequestBody requestBodyJson);

Make a request:

File imgFile = new File("YOUR IMAGE FILE PATH");
RequestBody requestBodyFile = RequestBody.create(MediaType.parse("image/*"), imgFile);
RequestBody requestBodyJson = RequestBody.create(MediaType.parse("text/plain"),
                    retrofitClient.getJsonObject(uploadRequest));



//make sync call
Call<ResponseBody> uploadBundle = uploadImpl.uploadImage(requestBodyFile, requestBodyJson);
Response<BaseResponse> response = uploadBundle.execute();

please refer https://square.github.io/retrofit/

500 Internal Server Error for php file not for html

I know this question is old, however I ran into this problem on Windows 8.1 while trying to use .htaccess files for rewriting. My solution was simple, I forgot to modify the following line in httpd.conf

#LoadModule rewrite_module modules/mod_rewrite.so

to

LoadModule rewrite_module modules/mod_rewrite.so

Restarted the apache monitor, now all works well. Just posting this as an answer because someone in the future may run across the same issue with a simple fix.

Good luck!

How to check if type of a variable is string?

I've seen:

hasattr(s, 'endswith') 

Populating VBA dynamic arrays

in your for loop use a Redim on the array like here:

For i = 0 to 3
  ReDim Preserve test(i)
  test(i) = 3 + i
Next i

Archive the artifacts in Jenkins

In Jenkins 2.60.3 there is a way to delete build artifacts (not the archived artifacts) in order to save hard drive space on the build machine. In the General section, check "Discard old builds" with strategy "Log Rotation" and then go into its Advanced options. Two more options will appear related to keeping build artifacts for the job based on number of days or builds.

The settings that work for me are to enter 1 for "Max # of builds to keep with artifacts" and then to have a post-build action to archive the artifacts. This way, all artifacts from all builds will be archived, all information from builds will be saved, but only the last build will keep its own artifacts.

Discard old builds options

&& (AND) and || (OR) in IF statements

Java has 5 different boolean compare operators: &, &&, |, ||, ^

& and && are "and" operators, | and || "or" operators, ^ is "xor"

The single ones will check every parameter, regardless of the values, before checking the values of the parameters. The double ones will first check the left parameter and its value and if true (||) or false (&&) leave the second one untouched. Sound compilcated? An easy example should make it clear:

Given for all examples:

 String aString = null;

AND:

 if (aString != null & aString.equals("lala"))

Both parameters are checked before the evaluation is done and a NullPointerException will be thrown for the second parameter.

 if (aString != null && aString.equals("lala"))

The first parameter is checked and it returns false, so the second paramter won't be checked, because the result is false anyway.

The same for OR:

 if (aString == null | !aString.equals("lala"))

Will raise NullPointerException, too.

 if (aString == null || !aString.equals("lala"))

The first parameter is checked and it returns true, so the second paramter won't be checked, because the result is true anyway.

XOR can't be optimized, because it depends on both parameters.

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

Just make Constructor of your mapping in your base class. Like if you want One-To-One relation in Entity A, Entity B. if your are taking A as base class, then A must have a Constructor have B as a argument.

Installation of SQL Server Business Intelligence Development Studio

If you have installed SQL 2005 express edition and want to install BIDS (Business Intelligence Development Studio) then go to here Microsoft SQL Server 2005 Express Edition Toolkit

This has an option to install BIDS on my machine, and is the only way l could get hold of BIDS for SQL Server 2005 express edition.

Also this package l think has also allowed me to install both BIDS 2005 & 2008 express edition on the same machine.

Application not picking up .css file (flask/python)

I'm running version 1.0.2 of flask right now. The above file structures did not work for me, but I found one that did, which are as follows:

     app_folder/ flask_app.py/ static/ style.css/ templates/
     index.html

(Please note that 'static' and 'templates' are folders, which should be named exactly the same thing.)

To check what version of flask you are running, you should open Python in terminal and type the following accordingly:

import flask

flask --version

Removing an element from an Array (Java)

Copy your original array into another array, without the element to be removed.

A simplier way to do that is to use a List, Set... and use the remove() method.

Javascript to Select Multiple options

A pure javascript solution

<select id="choice" multiple="multiple">
  <option value="1">One</option>
  <option value="2">two</option>
  <option value="3">three</option>
</select>
<script type="text/javascript">

var optionsToSelect = ['One', 'three'];
var select = document.getElementById( 'choice' );

for ( var i = 0, l = select.options.length, o; i < l; i++ )
{
  o = select.options[i];
  if ( optionsToSelect.indexOf( o.text ) != -1 )
  {
    o.selected = true;
  }
}

</script>

Although I agree this should be done server-side.

How can I save a screenshot directly to a file in Windows?

Of course you could write a program that monitors the clipboard and displays an annoying SaveAs-dialog for every image in the clipboard ;-). I guess you can even find out if the last key pressed was PrintScreen to limit the number of false positives.

While I'm thinking about it.. you could also google for someone who already did exactly that.


EDIT: .. or just wait for someone to post the source here - as just happend :-)

Basic example of using .ajax() with JSONP?

JSONP is really a simply trick to overcome XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)

So - instead of using XMLHttpRequest we have to use script HTMLl tags, the ones you usually use to load JS files, in order for JS to get data from another domain. Sounds weird?

Thing is - turns out script tags can be used in a fashion similar to XMLHttpRequest! Check this out:

script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data";

You will end up with a script segment that looks like this after it loads the data:

<script>
{['some string 1', 'some data', 'whatever data']}
</script>

However this is a bit inconvenient, because we have to fetch this array from script tag. So JSONP creators decided that this will work better (and it is):

script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data?callback=my_callback";

Notice my_callback function over there? So - when JSONP server receives your request and finds callback parameter - instead of returning plain JS array it'll return this:

my_callback({['some string 1', 'some data', 'whatever data']});

See where the profit is: now we get automatic callback (my_callback) that'll be triggered once we get the data. That's all there is to know about JSONP: it's a callback and script tags.


NOTE:
These are simple examples of JSONP usage, these are not production ready scripts.

RAW JavaScript demonstration (simple Twitter feed using JSONP):

<html>
    <head>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
        <script>
        function myCallback(dataWeGotViaJsonp){
            var text = '';
            var len = dataWeGotViaJsonp.length;
            for(var i=0;i<len;i++){
                twitterEntry = dataWeGotViaJsonp[i];
                text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
            }
            document.getElementById('twitterFeed').innerHTML = text;
        }
        </script>
        <script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script>
    </body>
</html>


Basic jQuery example (simple Twitter feed using JSONP):

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $.ajax({
                    url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
                    dataType: 'jsonp',
                    success: function(dataWeGotViaJsonp){
                        var text = '';
                        var len = dataWeGotViaJsonp.length;
                        for(var i=0;i<len;i++){
                            twitterEntry = dataWeGotViaJsonp[i];
                            text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
                        }
                        $('#twitterFeed').html(text);
                    }
                });
            })
        </script>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
    </body>
</html>


JSONP stands for JSON with Padding. (very poorly named technique as it really has nothing to do with what most people would think of as “padding”.)

WordPress path url in js script file

For users working with the Genesis framework.

Add the following to your child theme functions.php

add_action( 'genesis_before', 'script_urls' );

function script_urls() {
?>
    <script type="text/javascript">
     var stylesheetDir = '<?= get_bloginfo("stylesheet_directory"); ?>';
    </script>
<?php
}

And use that variable to set the relative url in your script. For example:

Reset.style.background = " url('"+stylesheetDir+"/images/searchfield_clear.png') ";

git clone from another directory

None of these worked for me. I am using git-bash on windows. Found out the problem was with my file path formatting.

WRONG:

git clone F:\DEV\MY_REPO\.git

CORRECT:

git clone /F/DEV/MY_REPO/.git

These commands are done from the folder you want the repo folder to appear in.

How do I jump to a closing bracket in Visual Studio Code?

Command "editor.action.jumpToBracket" jumps between opening and closing brackets.

Here is the command's default key binding as seen in window Default Keyboard Shortcuts accessed from File | Preferences | Keyboard Shortcuts:

{ "key": "ctrl+shift+\\", "command": "editor.action.jumpToBracket",
                             "when": "editorTextFocus" }

If you're fond of quickly configuring keyboard shortcuts and VS Code settings, there are commands "workbench.action.openGlobalKeybindings" and "workbench.action.openGlobalSettings":

~/.config/Code/User/keybindings.json:

{ "key": "ctrl+numpad4", "command": "workbench.action.openGlobalKeybindings" }
{ "key": "ctrl+numpad1", "command": "workbench.action.openGlobalSettings" }

Android: making a fullscreen application

According to this document, add the following code to onCreate

getWindow().getDecorView().setSystemUiVisibility(SYSTEM_UI_FLAG_IMMERSIVE_STICKY |
        SYSTEM_UI_FLAG_FULLSCREEN | SYSTEM_UI_FLAG_HIDE_NAVIGATION   | 
        SYSTEM_UI_FLAG_LAYOUT_STABLE | SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

How to make HTTP Post request with JSON body in Swift

func fucntion()
{

    var parameters = [String:String]()
    let apiToken = "Bearer \(ApiUtillity.sharedInstance.getUserData(key: "vAuthToken"))"
    let headers = ["Vauthtoken":apiToken]

    parameters = ["firstname":name,"lastname":last_name,"mobile":mobile_number,"email":emails_Address]


    Alamofire.request(ApiUtillity.sharedInstance.API(Join: "user/edit_profile"), method: .post, parameters: parameters, encoding: URLEncoding.default,headers:headers).responseJSON { response in
        debugPrint(response)
        if let json = response.result.value {
            let dict:NSDictionary = (json as? NSDictionary)!
            print(dict)
            //                print(response)

            let StatusCode = dict.value(forKey: "status") as! Int

            if StatusCode==200
            {
                ApiUtillity.sharedInstance.dismissSVProgressHUDWithSuccess(success: "Success")
                let UserData = dict.value(forKey: "data") as! NSDictionary
                print(UserData)

            }

            else if StatusCode==401
            {
                let ErrorDic:NSDictionary = dict.value(forKey: "message") as! NSDictionary
                let ErrorMessage = ErrorDic.value(forKey: "error") as! String

            }
            else
            {

                let ErrorDic:NSDictionary = dict.value(forKey: "message") as! NSDictionary
                let ErrorMessage = ErrorDic.value(forKey: "error") as! String
            }

        }
        else
        {
            ApiUtillity.sharedInstance.dismissSVProgressHUDWithError(error: "Something went wrong")
        }
    }

What's the simplest way to extend a numpy array in 2 dimensions?

A useful alternative answer to the first question, using the examples from tomeedee’s answer, would be to use numpy’s vstack and column_stack methods:

Given a matrix p,

>>> import numpy as np
>>> p = np.array([ [1,2] , [3,4] ])

an augmented matrix can be generated by:

>>> p = np.vstack( [ p , [5 , 6] ] )
>>> p = np.column_stack( [ p , [ 7 , 8 , 9 ] ] )
>>> p
array([[1, 2, 7],
       [3, 4, 8],
       [5, 6, 9]])

These methods may be convenient in practice than np.append() as they allow 1D arrays to be appended to a matrix without any modification, in contrast to the following scenario:

>>> p = np.array([ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] ] )
>>> p = np.append( p , [ 7 , 8 , 9 ] , 1 )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/dist-packages/numpy/lib/function_base.py", line 3234, in append
    return concatenate((arr, values), axis=axis)
ValueError: arrays must have same number of dimensions

In answer to the second question, a nice way to remove rows and columns is to use logical array indexing as follows:

Given a matrix p,

>>> p = np.arange( 20 ).reshape( ( 4 , 5 ) )

suppose we want to remove row 1 and column 2:

>>> r , c = 1 , 2
>>> p = p [ np.arange( p.shape[0] ) != r , : ] 
>>> p = p [ : , np.arange( p.shape[1] ) != c ]
>>> p
array([[ 0,  1,  3,  4],
       [10, 11, 13, 14],
       [15, 16, 18, 19]])

Note - for reformed Matlab users - if you wanted to do these in a one-liner you need to index twice:

>>> p = np.arange( 20 ).reshape( ( 4 , 5 ) )    
>>> p = p [ np.arange( p.shape[0] ) != r , : ] [ : , np.arange( p.shape[1] ) != c ]

This technique can also be extended to remove sets of rows and columns, so if we wanted to remove rows 0 & 2 and columns 1, 2 & 3 we could use numpy's setdiff1d function to generate the desired logical index:

>>> p = np.arange( 20 ).reshape( ( 4 , 5 ) )
>>> r = [ 0 , 2 ]
>>> c = [ 1 , 2 , 3 ]
>>> p = p [ np.setdiff1d( np.arange( p.shape[0] ), r ) , : ] 
>>> p = p [ : , np.setdiff1d( np.arange( p.shape[1] ) , c ) ]
>>> p
array([[ 5,  9],
       [15, 19]])

How to decode encrypted wordpress admin password?

MD5 encrypting is possible, but decrypting is still unknown (to me). However, there are many ways to compare these things.

  1. Using compare methods like so:

    <?php
      $db_pass = $P$BX5675uhhghfhgfhfhfgftut/0;
      $my_pass = "mypass";
      if ($db_pass === md5($my_pass)) {
        // password is matched
      } else {
        // password didn't match
      }
    
  2. Only for WordPress users. If you have access to your PHPMyAdmin, focus you have because you paste that hashing here: $P$BX5675uhhghfhgfhfhfgftut/0, WordPress user_pass is not only MD5 format it also uses utf8_mb4_cli charset so what to do?

    That's why I use another Approach if I forget my WordPress password I use

    I install other WordPress with new password :P, and I then go to PHPMyAdmin and copy that hashing from the database and paste that hashing to my current PHPMyAdmin password ( which I forget )

    EASY is use this :

    1. password = "ARJUNsingh@123"
    2. password_hasing = " $P$BDSdKx2nglM.5UErwjQGeVtVWvjEvD1 "
    3. Replace your $P$BX5675uhhghfhgfhfhfgftut/0 with my $P$BDSdKx2nglM.5UErwjQGeVtVWvjEvD1

I USE THIS APPROACH FOR MY SELF WHEN I DESIGN THEMES AND PLUGINS

WORDPRESS USE THIS

https://developer.wordpress.org/reference/functions/wp_hash_password/

Laravel 5 Carbon format datetime

$suborder['payment_date'] = Carbon::parse($item['created_at'])->format('M d Y');

Use JSTL forEach loop's varStatus as an ID

you'd use any of these:

JSTL c:forEach varStatus properties

Property Getter Description

  • current getCurrent() The item (from the collection) for the current round of iteration.

  • index getIndex() The zero-based index for the current round of iteration.

  • count getCount() The one-based count for the current round of iteration

  • first isFirst() Flag indicating whether the current round is the first pass through the iteration
  • last isLast() Flag indicating whether the current round is the last pass through the iteration

  • begin getBegin() The value of the begin attribute

  • end getEnd() The value of the end attribute

  • step getStep() The value of the step attribute

Javascript string replace with regex to strip off illegal characters

What you need are character classes. In that, you've only to worry about the ], \ and - characters (and ^ if you're placing it straight after the beginning of the character class "[" ).

Syntax: [characters] where characters is a list with characters.

Example:

var cleanString = dirtyString.replace(/[|&;$%@"<>()+,]/g, "");

Days between two dates?

Assuming you’ve literally got two date objects, you can subtract one from the other and query the resulting timedelta object for the number of days:

>>> from datetime import date
>>> a = date(2011,11,24)
>>> b = date(2011,11,17)
>>> a-b
datetime.timedelta(7)
>>> (a-b).days
7

And it works with datetimes too — I think it rounds down to the nearest day:

>>> from datetime import datetime
>>> a = datetime(2011,11,24,0,0,0)
>>> b = datetime(2011,11,17,23,59,59)
>>> a-b
datetime.timedelta(6, 1)
>>> (a-b).days
6

Access restriction: Is not accessible due to restriction on required library ..\jre\lib\rt.jar

I'm responding to this question because I had a different way of fixing this problem than the other answers had. I had this problem when I refactored the name of the plugins that I was exporting. Eventually I had to make sure to fix/change the following.

  1. The product file's dependencies,
  2. The plugin.xml dependencies (and make sure it is not implicitly imported using the imported packages dialog).
  3. The run configuration plug-ins tab. Run As..->Run Configurations->Plug-ins tab. Uncheck the old plugins and then click Add Required Plug-ins.

This worked for me, but your mileage may vary.

Android Studio Rendering Problems : The following classes could not be found

I had to change my values/styles.xml to

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">

Before that change, it was without 'Base'.

(IntelliJ IDEA 2017.2.4)

Change button text from Xcode?

UIButton *myButton;

[myButton setTitle:@"My Title" forState:UIControlStateNormal];
[myButton setTitle:@"My Selected Title" forState:UIControlStateSelected];

What does <![CDATA[]]> in XML mean?

I once had to use CDATA when my xml element needed to store HTML code. Something like

<codearea>
  <![CDATA[ 
  <div> <p> my para </p> </div> 
  ]]>
</codearea>

So CDATA means it will ignore any character which could otherwise be interpreted as XML tag like < and > etc.

How to convert HTML file to word?

Try using pandoc

pandoc -f html -t docx -o output.docx input.html

If the input or output format is not specified explicitly, pandoc will attempt to guess it from the extensions of the input and output filenames.
— pandoc manual

So you can even use

pandoc -o output.docx input.html

UIImage: Resize, then Crop

scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0,0.0,ScreenWidth,ScreenHeigth)];
    [scrollView setBackgroundColor:[UIColor blackColor]];
    [scrollView setDelegate:self];
    [scrollView setShowsHorizontalScrollIndicator:NO];
    [scrollView setShowsVerticalScrollIndicator:NO];
    [scrollView setMaximumZoomScale:2.0];
    image=[image scaleToSize:CGSizeMake(ScreenWidth, ScreenHeigth)];
    imageView = [[UIImageView alloc] initWithImage:image];
    UIImageView* imageViewBk = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.png"]];
    [self.view addSubview:imageViewBk];
    CGRect rect;
    rect.origin.x=0;
    rect.origin.y=0;
    rect.size.width = image.size.width;
    rect.size.height = image.size.height;

    [imageView setFrame:rect];

    [scrollView setContentSize:[imageView frame].size];
    [scrollView setMinimumZoomScale:[scrollView frame].size.width / [imageView frame].size.width];
    [scrollView setZoomScale:[scrollView minimumZoomScale]];
    [scrollView addSubview:imageView];

    [[self view] addSubview:scrollView];

then you can take screen shots to your image by this

float zoomScale = 1.0 / [scrollView zoomScale];
CGRect rect;
rect.origin.x = [scrollView contentOffset].x * zoomScale;
rect.origin.y = [scrollView contentOffset].y * zoomScale;
rect.size.width = [scrollView bounds].size.width * zoomScale;
rect.size.height = [scrollView bounds].size.height * zoomScale;

CGImageRef cr = CGImageCreateWithImageInRect([[imageView image] CGImage], rect);

UIImage *cropped = [UIImage imageWithCGImage:cr];

CGImageRelease(cr);

How to clear all <div>s’ contents inside a parent <div>?

jQuery's empty() function does just that:

$('#masterdiv').empty();

clears the master div.

$('#masterdiv div').empty();

clears all the child divs, but leaves the master intact.

How to send only one UDP packet with netcat?

If you are using bash, you might as well write

echo -n "hello" >/dev/udp/localhost/8000

and avoid all the idiosyncrasies and incompatibilities of netcat.

This also works sending to other hosts, ex:

echo -n "hello" >/dev/udp/remotehost/8000

These are not "real" devices on the file system, but bash "special" aliases. There is additional information in the Bash Manual.

How to insert a character in a string at a certain position?

If you are using a system where float is expensive (e.g. no FPU) or not allowed (e.g. in accounting) you could use something like this:

    for (int i = 1; i < 100000; i *= 2) {
        String s = "00" + i;
        System.out.println(s.substring(Math.min(2, s.length() - 2), s.length() - 2) + "." + s.substring(s.length() - 2));
    }

Otherwise the DecimalFormat is the better solution. (the StringBuilder variant above won't work with small numbers (<100)

How to force composer to reinstall a library?

Reinstall the dependencies. Remove the vendor folder (manually) or via rm command (if you are in the project folder, sure) on Linux before:

rm -rf vendor/

composer update -v

https://www.dev-metal.com/composer-problems-try-full-reset/

Git - deleted some files locally, how do I get them from a remote repository

git checkout filename

git reset --hard might do the trick as well

Syntax of for-loop in SQL Server

Try it, learn it:

DECLARE @r INT = 5
DECLARE @i INT = 0
DECLARE @F varchar(max) = ''
WHILE @i < @r
BEGIN

    DECLARE @j INT = 0
    DECLARE @o varchar(max) = ''
    WHILE @j < @r - @i - 1
    BEGIN
        SET @o = @o + ' '
        SET @j += 1
    END

    DECLARE @k INT = 0
    WHILE @k < @i + 1
    BEGIN
        SET @o = @o + ' *'  -- '*'
        SET @k += 1
    END
    SET @i += 1
    SET @F = @F + @o + CHAR(13)
END
PRINT @F

With date:

DECLARE @d DATE = '2019-11-01'
WHILE @d < GETDATE()
BEGIN
    PRINT @d
    SET @d = DATEADD(DAY,1,@d)
END
PRINT 'n'
PRINT @d

Get PHP class property by string

It is simple, $obj->{$obj->Name} the curly brackets will wrap the property much like a variable variable.

This was a top search. But did not resolve my question, which was using $this. In the case of my circumstance using the curly bracket also helped...

example with Code Igniter get instance

in an sourced library class called something with a parent class instance

$this->someClass='something';
$this->someID=34;

the library class needing to source from another class also with the parents instance

echo $this->CI->{$this->someClass}->{$this->someID};

Get the Year/Month/Day from a datetime in php?

Use DateTime with DateTime::format()

$datetime = new DateTime($dateTimeString);
echo $datetime->format('w');

ERROR 2003 (HY000): Can't connect to MySQL server on localhost (10061)

i also face the same problem. try it

  1. Go to bin directory copy the path and set it as a environment variable.
  2. Run the command prompt as admin and cd to bin directory:
  3. Run command : mysqld –install
  4. Now the services are successfully installed
  5. Start the service in service windows of os
  6. Type mysql and go

How to save a Python interactive session?

There is %history magic for printing and saving the input history (and optionally the output).

To store your current session to a file named my_history.py:

>>> %hist -f my_history.py

History IPython stores both the commands you enter, and the results it produces. You can easily go through previous commands with the up- and down-arrow keys, or access your history in more sophisticated ways.

You can use the %history magic function to examine past input and output. Input history from previous sessions is saved in a database, and IPython can be configured to save output history.

Several other magic functions can use your input history, including %edit, %rerun, %recall, %macro, %save and %pastebin. You can use a standard format to refer to lines:

%pastebin 3 18-20 ~1/1-5

This will take line 3 and lines 18 to 20 from the current session, and lines 1-5 from the previous session.

See %history? for the Docstring and more examples.

Also, be sure to explore the capabilities of %store magic for lightweight persistence of variables in IPython.

Stores variables, aliases and macros in IPython’s database.

d = {'a': 1, 'b': 2}
%store d  # stores the variable
del d

%store -r d  # Refresh the variable from IPython's database.
>>> d
{'a': 1, 'b': 2}

To autorestore stored variables on startup, specifyc.StoreMagic.autorestore = True in ipython_config.py.

MySQL Sum() multiple columns

The short answer is there's no great way to do this given the design you have. Here's a related question on the topic: Sum values of a single row?

If you normalized your schema and created a separate table called "Marks" which had a subject_id and a mark column this would allow you to take advantage of the SUM function as intended by a relational model.

Then your query would be

SELECT subject, SUM(mark) total 
FROM Subjects s 
  INNER JOIN Marks m ON m.subject_id = s.id
GROUP BY s.id

How to check string length with JavaScript

That's the function I wrote to get string in Unicode characters:

function nbUnicodeLength(string){
    var stringIndex = 0;
    var unicodeIndex = 0;
    var length = string.length;
    var second;
    var first;
    while (stringIndex < length) {

        first = string.charCodeAt(stringIndex);  // returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.
        if (first >= 0xD800 && first <= 0xDBFF && string.length > stringIndex + 1) {
            second = string.charCodeAt(stringIndex + 1);
            if (second >= 0xDC00 && second <= 0xDFFF) {
                stringIndex += 2;
            } else {
                stringIndex += 1;
            }
        } else {
            stringIndex += 1;
        }

        unicodeIndex += 1;
    }
    return unicodeIndex;
}

@viewChild not working - cannot read property nativeElement of undefined

Initializing the Canvas like below works for TypeScript/Angular solutions.

const canvas = <HTMLCanvasElement> document.getElementById("htmlElemId"); 

const context = canvas.getContext("2d"); 

In Perl, how do I create a hash whose keys come from a given array?

%hash = map { $_ => 1 } @array;

It's not as short as the "@hash{@array} = ..." solutions, but those ones require the hash and array to already be defined somewhere else, whereas this one can take an anonymous array and return an anonymous hash.

What this does is take each element in the array and pair it up with a "1". When this list of (key, 1, key, 1, key 1) pairs get assigned to a hash, the odd-numbered ones become the hash's keys, and the even-numbered ones become the respective values.

Where can I download Eclipse Android bundle?

Google has ended support for eclipse plugin. If you prefer to use eclipse still you can download Eclipse Android Development Tool from

ADT for Eclipse

Adb Devices can't find my phone

I have a Fascinate as well, and had to change the phone's USB communication mode from MODEM to PDA. Use:

  • enter **USBUI (**87284)

to change both USB and UART to PDA mode. I also had to disconnect and reconnect the USB cable. Once Windows re-recognized the device again, "adb devices" started returning my device.

BTW if you use CDMA workshop or the equivalent, you will need to switch the setting back to MODEM.

Unicode character as bullet for list-item in CSS

Using Text As Bullets

Use li:before with an escaped Hex HTML Entity (or any plain text).


Example

My example will produce lists with check marks as bullets.

CSS:

ul {
    list-style: none;
    padding: 0px;
}

ul li:before
{
    content: '\2713';
    margin: 0 1em;    /* any design */
}

Browser Compatibility

Haven't tested myself, but it should be supported as of IE8. At least that's what quirksmode & css-tricks say.

You can use conditional comments to apply older/slower solutions like images, or scripts. Better yet, use both with <noscript> for the images.

HTML:

<!--[if lt IE 8]>
    *SCRIPT SOLUTION*
    <noscript>
        *IMAGE SOLUTION*
    </noscript>
<![endif]-->

About background images

Background images are indeed easy to handle, but...

  1. Browser support for background-size is actually only as of IE9.
  2. HTML text colors and special (crazy) fonts can do a lot, with less HTTP requests.
  3. A script solution can just inject the HTML Entity, and let the same CSS do the work.
  4. A good resetting CSS code might make list-style (the more logical choice) easier.

Enjoy.

Python integer division yields float

The accepted answer already mentions PEP 238. I just want to add a quick look behind the scenes for those interested in what's going on without reading the whole PEP.

Python maps operators like +, -, * and / to special functions, such that e.g. a + b is equivalent to

a.__add__(b)

Regarding division in Python 2, there is by default only / which maps to __div__ and the result is dependent on the input types (e.g. int, float).

Python 2.2 introduced the __future__ feature division, which changed the division semantics the following way (TL;DR of PEP 238):

  • / maps to __truediv__ which must "return a reasonable approximation of the mathematical result of the division" (quote from PEP 238)
  • // maps to __floordiv__, which should return the floored result of /

With Python 3.0, the changes of PEP 238 became the default behaviour and there is no more special method __div__ in Python's object model.

If you want to use the same code in Python 2 and Python 3 use

from __future__ import division

and stick to the PEP 238 semantics of / and //.

How do you remove the title text from the Android ActionBar?

I am new to Android so maybe I am wrong...but to solve this problem cant we just go to the manifest and remove the activity label

<activity
        android:name=".Bcft"
        android:screenOrientation="portrait"

        **android:label="" >**

Worked for me....

Disable vertical sync for glxgears

For Intel graphics and AMD/ATI opensource graphics drivers

Find the "Device" section of /etc/X11/xorg.conf which contains one of the following directives:

  • Driver "intel"
  • Driver "radeon"
  • Driver "fglrx"

And add the following line to that section:

Option     "SwapbuffersWait"       "false"

And run your application with vblank_mode environment variable set to 0:

$ vblank_mode=0 glxgears

For Nvidia graphics with the proprietary Nvidia driver

$ echo "0/SyncToVBlank=0" >> ~/.nvidia-settings-rc

The same change can be made in the nvidia-settings GUI by unchecking the option at X Screen 0 / OpenGL Settings / Sync to VBlank. Or, if you'd like to just test the setting without modifying your ~/.nvidia-settings-rc file you can do something like:

$ nvidia-settings --load-config-only --assign="SyncToVBlank=0"  # disable vertical sync
$ glxgears  # test it out
$ nvidia-settings --load-config-only  # restore your original vertical sync setting

How to Populate a DataTable from a Stored Procedure

You can use a SqlDataAdapter:

    SqlDataAdapter adapter = new SqlDataAdapter();
    SqlCommand cmd = new SqlCommand("usp_GetABCD", sqlcon);
    cmd.CommandType = CommandType.StoredProcedure;
    adapter.SelectCommand = cmd;
    DataTable dt = new DataTable();
    adapter.Fill(dt);

Iterate over array of objects in Typescript

You can use the built-in forEach function for arrays.

Like this:

//this sets all product descriptions to a max length of 10 characters
data.products.forEach( (element) => {
    element.product_desc = element.product_desc.substring(0,10);
});

Your version wasn't wrong though. It should look more like this:

for(let i=0; i<data.products.length; i++){
    console.log(data.products[i].product_desc); //use i instead of 0
}

Stored Procedure error ORA-06550

create or replace procedure point_triangle
AS
BEGIN
FOR thisteam in (select FIRSTNAME,LASTNAME,SUM(PTS)  from PLAYERREGULARSEASON  where TEAM    = 'IND' group by FIRSTNAME, LASTNAME order by SUM(PTS) DESC)

LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.PTS);
END LOOP;

END;
/

UnicodeDecodeError when reading CSV file in Pandas with Python

In my case, a file has USC-2 LE BOM encoding, according to Notepad++. It is encoding="utf_16_le" for python.

Hope, it helps to find an answer a bit faster for someone.

Is it possible to have a custom facebook like button?

It's possible with a lot of work.

Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.

But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.

Plus, you'll need to ask user to log into your app and ask them the publish_action permission.

All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.

Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.

If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it

MySQL "Or" Condition

Your question is about the operator precedences in mysql and Alex has shown you how to "override" the precedence with parentheses.

But on a side note, if your column date is of the type Date you can use MySQL's date and time functions to fetch the records of the last seven days, like e.g.

SELECT
  *
FROM
  Drinks
WHERE
  email='$Email'
  AND date >= Now()-Interval 7 day

(or maybe Curdate() instead of Now())

Substring in excel

I believe we can start from basic to achieve desired result.

For example, I had a situation to extract data after "/". The given excel field had a value of 2rko6xyda14gdl7/VEERABABU%20MATCHA%20IN131621.jpg . I simply wanted to extract the text from "I5" cell after slash symbol. So firstly I want to find where "/" symbol is (FIND("/",I5). This gives me the position of "/". Then I should know the length of text, which i can get by LEN(I5).so total length minus the position of "/" . which is LEN(I5)-(FIND("/",I5)) . This will first find the "/" position and then get me the total text that needs to be extracted. The RIGHT function is RIGHT(I5,12) will simply extract all the values of last 12 digits starting from right most character. So I will replace the above function "LEN(I5)-(FIND("/",I5))" for 12 number in the RIGHT function to get me dynamically the number of characters I need to extract in any given cell and my solution is presented as given below

The approach was

=RIGHT(I5,LEN(I5)-(FIND("/",I5))) will give me out as VEERABABU%20MATCHA%20IN131621.jpg . I think I am clear.

How can I check if a user is logged-in in php?

You need this on all pages before you check for current sessions:

session_start();

Check if $_SESSION["loggedIn"] (is not) true - If not, redirect them to the login page.

if($_SESSION["loggedIn"] != true){
    echo 'not logged in';
    header("Location: login.php");
    exit;
}

pthread_join() and pthread_exit()

The typical use is

void* ret = NULL;
pthread_t tid = something; /// change it suitably
if (pthread_join (tid, &ret)) 
   handle_error();
// do something with the return value ret

Difference between getAttribute() and getParameter()

getParameter - Is used for getting the information you need from the Client's HTML page

getAttribute - This is used for getting the parameters set previously in another or the same JSP or Servlet page.

Basically, if you are forwarding or just going from one jsp/servlet to another one, there is no way to have the information you want unless you choose to put them in an Object and use the set-attribute to store in a Session variable.

Using getAttribute, you can retrieve the Session variable.

Check if key exists and iterate the JSON array using Python

import json

jsonData = """{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}]}, "type": "status", "id": "id_7"}"""

def getTargetIds(jsonData):
    data = json.loads(jsonData)
    if 'to' not in data:
        raise ValueError("No target in given data")
    if 'data' not in data['to']:
        raise ValueError("No data for target")

    for dest in data['to']['data']:
        if 'id' not in dest:
            continue
        targetId = dest['id']
        print("to_id:", targetId)

Output:

In [9]: getTargetIds(s)
to_id: 1543

Set CSS property in Javascript?

<body>
  <h1 id="h1">Silence and Smile</h1><br />
  <h3 id="h3">Silence and Smile</h3>

  <script type="text/javascript">
    document.getElementById("h1").style.color = "Red";
    document.getElementById("h1").style.background = "Green";
    document.getElementById("h3").style.fontSize = "larger" ; 
    document.getElementById("h3").style.fontFamily = "Arial";
  </script>
</body>

How to check for Is not Null And Is not Empty string in SQL server?

If you only want to match "" as an empty string

WHERE DATALENGTH(COLUMN) > 0 

If you want to count any string consisting entirely of spaces as empty

WHERE COLUMN <> '' 

Both of these will not return NULL values when used in a WHERE clause. As NULL will evaluate as UNKNOWN for these rather than TRUE.

CREATE TABLE T 
  ( 
     C VARCHAR(10) 
  ); 

INSERT INTO T 
VALUES      ('A'), 
            (''),
            ('    '), 
            (NULL); 

SELECT * 
FROM   T 
WHERE  C <> ''

Returns just the single row A. I.e. The rows with NULL or an empty string or a string consisting entirely of spaces are all excluded by this query.

SQL Fiddle

How to set timeout in Retrofit library?

I found this example

https://github.com/square/retrofit/issues/1557

Here we set custom url client connection client before before we build API rest service implementation.

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import retrofit.Endpoint
import retrofit.RestAdapter
import retrofit.client.Request
import retrofit.client.UrlConnectionClient
import retrofit.converter.GsonConverter


class ClientBuilder {

    public static <T> T buildClient(final Class<T> client, final String serviceUrl) {
        Endpoint mCustomRetrofitEndpoint = new CustomRetrofitEndpoint()


        Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
        RestAdapter.Builder builder = new RestAdapter.Builder()
            .setEndpoint(mCustomRetrofitEndpoint)
            .setConverter(new GsonConverter(gson))
            .setClient(new MyUrlConnectionClient())
        RestAdapter restAdapter = builder.build()
        return restAdapter.create(client)
    }
}

 public final class MyUrlConnectionClient extends UrlConnectionClient {
        @Override
        protected HttpURLConnection openConnection(Request request) {
            HttpURLConnection connection = super.openConnection(request);
            connection.setConnectTimeout(15 * 1000);
            connection.setReadTimeout(30 * 1000);
            return connection;
        }
    }

How to find the day, month and year with moment.js

I know this has already been answered, but I stumbled across this question and went down the path of using format, which works, but it returns them as strings when I wanted integers.

I just realized that moment comes with date, month and year methods that return the actual integers for each method.

moment().date()
moment().month()  // jan=0, dec=11
moment().year()

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

Using Visual Studio 2015 adding the additional parameter

/deployonbuild=false

to the msbuild command line fixed the issue.

Http 415 Unsupported Media type error with JSON

If you are making jquery ajax request, dont forget to add

contentType:'application/json'

Sorting an ArrayList of objects using a custom sorting order

use this method:

private ArrayList<myClass> sortList(ArrayList<myClass> list) {
    if (list != null && list.size() > 1) {
        Collections.sort(list, new Comparator<myClass>() {
            public int compare(myClass o1, myClass o2) {
                if (o1.getsortnumber() == o2.getsortnumber()) return 0;
                return o1.getsortnumber() < o2.getsortnumber() ? 1 : -1;
            }
        });
    }
    return list;
}

`

and use: mySortedlist = sortList(myList); No need to implement comparator in your class. If you want inverse order swap 1 and -1

How to create a custom-shaped bitmap marker with Android map API v2

I hope it still not too late to share my solution. Before that, you can follow the tutorial as stated in Android Developer documentation. To achieve this, you need to use Cluster Manager with defaultRenderer.

  1. Create an object that implements ClusterItem

    public class SampleJob implements ClusterItem {
    
    private double latitude;
    private double longitude;
    
    //Create constructor, getter and setter here
    
    @Override
    public LatLng getPosition() {
        return new LatLng(latitude, longitude);
    }
    
  2. Create a default renderer class. This is the class that do all the job (inflating custom marker/cluster with your own style). I am using Universal image loader to do the downloading and caching the image.

    public class JobRenderer extends DefaultClusterRenderer< SampleJob > {
    
    private final IconGenerator iconGenerator;
    private final IconGenerator clusterIconGenerator;
    private final ImageView imageView;
    private final ImageView clusterImageView;
    private final int markerWidth;
    private final int markerHeight;
    private final String TAG = "ClusterRenderer";
    private DisplayImageOptions options;
    
    
    public JobRenderer(Context context, GoogleMap map, ClusterManager<SampleJob> clusterManager) {
        super(context, map, clusterManager);
    
        // initialize cluster icon generator
        clusterIconGenerator = new IconGenerator(context.getApplicationContext());
        View clusterView = LayoutInflater.from(context).inflate(R.layout.multi_profile, null);
        clusterIconGenerator.setContentView(clusterView);
        clusterImageView = (ImageView) clusterView.findViewById(R.id.image);
    
        // initialize cluster item icon generator
        iconGenerator = new IconGenerator(context.getApplicationContext());
        imageView = new ImageView(context.getApplicationContext());
        markerWidth = (int) context.getResources().getDimension(R.dimen.custom_profile_image);
        markerHeight = (int) context.getResources().getDimension(R.dimen.custom_profile_image);
        imageView.setLayoutParams(new ViewGroup.LayoutParams(markerWidth, markerHeight));
        int padding = (int) context.getResources().getDimension(R.dimen.custom_profile_padding);
        imageView.setPadding(padding, padding, padding, padding);
        iconGenerator.setContentView(imageView);
    
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.circle_icon_logo)
                .showImageForEmptyUri(R.drawable.circle_icon_logo)
                .showImageOnFail(R.drawable.circle_icon_logo)
                .cacheInMemory(false)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
    }
    
    @Override
    protected void onBeforeClusterItemRendered(SampleJob job, MarkerOptions markerOptions) {
    
    
        ImageLoader.getInstance().displayImage(job.getJobImageURL(), imageView, options);
        Bitmap icon = iconGenerator.makeIcon(job.getName());
        markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon)).title(job.getName());
    
    
    }
    
    @Override
    protected void onBeforeClusterRendered(Cluster<SampleJob> cluster, MarkerOptions markerOptions) {
    
        Iterator<Job> iterator = cluster.getItems().iterator();
        ImageLoader.getInstance().displayImage(iterator.next().getJobImageURL(), clusterImageView, options);
        Bitmap icon = clusterIconGenerator.makeIcon(iterator.next().getName());
        markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
    }
    
    @Override
    protected boolean shouldRenderAsCluster(Cluster cluster) {
        return cluster.getSize() > 1;
    }
    
  3. Apply cluster manager in your activity/fragment class.

    public class SampleActivity extends AppCompatActivity implements OnMapReadyCallback {
    
    private ClusterManager<SampleJob> mClusterManager;
    private GoogleMap mMap;
    private ArrayList<SampleJob> jobs = new ArrayList<SampleJob>();
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_landing);
    
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
    
    
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.getUiSettings().setMapToolbarEnabled(true);
        mClusterManager = new ClusterManager<SampleJob>(this, mMap);
        mClusterManager.setRenderer(new JobRenderer(this, mMap, mClusterManager));
        mMap.setOnCameraChangeListener(mClusterManager);
        mMap.setOnMarkerClickListener(mClusterManager);
    
        //Assume that we already have arraylist of jobs
    
    
        for(final SampleJob job: jobs){
            mClusterManager.addItem(job);
        }
        mClusterManager.cluster();
    }
    
  4. Result

Result

How to build a Horizontal ListView with RecyclerView?

With the release of RecyclerView library, now you can align a list of images bind with text easily. You can use LinearLayoutManager to specify the direction in which you would like to orient your list, either vertical or horizontal as shown below.

enter image description here

You can download a full working demo from this post

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

If you have ever used a proxy, VPN, etc(or may not, I am not sure).....Then the solution below may help you...I don't know why (and if anybody can tell me why, I will appreciate that), but it works, pefectly. Have a try when you totally feel desperate about that issue.

Come to your project, and open gradle-wrapper.properties or gradle.properties, comment out these codes about proxy:

#systemProp.http.nonProxyHosts=118.89.144.241|47.112.105.125
#systemProp.http.proxyHost=127.0.0.1
#systemProp.http.proxyPort=1081
#systemProp.https.nonProxyHosts=118.89.144.241|47.112.105.125
#systemProp.https.proxyHost=127.0.0.1
#systemProp.https.proxyPort=1081

enter image description here

Then, it might work.

PS: I met this problem when I try to use dataBinding library, and when I added the code

buildFeatures {
        dataBinding true
    }

into gradle as the guide told me and Syns the project, I got such an error:"Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve ......". Finally I did what I described above, and I successed. What I experience may give you a hint, so I post the solution here and hope it might help.

Asynchronous Requests with Python requests

If you want to use asyncio, then requests-async provides async/await functionality for requests - https://github.com/encode/requests-async

Encoding conversion in java

You don't need a library beyond the standard one - just use Charset. (You can just use the String constructors and getBytes methods, but personally I don't like just working with the names of character encodings. Too much room for typos.)

EDIT: As pointed out in comments, you can still use Charset instances but have the ease of use of the String methods: new String(bytes, charset) and String.getBytes(charset).

See "URL Encoding (or: 'What are those "%20" codes in URLs?')".

Query to display all tablespaces in a database and datafiles

In oracle, generally speaking, there are number of facts that I will mention in following section:

  • Each database can have many Schema/User (Logical division).
  • Each database can have many tablespaces (Logical division).
  • A schema is the set of objects (tables, indexes, views, etc) that belong to a user.
  • In Oracle, a user can be considered the same as a schema.
  • A database is divided into logical storage units called tablespaces, which group related logical structures together. For example, tablespaces commonly group all of an application’s objects to simplify some administrative operations. You may have a tablespace for application data and an additional one for application indexes.

Therefore, your question, "to see all tablespaces and datafiles belong to SCOTT" is s bit wrong.

However, there are some DBA views encompass information about all database objects, regardless of the owner. Only users with DBA privileges can access these views: DBA_DATA_FILES, DBA_TABLESPACES, DBA_FREE_SPACE, DBA_SEGMENTS.

So, connect to your DB as sysdba and run query through these helpful views. For example this query can help you to find all tablespaces and their data files that objects of your user are located:

SELECT DISTINCT sgm.TABLESPACE_NAME , dtf.FILE_NAME
FROM DBA_SEGMENTS sgm
JOIN DBA_DATA_FILES dtf ON (sgm.TABLESPACE_NAME = dtf.TABLESPACE_NAME)
WHERE sgm.OWNER = 'SCOTT'

How to calculate growth with a positive and negative number?

You could try shifting the number space upward so they both become positive.

To calculate a gain between any two positive or negative numbers, you're going to have to keep one foot in the magnitude-growth world and the other foot in the volume-growth world. You can lean to one side or the other depending on how you want the result gains to appear, and there are consequences to each choice.

Strategy

  1. Create a shift equation that generates a positive number relative to the old and new numbers.

  2. Add the custom shift to the old and new numbers to get new_shifted and old_shifted.

  3. Take the (new_shifted - old_shifted) / old_shifted) calculation to get the gain.

For example:

old -> new
-50 -> 30               //Calculate a shift like (2*(50 + 30)) = 160

shifted_old -> shifted_new
110         ->  190

= (new-old)/old
= (190-110)/110 = 72.73%

How to choose a shift function

If your shift function shifts the numbers too far upward, like for example adding 10000 to each number, you always get a tiny growth/decline. But if the shift is just big enough to get both numbers into positive territory, you'll get wild swings in the growth/decline on edge cases. You'll need to dial in the shift function so it makes sense for your particular application. There is no totally correct solution to this problem, you must take the bitter with the sweet.

Add this to your excel to see how the numbers and gains move about:

                           shift function
old new  abs_old  abs_new  2*abs(old)+abs(new)   shiftedold  shiftednew    gain
-50  30  50          30          160                110         190        72.73%
-50  40  50          40          180                130         220        69.23%
10   20  10          20          60                 70          80         14.29%
10   30  10          30          80                 90          110        22.22%
1    10  1           10          22                 23          32         39.13%
1    20  1           20          42                 43          62         44.19%
-10  10  10          10          40                 30          50         66.67%
-10  20  10          20          60                 50          80         60.00%
1    100  1          100         202                203         302        48.77%
1    1000 1          1000        2002               2003        3002       49.88%

The gain percentage is affected by the magnitude of the numbers. The numbers above are a bad example and result from a primitive shift function.

You have to ask yourself which critter has the most productive gain:

Evaluate the growth of critters A, B, C, and D:
A used to consume 0.01 units of energy and now consumes 10 units.
B used to consume 500 units and now consumes 700 units.
C used to consume -50 units (Producing units!) and now consumes 30 units.
D used to consume -0.01 units (Producing) and now consumes -30 units (producing).

In some ways arguments can be made that each critter is the biggest grower in their own way. Some people say B is best grower, others will say D is a bigger gain. You have to decide for yourself which is better.

The question becomes, can we map this intuitive feel of what we label as growth into a continuous function that tells us what humans tend to regard as "awesome growth" vs "mediocre growth".

Growth a mysterious thing

You then have to take into account that Critter B may have had a far more difficult time than critter D. Critter D may have far more prospects for it in the future than the others. It had an advantage! How do you measure the opportunity, difficulty, velocity and acceleration of growth? To be able to predict the future, you need to have an intuitive feel for what constitutes a "major home run" and a "lame advance in productivity".

The first and second derivatives of a function will give you the "velocity of growth" and "acceleration of growth". Learn about those in calculus, they are super important.

Which is growing more? A critter that is accelerating its growth minute by minute, or a critter that is decelerating its growth? What about high and low velocity and high/low rate of change? What about the notion of exhausting opportunities for growth. Cost benefit analysis and ability/inability to capitalize on opportunity. What about adversarial systems (where your success comes from another person's failure) and zero sum games?

There is exponential growth, liner growth. And unsustainable growth. Cost benefit analysis and fitting a curve to the data. The world is far queerer than we can suppose. Plotting a perfect line to the data does not tell you which data point comes next because of the black swan effect. I suggest all humans listen to this lecture on growth, the University of Colorado At Boulder gave a fantastic talk on growth, what it is, what it isn't, and how humans completely misunderstand it. http://www.youtube.com/watch?v=u5iFESMAU58

Fit a line to the temperature of heated water, once you think you've fit a curve, a black swan happens, and the water boils. This effect happens all throughout our universe, and your primitive function (new-old)/old is not going to help you.

Here is Java code that accomplishes most of the above notions in a neat package that suits my needs:

Critter growth - (a critter can be "radio waves", "beetles", "oil temprature", "stock options", anything).

public double evaluate_critter_growth_return_a_gain_percentage(
        double old_value, double new_value) throws Exception{

    double abs_old = Math.abs(old_value);
    double abs_new = Math.abs(new_value);

    //This is your shift function, fool around with it and see how
    //It changes.  Have a full battery of unit tests though before you fiddle.
    double biggest_absolute_value = (Math.max(abs_old, abs_new)+1)*2;

    if (new_value <= 0 || old_value <= 0){
        new_value = new_value + (biggest_absolute_value+1);
        old_value = old_value + (biggest_absolute_value+1);
    }

    if (old_value == 0 || new_value == 0){
        old_value+=1;
        new_value+=1;
    }

    if (old_value <= 0)
        throw new Exception("This should never happen.");

    if (new_value <= 0)
        throw new Exception("This should never happen.");


    return (new_value - old_value) / old_value;


}

Result

It behaves kind-of sort-of like humans have an instinctual feel for critter growth. When our bank account goes from -9000 to -3000, we say that is better growth than when the account goes from 1000 to 2000.

1->2     (1.0)  should be bigger than   1->1 (0.0)
1->2     (1.0)  should be smaller than  1->4 (3.0)
0->1     (0.2)  should be smaller than  1->3 (2.0)
-5-> -3  (0.25) should be smaller than -5->-1 (0.5)
-5->1    (0.75) should be smaller than -5->5 (1.25)
100->200 (1.0)  should be the same as  10->20 (1.0)
-10->1   (0.84) should be smaller than -20->1 (0.91)
-10->10  (1.53) should be smaller than -20->20 (1.73)
-200->200 should not be in outer space (say more than 500%):(1.97)
handle edge case 1-> -4: (-0.41)
1-> -4:  (-0.42) should be bigger than 1-> -9:(-0.45)

If my shift function makes sense for your needs, use it. Be sure to battle test this, if you crash the space shuttle its totally NOT my fault. This method is a heuristic.

Count number of columns in a table row

You could do

alert(document.getElementById('table1').rows[0].cells.length)

fiddle here http://jsfiddle.net/TEZ73/

Get full path of a file with FileUpload Control

It's currently true that "when you upload a file the browser will only send the source filename and not the full path" - it makes perfect sense that the server has no business knowing whether the file was in "C:\WINDOWS\" or "F:\SOMEDIR\OTHERDIR\PERSONALINFO\". The filename is always sent, and is useful both to help the user 'recognise' the content and possibly to interrogate the file extension to help determine the file type.

However I know from experience that Internet Explorer definitely used to (in older versions) send the entire path. It's difficult to find an authoritative confirmation (except this apache fileupload control doco)

Internet Explorer provides the entire path to the uploaded file and not just the base file name

Regardless, you should not use nor expect the full path to be sent by any 'modern' browser.

Function Pointers in Java

This brings to mind Steve Yegge's Execution in the Kingdom of Nouns. It basically states that Java needs an object for every action, and therefore does not have "verb-only" entities like function pointers.

ORA-00054: resource busy and acquire with NOWAIT specified

Step 1:

select object_name, s.sid, s.serial#, p.spid 
from v$locked_object l, dba_objects o, v$session s, v$process p
where l.object_id = o.object_id and l.session_id = s.sid and s.paddr = p.addr;

Step 2:

alter system kill session 'sid,serial#'; --`sid` and `serial#` get from step 1

More info: http://www.oracle-base.com/articles/misc/killing-oracle-sessions.php

Replacing instances of a character in a string

How about this:

sentence = 'After 1500 years of that thinking surpressed'

sentence = sentence.lower()

def removeLetter(text,char):

    result = ''
    for c in text:
        if c != char:
            result += c
    return text.replace(char,'*')
text = removeLetter(sentence,'a')

Writing an Excel file in EPPlus

If you have a collection of objects that you load using stored procedure you can also use LoadFromCollection.

using (ExcelPackage package = new ExcelPackage(file))
{
    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("test");

    worksheet.Cells["A1"].LoadFromCollection(myColl, true, OfficeOpenXml.Table.TableStyles.Medium1);

    package.Save();
}

Regular expression to match DNS hostname or IP Address?

You can use the following regular expressions separately or by combining them in a joint OR expression.

ValidIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";

ValidHostnameRegex = "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$";

ValidIpAddressRegex matches valid IP addresses and ValidHostnameRegex valid host names. Depending on the language you use \ could have to be escaped with \.


ValidHostnameRegex is valid as per RFC 1123. Originally, RFC 952 specified that hostname segments could not start with a digit.

http://en.wikipedia.org/wiki/Hostname

The original specification of hostnames in RFC 952, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (RFC 1123) permitted hostname labels to start with digits.

Valid952HostnameRegex = "^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$";

Formula to check if string is empty in Crystal Reports

If IsNull({TABLE.FIELD1}) then "NULL" +',' + {TABLE.FIELD2} else {TABLE.FIELD1} + ', ' + {TABLE.FIELD2}

Here I put NULL as string to display the string value NULL in place of the null value in the data field. Hope you understand.

How to disable JavaScript in Chrome Developer Tools?

This is the latest setting for the windows

Settings > Advanced > Privacy and security > Site Settings > Javascript > Blocked then get switch on and off

How to preserve request url with nginx proxy_pass

nginx also provides the $http_host variable which will pass the port for you. its a concatenation of host and port.

So u just need to do:

proxy_set_header Host $http_host;

How to convert java.util.Date to java.sql.Date?

i am using the following code please try it out

DateFormat fm= new SimpleDateFormatter();

specify the format of the date you want for example "DD-MM_YYYY" or 'YYYY-mm-dd' then use the java Date datatype as

fm.format("object of java.util.date");

then it will parse your date

Why is my Button text forced to ALL CAPS on Lollipop?

Add android:textAllCaps="false" in <Button> tag that's it.

Does it make sense to use Require.js with Angular.js?

I would avoid using Require.js. Apps I've seen that do this wind up a mess of multiple types of module pattern architecture. AMD, Revealing, different flavors of IIFE, etc. There are other ways to load on demand like the loadOnDemand Angular mod. Adding other stuff just fills your code full of cruft and creates a low signal to noise ratio and makes your code hard to read.

Get the current URL with JavaScript?

var currentPageUrlIs = "";
if (typeof this.href != "undefined") {
       currentPageUrlIs = this.href.toString().toLowerCase(); 
}else{ 
       currentPageUrlIs = document.location.toString().toLowerCase();
}

The above code can also help someone

How to send an email using PHP?

The native PHP function mail() does not work for me. It issues the message:

503 This mail server requires authentication when attempting to send to a non-local e-mail address

So, I usually use PHPMailer package

I've downloaded the version 5.2.23 from: GitHub.

I've just picked 2 files and put them in my source PHP root

class.phpmailer.php
class.smtp.php

In PHP, the file needs to be added

require_once('class.smtp.php');
require_once('class.phpmailer.php');

After this, it's just code:

require_once('class.smtp.php');
require_once('class.phpmailer.php');
... 
//----------------------------------------------
// Send an e-mail. Returns true if successful 
//
//   $to - destination
//   $nameto - destination name
//   $subject - e-mail subject
//   $message - HTML e-mail body
//   altmess - text alternative for HTML.
//----------------------------------------------
function sendmail($to,$nameto,$subject,$message,$altmess)  {

  $from  = "[email protected]";
  $namefrom = "yourname";
  $mail = new PHPMailer();  
  $mail->CharSet = 'UTF-8';
  $mail->isSMTP();   // by SMTP
  $mail->SMTPAuth   = true;   // user and password
  $mail->Host       = "localhost";
  $mail->Port       = 25;
  $mail->Username   = $from;  
  $mail->Password   = "yourpassword";
  $mail->SMTPSecure = "";    // options: 'ssl', 'tls' , ''  
  $mail->setFrom($from,$namefrom);   // From (origin)
  $mail->addCC($from,$namefrom);      // There is also addBCC
  $mail->Subject  = $subject;
  $mail->AltBody  = $altmess;
  $mail->Body = $message;
  $mail->isHTML();   // Set HTML type
//$mail->addAttachment("attachment");  
  $mail->addAddress($to, $nameto);
  return $mail->send();
}

It works like a charm

Cloning git repo causes error - Host key verification failed. fatal: The remote end hung up unexpectedly

Resolved the issue... you need to add the ssh public key to your github account.

  1. Verify that the ssh keys have been setup correctly.
    1. Run ssh-keygen
    2. Enter the password (keep the default path - ~/.ssh/id_rsa)
  2. Add the public key (~/.ssh/id_rsa.pub) to github account
  3. Try git clone. It works!


Initial status (public key not added to git hub account)

foo@bn18-251:~$ rm -rf test
foo@bn18-251:~$ ls
foo@bn18-251:~$ git clone [email protected]:devendra-d-chavan/test.git
Cloning into 'test'...
Permission denied (publickey).
fatal: The remote end hung up unexpectedly
foo@bn18-251:~$


Now, add the public key ~/.ssh/id_rsa.pub to the github account (I used cat ~/.ssh/id_rsa.pub)

foo@bn18-251:~$ ssh-keygen 
Generating public/private rsa key pair.
Enter file in which to save the key (/home/foo/.ssh/id_rsa): 
Created directory '/home/foo/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/foo/.ssh/id_rsa.
Your public key has been saved in /home/foo/.ssh/id_rsa.pub.
The key fingerprint is:
xxxxx
The key's randomart image is:
+--[ RSA 2048]----+
xxxxx
+-----------------+
foo@bn18-251:~$ cat ./.ssh/id_rsa.pub 
xxxxx
foo@bn18-251:~$ git clone [email protected]:devendra-d-chavan/test.git
Cloning into 'test'...
The authenticity of host 'github.com (207.97.227.239)' can't be established.
RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'github.com,207.97.227.239' (RSA) to the list of known hosts.
Enter passphrase for key '/home/foo/.ssh/id_rsa': 
warning: You appear to have cloned an empty repository.
foo@bn18-251:~$ ls
test
foo@bn18-251:~/test$ git status
# On branch master
#
# Initial commit
#
nothing to commit (create/copy files and use "git add" to track)

Simple PowerShell LastWriteTime compare

Use

ls | % {(get-date) - $_.LastWriteTime }

It can work to retrieve the diff. You can replace ls with a single file.

How to prevent errno 32 broken pipe?

This might be because you are using two method for inserting data into database and this cause the site to slow down.

def add_subscriber(request, email=None):
    if request.method == 'POST':
        email = request.POST['email_field']
        e = Subscriber.objects.create(email=email).save()  <==== 
        return HttpResponseRedirect('/')
    else:
        return HttpResponseRedirect('/')

In above function, the error is where arrow is pointing. The correct implementation is below:

def add_subscriber(request, email=None):
    if request.method == 'POST':
        email = request.POST['email_field']
        e = Subscriber.objects.create(email=email)
        return HttpResponseRedirect('/')
    else:
        return HttpResponseRedirect('/')

JSHint and jQuery: '$' is not defined

You probably want to do the following,

const $ = window.$

to avoid it throwing linting error.

How to count the number of occurrences of an element in a List

A slightly more efficient approach might be

Map<String, AtomicInteger> instances = new HashMap<String, AtomicInteger>();

void add(String name) {
     AtomicInteger value = instances.get(name);
     if (value == null) 
        instances.put(name, new AtomicInteger(1));
     else
        value.incrementAndGet();
}

How / can I display a console window in Intellij IDEA?

Hover to the sidebar and select the "Restore visual elements of debugger..."

enter image description here

<hr> tag in Twitter Bootstrap not functioning correctly?

the css property of <hr> are :

hr {
  -moz-border-bottom-colors: none;
  -moz-border-image: none;
  -moz-border-left-colors: none;
  -moz-border-right-colors: none;
  -moz-border-top-colors: none;
  border-color: #EEEEEE -moz-use-text-color #FFFFFF;
  border-style: solid none;
  border-width: 1px 0;
  margin: 18px 0;
}

It correspond to a 1px horizontal line with a very light grey and vertical margin of 18px.

and because <hr> is inside a <div> without class the width depends on the content of the <div>

if you would like the <hr> to be full width, replace <div> with <div class='row'><div class='span12'> (with according closing tags).

If you expect something different, describe what you expect by adding a comment.

PostgreSQL Error: Relation already exists

Another reason why you might get errors like "relation already exists" is if the DROP command did not execute correctly.

One reason this can happen is if there are other sessions connected to the database which you need to close first.

Populating a ListView using an ArrayList?

Try the below answer to populate listview using ArrayList

public class ExampleActivity extends Activity
{
    ArrayList<String> movies;

    public void onCreate(Bundle saveInstanceState)
    {
       super.onCreate(saveInstanceState);
       setContentView(R.layout.list);

       // Get the reference of movies
       ListView moviesList=(ListView)findViewById(R.id.listview);

       movies = new ArrayList<String>();
       getMovies();

       // Create The Adapter with passing ArrayList as 3rd parameter
       ArrayAdapter<String> arrayAdapter =      
                 new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, movies);
       // Set The Adapter
       moviesList.setAdapter(arrayAdapter); 

       // register onClickListener to handle click events on each item
       moviesList.setOnItemClickListener(new OnItemClickListener()
       {
           // argument position gives the index of item which is clicked
           public void onItemClick(AdapterView<?> arg0, View v,int position, long arg3)
           {
               String selectedmovie=movies.get(position);
               Toast.makeText(getApplicationContext(), "Movie Selected : "+selectedmovie,   Toast.LENGTH_LONG).show();
           }
        });
    }

    void getmovies()
    {
        movies.add("X-Men");
        movies.add("IRONMAN");
        movies.add("SPIDY");
        movies.add("NARNIA");
        movies.add("LIONKING");
        movies.add("AVENGERS");   
    }
}

Moving all files from one directory to another using Python

Move files with filter( using Path, os,shutil modules):

from pathlib import Path
import shutil
import os

src_path ='/media/shakil/New Volume/python/src'
trg_path ='/media/shakil/New Volume/python/trg'

for src_file in Path(src_path).glob('*.txt*'):
    shutil.move(os.path.join(src_path,src_file),trg_path)

JPA entity without id

I guess you can use @CollectionOfElements (for hibernate/jpa 1) / @ElementCollection (jpa 2) to map a collection of "entity properties" to a List in entity.

You can create the EntityProperty type and annotate it with @Embeddable

array.select() in javascript

There's also Array.find() in ES6 which returns the first matching element it finds.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

const myArray = [1, 2, 3]

const myElement = myArray.find((element) => element === 2)

console.log(myElement)
// => 2

How to get an Android WakeLock to work?

Do you have the required permission set in your Manifest?

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

C# Switch-case string starting with

If all the cases have the same length you can use
switch (mystring.SubString(0,Math.Min(len, mystring.Length))).
Another option is to have a function that will return categoryId based on the string and switch on the id.

Call angularjs function using jquery/javascript

Try this:

const scope = angular.element(document.getElementById('YourElementId')).scope();
scope.$apply(function(){
     scope.myfunction('test');
});

How to disable an input box using angular.js

Your markup should contain an additional attribute called ng-disabled whose value should be a condition or expression that would evaluate to be either true or false.

    <input data-ng-model="userInf.username"  class="span12 editEmail" 
       type="text"  placeholder="[email protected]"  
       pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" 
       required 
       ng-disabled="{condition or expression}"
/>

And in the controller you may have some code that would affect the value of ng-disabled directive.

How to properly use the "choices" field option in Django

For Django3.0+, use models.TextChoices (see docs-v3.0 for enumeration types)

from django.db import models

class MyModel(models.Model):
    class Month(models.TextChoices):
        JAN = '1', "JANUARY"
        FEB = '2', "FEBRUARY"
        MAR = '3', "MAR"
        # (...)

    month = models.CharField(
        max_length=2,
        choices=Month.choices,
        default=Month.JAN
    )

Usage::

>>> obj = MyModel.objects.create(month='1')
>>> assert obj.month == obj.Month.JAN
>>> assert MyModel.Month(obj.month).label == 'JANUARY'
>>> assert MyModel.objects.filter(month=MyModel.Month.JAN).count() >= 1

>>> obj2 = MyModel(month=MyModel.Month.FEB)
>>> assert obj2.get_month_display() == obj2.Month(obj2.month).label

Converting data frame column from character to numeric

If we need only one column to be numeric

yyz$b <- as.numeric(as.character(yyz$b))

But, if all the columns needs to changed to numeric, use lapply to loop over the columns and convert to numeric by first converting it to character class as the columns were factor.

yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))

Both the columns in the OP's post are factor because of the string "n/a". This could be easily avoided while reading the file using na.strings = "n/a" in the read.table/read.csv or if we are using data.frame, we can have character columns with stringsAsFactors=FALSE (the default is stringsAsFactors=TRUE)


Regarding the usage of apply, it converts the dataset to matrix and matrix can hold only a single class. To check the class, we need

lapply(yyz, class)

Or

sapply(yyz, class)

Or check

str(yyz)

What is the best way to implement constants in Java?

A good object oriented design should not need many publicly available constants. Most constants should be encapsulated in the class that needs them to do its job.

How to check if a String contains any letter from a to z?

Replace your for loop by this :

errorCounter = Regex.Matches(yourstring,@"[a-zA-Z]").Count;

Remember to use Regex class, you have to using System.Text.RegularExpressions; in your import

Getting number of elements in an iterator in Python

It's common practice to put this type of information in the file header, and for pysam to give you access to this. I don't know the format, but have you checked the API?

As others have said, you can't know the length from the iterator.

List of phone number country codes

Android ready county list and flag images

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- country list -->
    <string-array name="data000">
        <item name="code">+93</item>
        <item name="country">Afghanistan</item>
        <item name="iso">AF</item>
        <item name="flag">@drawable/afghanistan</item>
    </string-array>
    <string-array name="data001">
        <item name="code">+355</item>
        <item name="country">Albania</item>
        <item name="iso">AL</item>
        <item name="flag">@drawable/albania</item>
    </string-array>
    ...

    <array name="countries">
        <item>@array/data000</item>
        <item>@array/data001</item>
        ...
    </array>
</resources>

Moving from one activity to another Activity in Android

public void onClick(View v)
{
 startActivity(new Intent(getApplicationContext(), Next.class));

}

it is direct way to move second activity and there is no need for call intent

How to add background image for input type="button"?

background-image takes an url as a value. Use either

background-image: url ('/image/btn.png');

or

background: url ('/image/btn.png') no-repeat;

which is a shorthand for

background-image: url ('/image/btn.png');
background-repeat: no-repeat;

Also, you might want to look at the button HTML element for fancy submit buttons.

Converting string to date in mongodb

I had some strings in the MongoDB Stored wich had to be reformated to a proper and valid dateTime field in the mongodb.

here is my code for the special date format: "2014-03-12T09:14:19.5303017+01:00"

but you can easyly take this idea and write your own regex to parse the date formats:

// format: "2014-03-12T09:14:19.5303017+01:00"
var myregexp = /(....)-(..)-(..)T(..):(..):(..)\.(.+)([\+-])(..)/;

db.Product.find().forEach(function(doc) { 
   var matches = myregexp.exec(doc.metadata.insertTime);

   if myregexp.test(doc.metadata.insertTime)) {
       var offset = matches[9] * (matches[8] == "+" ? 1 : -1);
       var hours = matches[4]-(-offset)+1
       var date = new Date(matches[1], matches[2]-1, matches[3],hours, matches[5], matches[6], matches[7] / 10000.0)
       db.Product.update({_id : doc._id}, {$set : {"metadata.insertTime" : date}})
       print("succsessfully updated");
    } else {
        print("not updated");
    }
})

How to use a findBy method with comparative criteria

This is an example using the Expr() Class - I needed this too some days ago and it took me some time to find out what is the exact syntax and way of usage:

/**
 * fetches Products that are more expansive than the given price
 * 
 * @param int $price
 * @return array
 */
public function findProductsExpensiveThan($price)
{
  $em = $this->getEntityManager();
  $qb = $em->createQueryBuilder();

  $q  = $qb->select(array('p'))
           ->from('YourProductBundle:Product', 'p')
           ->where(
             $qb->expr()->gt('p.price', $price)
           )
           ->orderBy('p.price', 'DESC')
           ->getQuery();

  return $q->getResult();
}

SQL Insert Query Using C#

I have just wrote a reusable method for that, there is no answer here with reusable method so why not to share...
here is the code from my current project:

public static int ParametersCommand(string query,List<SqlParameter> parameters)
{
    SqlConnection connection = new SqlConnection(ConnectionString);
    try
    {
        using (SqlCommand cmd = new SqlCommand(query, connection))
        {   // for cases where no parameters needed
            if (parameters != null)
            {
                cmd.Parameters.AddRange(parameters.ToArray());
            }

            connection.Open();
            int result = cmd.ExecuteNonQuery();
            return result;
        }
    }
    catch (Exception ex)
    {
        AddEventToEventLogTable("ERROR in DAL.DataBase.ParametersCommand() method: " + ex.Message, 1);
        return 0;
        throw;
    }

    finally
    {
        CloseConnection(ref connection);
    }
}

private static void CloseConnection(ref SqlConnection conn)
{
    if (conn.State != ConnectionState.Closed)
    {
        conn.Close();
        conn.Dispose();
    }
}

Checking if date is weekend PHP

The working version of your code (from the errors pointed out by BoltClock):

<?php
$date = '2011-01-01';
$timestamp = strtotime($date);
$weekday= date("l", $timestamp );
$normalized_weekday = strtolower($weekday);
echo $normalized_weekday ;
if (($normalized_weekday == "saturday") || ($normalized_weekday == "sunday")) {
    echo "true";
} else {
    echo "false";
}

?>

The stray "{" is difficult to see, especially without a decent PHP editor (in my case). So I post the corrected version here.

What is the maximum possible length of a .NET string?

For anyone coming to this topic late, I could see that hitscan's "you probably shouldn't do that" might cause someone to ask what they should do…

The StringBuilder class is often an easy replacement. Consider one of the stream-based classes especially, if your data is coming from a file.

The problem with s += "stuff" is that it has to allocate a completely new area to hold the data and then copy all of the old data to it plus the new stuff - EACH AND EVERY LOOP ITERATION. So, adding five bytes to 1,000,000 with s += "stuff" is extremely costly. If what you want is to just write five bytes to the end and proceed with your program, you have to pick a class that leaves some room for growth:

StringBuilder sb = new StringBuilder(5000);
for (; ; )
    {
        sb.Append("stuff");
    }

StringBuilder will auto-grow by doubling when it's limit is hit. So, you will see the growth pain once at start, once at 5,000 bytes, again at 10,000, again at 20,000. Appending strings will incur the pain every loop iteration.

how to get 2 digits after decimal point in tsql?

Try cast result to numeric

CAST(sum(cast(datediff(second, IEC.CREATE_DATE, IEC.STATUS_DATE) as float) / 60)
    AS numeric(10,2)) TotalSentMinutes

Input

1
2
3

Output

1.00
2.00
3.00

Define make variable at rule execution time

Another possibility is to use separate lines to set up Make variables when a rule fires.

For example, here is a makefile with two rules. If a rule fires, it creates a temp dir and sets TMP to the temp dir name.

PHONY = ruleA ruleB display

all: ruleA

ruleA: TMP = $(shell mktemp -d testruleA_XXXX)
ruleA: display

ruleB: TMP = $(shell mktemp -d testruleB_XXXX)
ruleB: display

display:
    echo ${TMP}

Running the code produces the expected result:

$ ls
Makefile
$ make ruleB
echo testruleB_Y4Ow
testruleB_Y4Ow
$ ls
Makefile  testruleB_Y4Ow

How to update multiple columns in single update statement in DB2

I know it's an old question, but I just had to find solution for multiple rows update where multiple records had to updated with different values based on their IDs and I found that I can use a a scalar-subselect:

UPDATE PROJECT
  SET DEPTNO =
        (SELECT WORKDEPT FROM EMPLOYEE
           WHERE PROJECT.RESPEMP = EMPLOYEE.EMPNO)
  WHERE RESPEMP='000030'

(with WHERE optional, of course)

Also, I found that it is critical to specify that no NULL values would not be used in this update (in case not all records in first table have corresponding record in the second one), this way:

UPDATE PROJECT
  SET DEPTNO =
        (SELECT WORKDEPT FROM EMPLOYEE
           WHERE PROJECT.RESPEMP = EMPLOYEE.EMPNO)
  WHERE RESPEMP IN (SELECT EMPNO FROM EMPLOYEE)

Source: https://www.ibm.com/support/knowledgecenter/ssw_i5_54/sqlp/rbafyupdatesub.htm

Can't start Tomcat as Windows Service

Well before going so far, fist make sure that you have the path to the Java directory in your Windows Environment Path

  1. Start > Control Panel > look up for the "System"
  2. Edit the system environment variables
  3. Click on "Environment Variables..." button.
  4. in the System Variables group box, click one the "New..." button
  5. assign a desired name like "Java_Home"
  6. Click on "Brows Directory" and address your Java jdk directory. ex: C:\Program Files\Java\jdk-13.0.2
  7. go to the Tomcat 'bin' folder and start it up.

Supposed to work now.

Get Locale Short Date Format using javascript

I believe you can use this one:

new Date().toLocaleDateString();

Which can accept parameters for the locale:

new Date().toLocaleDateString("en-us");
new Date().toLocaleDateString("he-il");

I see it is supported by chrome, IE, edge, although results may vary it does a pretty good job for me.

PHP date() with timezone?

The answer above caused me to jump through some hoops/gotchas, so just posting the cleaner code that worked for me:

$dt = new DateTime();
$dt->setTimezone(new DateTimeZone('America/New_York'));
$dt->setTimestamp(123456789);

echo $dt->format('F j, Y @ G:i');

Python Requests throwing SSLError

I encountered the same issue and ssl certificate verify failed issue when using aws boto3, by review boto3 code, I found the REQUESTS_CA_BUNDLE is not set, so I fixed the both issue by setting it manually:

from boto3.session import Session
import os

# debian
os.environ['REQUESTS_CA_BUNDLE'] = os.path.join(
    '/etc/ssl/certs/',
    'ca-certificates.crt')
# centos
#   'ca-bundle.crt')

For aws-cli, I guess setting REQUESTS_CA_BUNDLE in ~/.bashrc will fix this issue (not tested because my aws-cli works without it).

REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt # ca-bundle.crt
export REQUESTS_CA_BUNDLE

What is Java String interning?

Java interning() method basically makes sure that if String object is present in SCP, If yes then it returns that object and if not then creates that objects in SCP and return its references

for eg: String s1=new String("abc");
        String s2="abc";
        String s3="abc";

s1==s2// false, because 1 object of s1 is stored in heap and other in scp(but this objects doesn't have explicit reference) and s2 in scp
s2==s3// true

now if we do intern on s1
s1=s1.intern() 

//JVM checks if there is any string in the pool with value “abc” is present? Since there is a string object in the pool with value “abc”, its reference is returned.
Notice that we are calling s1 = s1.intern(), so the s1 is now referring to the string pool object having value “abc”.
At this point, all the three string objects are referring to the same object in the string pool. Hence s1==s2 is returning true now.

PHP check if url parameter exists

It is not quite clear what function you are talking about and if you need 2 separate branches or one. Assuming one:

Change your first line to

$slide = '';
if (isset($_GET["id"]))
{
    $slide = $_GET["id"];
}

Python convert set to string and vice versa

If you do not need the serialized text to be human readable, you can use pickle.

import pickle

s = set([1,2,3])

serialized_s = pickle.dumps(s)
print "serialized:"
print serialized_s

deserialized_s = pickle.loads(serialized_s)
print "deserialized:"
print deserialized_s

Result:

serialized:
c__builtin__
set
p0
((lp1
I1
aI2
aI3
atp2
Rp3
.
deserialized:
set([1, 2, 3])

how to get the cookies from a php curl into a variable

$ch = curl_init('http://www.google.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// get headers too with this line
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
// get cookie
// multi-cookie variant contributed by @Combuster in comments
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);
$cookies = array();
foreach($matches[1] as $item) {
    parse_str($item, $cookie);
    $cookies = array_merge($cookies, $cookie);
}
var_dump($cookies);

What is better, adjacency lists or adjacency matrices for graph problems in C++?

This answer is not just for C++ since everything mentioned is about the data structures themselves, regardless of language. And, my answer is assuming that you know the basic structure of adjacency lists and matrices.

Memory

If memory is your primary concern you can follow this formula for a simple graph that allows loops:

An adjacency matrix occupies n2/8 byte space (one bit per entry).

An adjacency list occupies 8e space, where e is the number of edges (32bit computer).

If we define the density of the graph as d = e/n2 (number of edges divided by the maximum number of edges), we can find the "breakpoint" where a list takes up more memory than a matrix:

8e > n2/8 when d > 1/64

So with these numbers (still 32-bit specific) the breakpoint lands at 1/64. If the density (e/n2) is bigger than 1/64, then a matrix is preferable if you want to save memory.

You can read about this at wikipedia (article on adjacency matrices) and a lot of other sites.

Side note: One can improve the space-efficiency of the adjacency matrix by using a hash table where the keys are pairs of vertices (undirected only).

Iteration and lookup

Adjacency lists are a compact way of representing only existing edges. However, this comes at the cost of possibly slow lookup of specific edges. Since each list is as long as the degree of a vertex the worst case lookup time of checking for a specific edge can become O(n), if the list is unordered. However, looking up the neighbours of a vertex becomes trivial, and for a sparse or small graph the cost of iterating through the adjacency lists might be negligible.

Adjacency matrices on the other hand use more space in order to provide constant lookup time. Since every possible entry exists you can check for the existence of an edge in constant time using indexes. However, neighbour lookup takes O(n) since you need to check all possible neighbours. The obvious space drawback is that for sparse graphs a lot of padding is added. See the memory discussion above for more information on this.

If you're still unsure what to use: Most real-world problems produce sparse and/or large graphs, which are better suited for adjacency list representations. They might seem harder to implement but I assure you they aren't, and when you write a BFS or DFS and want to fetch all neighbours of a node they're just one line of code away. However, note that I'm not promoting adjacency lists in general.

How do I use shell variables in an awk script?

It seems that the good-old ENVIRON built-in hash is not mentioned at all. An example of its usage:

$ X=Solaris awk 'BEGIN{print ENVIRON["X"], ENVIRON["TERM"]}'
Solaris rxvt

Running interactive commands in Paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(server_IP,22,username, password)


stdin, stdout, stderr = ssh.exec_command('/Users/lteue/Downloads/uecontrol-CXC_173_6456-R32A01/uecontrol.sh -host localhost ')
alldata = ""
while not stdout.channel.exit_status_ready():
   solo_line = ""        
   # Print stdout data when available
   if stdout.channel.recv_ready():
      # Retrieve the first 1024 bytes
      solo_line = stdout.channel.recv(1024) 
      alldata += solo_line
   if(cmp(solo_line,'uec> ') ==0 ):    #Change Conditionals to your code here  
     if num_of_input == 0 :
      data_buffer = ""    
      for cmd in commandList :
       #print cmd
       stdin.channel.send(cmd)        # send input commmand 1
      num_of_input += 1
     if num_of_input == 1 :
      stdin.channel.send('q \n')      # send input commmand 2 , in my code is exit the interactive session, the connect will close.
      num_of_input += 1 
print alldata
ssh.close()              

Why the stdout.read() will hang if use dierectly without checking stdout.channel.recv_ready(): in while stdout.channel.exit_status_ready():

For my case ,after run command on remote server , the session is waiting for user input , after input 'q' ,it will close the connection . But before inputting 'q' , the stdout.read() will waiting for EOF,seems this methord does not works if buffer is larger .

  • I tried stdout.read(1) in while , it works
    I tried stdout.readline() in while , it works also.
    stdin, stdout, stderr = ssh.exec_command('/Users/lteue/Downloads/uecontrol')
    stdout.read() will hang

How to find indices of all occurrences of one string in another in JavaScript?

the below code will do the job for you :

function indexes(source, find) {
  var result = [];
  for(i=0;i<str.length; ++i) {
    // If you want to search case insensitive use 
    // if (source.substring(i, i + find.length).toLowerCase() == find) {
    if (source.substring(i, i + find.length) == find) {
      result.push(i);
    }
  }
  return result;
}

indexes("hello, how are you", "ar")

What does if __name__ == "__main__": do?

What does the if __name__ == "__main__": do?

To outline the basics:

  • The global variable, __name__, in the module that is the entry point to your program, is '__main__'. Otherwise, it's the name you import the module by.

  • So, code under the if block will only run if the module is the entry point to your program.

  • It allows the code in the module to be importable by other modules, without executing the code block beneath on import.


Why do we need this?

Developing and Testing Your Code

Say you're writing a Python script designed to be used as a module:

def do_important():
    """This function does something very important"""

You could test the module by adding this call of the function to the bottom:

do_important()

and running it (on a command prompt) with something like:

~$ python important.py

The Problem

However, if you want to import the module to another script:

import important

On import, the do_important function would be called, so you'd probably comment out your function call, do_important(), at the bottom.

# do_important() # I must remember to uncomment to execute this!

And then you'll have to remember whether or not you've commented out your test function call. And this extra complexity would mean you're likely to forget, making your development process more troublesome.

A Better Way

The __name__ variable points to the namespace wherever the Python interpreter happens to be at the moment.

Inside an imported module, it's the name of that module.

But inside the primary module (or an interactive Python session, i.e. the interpreter's Read, Eval, Print Loop, or REPL) you are running everything from its "__main__".

So if you check before executing:

if __name__ == "__main__":
    do_important()

With the above, your code will only execute when you're running it as the primary module (or intentionally call it from another script).

An Even Better Way

There's a Pythonic way to improve on this, though.

What if we want to run this business process from outside the module?

If we put the code we want to exercise as we develop and test in a function like this and then do our check for '__main__' immediately after:

def main():
    """business logic for when running this module as the primary one!"""
    setup()
    foo = do_important()
    bar = do_even_more_important(foo)
    for baz in bar:
        do_super_important(baz)
    teardown()

# Here's our payoff idiom!
if __name__ == '__main__':
    main()

We now have a final function for the end of our module that will run if we run the module as the primary module.

It will allow the module and its functions and classes to be imported into other scripts without running the main function, and will also allow the module (and its functions and classes) to be called when running from a different '__main__' module, i.e.

import important
important.main()

This idiom can also be found in the Python documentation in an explanation of the __main__ module. That text states:

This module represents the (otherwise anonymous) scope in which the interpreter’s main program executes — commands read either from standard input, from a script file, or from an interactive prompt. It is this environment in which the idiomatic “conditional script” stanza causes a script to run:

if __name__ == '__main__':
    main()

Xampp localhost/dashboard

If you want to display directory than edit htdocs/index.php file

Below code is display all directory in table

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Welcome to Nims Server</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="server/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<!-- START PAGE SOURCE -->
<div id="wrap">
  <div id="top">
    <h1 id="sitename">Nims <em>Server</em> Directory list</h1>
    <div id="searchbar">
      <form action="#">
        <div id="searchfield">
          <input type="text" name="keyword" class="keyword" />
          <input class="searchbutton" type="image" src="server/images/searchgo.gif"  alt="search" />
        </div>
      </form>
    </div>
  </div>

<div class="background">
<div class="transbox">
<table width="100%" border="0" cellspacing="3" cellpadding="5" style="border:0px solid #333333;background: #F9F9F9;"> 
<tr>
<?php
//echo md5("saketbook007");

//File functuion DIR is used here.
$d = dir($_SERVER['DOCUMENT_ROOT']); 
$i=-1;
//Loop start with read function
while ($entry = $d->read()) {
if($entry == "." || $entry ==".."){
}else{
?>
<td  class="site" width="33%"><a href="<?php echo $entry;?>" ><?php echo ucfirst($entry); ?></a></td>  
<?php 
}
if($i%3 == 0){
echo "</tr><tr>";
}
$i++;
}?>
</tr> 
</table>

<?php $d->close();
?> 

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

Style:

@import url("fontface.css");
* {
    padding:0;
    margin:0;
}
.clear {
    clear:both;
}

body {
    background:url(images/bg.jpg) repeat;
    font-family:"Palatino Linotype", "Book Antiqua", Palatino, serif;
    color:#212713;
}
#wrap {
    width:1300px;
    margin:auto;
}

#sitename {
    font: normal 46px chunk;
    color:#1b2502;
    text-shadow:#5d7a17 1px 1px 1px;
    display:block;
    padding:45px 0 0 0;
    width:60%;
    float:left;
}
#searchbar {
    width:39%;
    float:right;
}
#sitename em {
    font-family:"Palatino Linotype", "Book Antiqua", Palatino, serif;
}
#top {
    height:145px;
}
img {

    width:90%;
    height:250px;
    padding:10px;
    border:1px solid #000;
    margin:0 0 0 50px;
}


.post h2 a {
    color:#656f42;
    text-decoration:none;
}
#searchbar {
    padding:55px 0 0 0;
}
#searchfield {
    background:url(images/searchbar.gif) no-repeat;
    width:239px;
    height:35px;
    float:right;
}
#searchfield .keyword {
    width:170px;
    background:transparent;
    border:none;
    padding:8px 0 0 10px;
    color:#fff;
    display:block;
    float:left;
}
#searchfield .searchbutton {
    display:block;
    float:left;
    margin:7px 0 0 5px;
}

div.background
{
  background:url(h.jpg) repeat-x;
  border: 2px solid black;

  width:99%;
}
div.transbox
{
  margin: 15px;
  background-color: #ffffff;

  border: 1px solid black;
  opacity:0.8;
  filter:alpha(opacity=60); /* For IE8 and earlier */
  height:500px;
}

.site{

border:1px solid #CCC; 
}

.site a{text-decoration:none;font-weight:bold; color:#000; line-height:2}
.site:hover{background:#000; border:1px solid #03C;}
.site:hover a{color:#FFF}

Output : enter image description here

Hide div by default and show it on click with bootstrap

Just add water style="display:none"; to the <div>

Fiddles I say: http://jsfiddle.net/krY56/13/

jQuery:

function toggler(divId) {
    $("#" + divId).toggle();
}

Preferred to have a CSS Class .hidden

.hidden {
     display:none;
}

The view didn't return an HttpResponse object. It returned None instead

Python is very sensitive to indentation, with the code below I got the same error:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
            return render(request, "calender.html")

The correct indentation is:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
        return render(request, "calender.html")

How to SHA1 hash a string in Android?

A simpler SHA-1 method: (updated from the commenter's suggestions, also using a massively more efficient byte->string algorithm)

String sha1Hash( String toHash )
{
    String hash = null;
    try
    {
        MessageDigest digest = MessageDigest.getInstance( "SHA-1" );
        byte[] bytes = toHash.getBytes("UTF-8");
        digest.update(bytes, 0, bytes.length);
        bytes = digest.digest();

        // This is ~55x faster than looping and String.formating()
        hash = bytesToHex( bytes );
    }
    catch( NoSuchAlgorithmException e )
    {
        e.printStackTrace();
    }
    catch( UnsupportedEncodingException e )
    {
        e.printStackTrace();
    }
    return hash;
}

// http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex( byte[] bytes )
{
    char[] hexChars = new char[ bytes.length * 2 ];
    for( int j = 0; j < bytes.length; j++ )
    {
        int v = bytes[ j ] & 0xFF;
        hexChars[ j * 2 ] = hexArray[ v >>> 4 ];
        hexChars[ j * 2 + 1 ] = hexArray[ v & 0x0F ];
    }
    return new String( hexChars );
}

MySQL: How to set the Primary Key on phpMyAdmin?

MySQL can index the first x characters of a column,but a TEXT type is of variable length so mysql cant assure the uniqueness of the column.If you still want text column,use VARCHAR.

Can I set an opacity only to the background image of a div?

Nope, this cannot be done since opacity affects the whole element including its content and there's no way to alter this behavior. You can work around this with the two following methods.

Secondary div

Add another div element to the container to hold the background. This is the most cross-browser friendly method and will work even on IE6.

HTML

<div class="myDiv">
    <div class="bg"></div>
    Hi there
</div>

CSS

.myDiv {
    position: relative;
    z-index: 1;
}

.myDiv .bg {
    position: absolute;
    z-index: -1;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: url(test.jpg) center center;
    opacity: .4;
    width: 100%;
    height: 100%;
}

See test case on jsFiddle

:before and ::before pseudo-element

Another trick is to use the CSS 2.1 :before or CSS 3 ::before pseudo-elements. :before pseudo-element is supported in IE from version 8, while the ::before pseudo-element is not supported at all. This will hopefully be rectified in version 10.

HTML

<div class="myDiv">
    Hi there
</div>

CSS

.myDiv {
    position: relative;
    z-index: 1;
}

.myDiv:before {
    content: "";
    position: absolute;
    z-index: -1;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: url(test.jpg) center center;
    opacity: .4;
}

Additional notes

Due to the behavior of z-index you will have to set a z-index for the container as well as a negative z-index for the background image.

Test cases

See test case on jsFiddle:

Why can't I use Docker CMD multiple times to run multiple services?

The official docker answer to Run multiple services in a container.

It explains how you can do it with an init system (systemd, sysvinit, upstart) , a script (CMD ./my_wrapper_script.sh) or a supervisor like supervisord.

The && workaround can work only for services that starts in background (daemons) or that will execute quickly without interaction and release the prompt. Doing this with an interactive service (that keeps the prompt) and only the first service will start.

How to remove and clear all localStorage data

Something like this should do:

function cleanLocalStorage() {
    for(key in localStorage) {
        delete localStorage[key];
    }
}

Be careful about using this, though, as the user may have other data stored in localStorage and would probably be pretty ticked if you deleted that. I'd recommend either a) not storing the user's data in localStorage or b) storing the user's account stuff in a single variable, and then clearing that instead of deleting all the keys in localStorage.


Edit: As Lyn pointed out, you'll be good with localStorage.clear(). My previous points still stand, however.

print call stack in C or C++

Is there any way to dump the call stack in a running process in C or C++ every time a certain function is called?

No there is not, although platform-dependent solutions might exist.

Auto refresh page every 30 seconds

There are multiple solutions for this. If you want the page to be refreshed you actually don't need JavaScript, the browser can do it for you if you add this meta tag in your head tag.

<meta http-equiv="refresh" content="30">

The browser will then refresh the page every 30 seconds.

If you really want to do it with JavaScript, then you can refresh the page every 30 seconds with location.reload() (docs) inside a setTimeout():

window.setTimeout(function () {
  window.location.reload();
}, 30000);

If you don't need to refresh the whole page but only a part of it, I guess an Ajax call would be the most efficient way.

How to hide the soft keyboard from inside a fragment?

Use this:

Button loginBtn = view.findViewById(R.id.loginBtn);
loginBtn.setOnClickListener(new View.OnClickListener() {
   public void onClick(View v) {
      InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
      imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
   }
});

Convert from List into IEnumerable format

Why not use a Single liner ...

IEnumerable<Book> _Book_IE= _Book_List as IEnumerable<Book>;