Programs & Examples On #Radmenu

RadMenu is an ASP.NET based menu control by Telerik that provides many advanced functions.

Is it possible to create static classes in PHP (like in C#)?

object cannot be defined staticly but this works

final Class B{
  static $var;
  static function init(){
    self::$var = new A();
}
B::init();

what is Ljava.lang.String;@

According to the Java Virtual Machine Specification (Java SE 8), JVM §4.3.2. Field Descriptors:

FieldType term | Type      | Interpretation
-------------- | --------- | --------------
L ClassName ;  | reference | an instance of class ClassName
[              | reference | one array dimension
...            | ...       | ...

the expression [Ljava.lang.String;@45a877 means this is an array ( [ ) of class java.lang.String ( Ljava.lang.String; ). And @45a877 is the address where the String object is stored in memory.

IP to Location using Javascript

You can use this google service free IP geolocation webservice

update

the link is broken, I put here other link that include @NickSweeting in the comments:

ip-api.com

and you can get the data in json format:

http://ip-api.com/docs/api:json

Using an attribute of the current class instance as a default value for method's parameter

It's written as:

def my_function(self, param_one=None): # Or custom sentinel if None is vaild
    if param_one is None:
        param_one = self.one_of_the_vars

And I think it's safe to say that will never happen in Python due to the nature that self doesn't really exist until the function starts... (you can't reference it, in its own definition - like everything else)

For example: you can't do d = {'x': 3, 'y': d['x'] * 5}

Is it possible to have a multi-line comments in R?

CTRL+SHIFT+C in Eclipse + StatET and Rstudio.

Named parameters in JDBC

Plain vanilla JDBC does not support named parameters.

If you are using DB2 then using DB2 classes directly:

  1. Using named parameter markers with PreparedStatement objects
  2. Using named parameter markers with CallableStatement objects

Oracle PL/SQL - Raise User-Defined Exception With Custom SQLERRM

I usually lose track of all of my -20001-type error codes, so I try to consolidate all my application errors into a nice package like such:

SET SERVEROUTPUT ON

CREATE OR REPLACE PACKAGE errors AS
  invalid_foo_err EXCEPTION;
  invalid_foo_num NUMBER := -20123;
  invalid_foo_msg VARCHAR2(32767) := 'Invalid Foo!';
  PRAGMA EXCEPTION_INIT(invalid_foo_err, -20123);  -- can't use var >:O

  illegal_bar_err EXCEPTION;
  illegal_bar_num NUMBER := -20156;
  illegal_bar_msg VARCHAR2(32767) := 'Illegal Bar!';
  PRAGMA EXCEPTION_INIT(illegal_bar_err, -20156);  -- can't use var >:O

  PROCEDURE raise_err(p_err NUMBER, p_msg VARCHAR2 DEFAULT NULL);
END;
/

CREATE OR REPLACE PACKAGE BODY errors AS
  unknown_err EXCEPTION;
  unknown_num NUMBER := -20001;
  unknown_msg VARCHAR2(32767) := 'Unknown Error Specified!';

  PROCEDURE raise_err(p_err NUMBER, p_msg VARCHAR2 DEFAULT NULL) AS
    v_msg VARCHAR2(32767);
  BEGIN
    IF p_err = unknown_num THEN
      v_msg := unknown_msg;
    ELSIF p_err = invalid_foo_num THEN
      v_msg := invalid_foo_msg;
    ELSIF p_err = illegal_bar_num THEN
      v_msg := illegal_bar_msg;
    ELSE
      raise_err(unknown_num, 'USR' || p_err || ': ' || p_msg);
    END IF;

    IF p_msg IS NOT NULL THEN
      v_msg := v_msg || ' - '||p_msg;
    END IF;

    RAISE_APPLICATION_ERROR(p_err, v_msg);
  END;
END;
/

Then call errors.raise_err(errors.invalid_foo_num, 'optional extra text') to use it, like such:

BEGIN
  BEGIN
    errors.raise_err(errors.invalid_foo_num, 'Insufficient Foo-age!');
  EXCEPTION
    WHEN errors.invalid_foo_err THEN
      dbms_output.put_line(SQLERRM);
  END;

  BEGIN
    errors.raise_err(errors.illegal_bar_num, 'Insufficient Bar-age!');
  EXCEPTION
    WHEN errors.illegal_bar_err THEN
      dbms_output.put_line(SQLERRM);
  END;

  BEGIN
    errors.raise_err(-10000, 'This Doesn''t Exist!!');
  EXCEPTION
    WHEN OTHERS THEN
      dbms_output.put_line(SQLERRM);
  END;
END;
/

produces this output:

ORA-20123: Invalid Foo! - Insufficient Foo-age!
ORA-20156: Illegal Bar! - Insufficient Bar-age!
ORA-20001: Unknown Error Specified! - USR-10000: This Doesn't Exist!!

How to return HTTP 500 from ASP.NET Core RC2 Web Api?

How about creating a custom ObjectResult class that represents an Internal Server Error like the one for OkObjectResult? You can put a simple method in your own base class so that you can easily generate the InternalServerError and return it just like you do Ok() or BadRequest().

[Route("api/[controller]")]
[ApiController]
public class MyController : MyControllerBase
{
    [HttpGet]
    [Route("{key}")]
    public IActionResult Get(int key)
    {
        try
        {
            //do something that fails
        }
        catch (Exception e)
        {
            LogException(e);
            return InternalServerError();
        }
    }
}

public class MyControllerBase : ControllerBase
{
    public InternalServerErrorObjectResult InternalServerError()
    {
        return new InternalServerErrorObjectResult();
    }

    public InternalServerErrorObjectResult InternalServerError(object value)
    {
        return new InternalServerErrorObjectResult(value);
    }
}

public class InternalServerErrorObjectResult : ObjectResult
{
    public InternalServerErrorObjectResult(object value) : base(value)
    {
        StatusCode = StatusCodes.Status500InternalServerError;
    }

    public InternalServerErrorObjectResult() : this(null)
    {
        StatusCode = StatusCodes.Status500InternalServerError;
    }
}

What's the difference between "end" and "exit sub" in VBA?

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don't perform the same task.

End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can't be called in the same way Exit Sub can be, because the compiler doesn't allow it.

enter image description here

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
Terminates the definition of this procedure.

Passing string to a function in C - with or without pointers?

The accepted convention of passing C-strings to functions is to use a pointer:

void function(char* name)

When the function modifies the string you should also pass in the length:

void function(char* name, size_t name_length)

Your first example:

char *functionname(char *string name[256])

passes an array of pointers to strings which is not what you need at all.

Your second example:

char functionname(char string[256])

passes an array of chars. The size of the array here doesn't matter and the parameter will decay to a pointer anyway, so this is equivalent to:

char functionname(char *string)

See also this question for more details on array arguments in C.

How to do SELECT MAX in Django?

See this. Your code would be something like the following:

from django.db.models import Max
# Generates a "SELECT MAX..." query
Argument.objects.aggregate(Max('rating')) # {'rating__max': 5}

You can also use this on existing querysets:

from django.db.models import Max
args = Argument.objects.filter(name='foo') # or whatever arbitrary queryset
args.aggregate(Max('rating')) # {'rating__max': 5}

If you need the model instance that contains this max value, then the code you posted is probably the best way to do it:

arg = args.order_by('-rating')[0]

Note that this will error if the queryset is empty, i.e. if no arguments match the query (because the [0] part will raise an IndexError). If you want to avoid that behavior and instead simply return None in that case, use .first():

arg = args.order_by('-rating').first() # may return None

Has been compiled by a more recent version of the Java Runtime (class file version 57.0)

The problem is that you compiled the code with java 13 (class file 57), and the java runtime is set to java 8 (class file 52).

Assuming you have the JRE 13 installed in your local system, you could change your runtime from 52 to 57. That you can do with the plugin Choose Runtime. To install it go to File/Settings/Plugins

enter image description here

Once installed go to Help/Find Action, type "runtime" and select the jre 13 from the dropdown menu.

enter image description here

Factorial in numpy and scipy

You can save some homemade factorial functions on a separate module, utils.py, and then import them and compare the performance with the predefinite one, in scipy, numpy and math using timeit. In this case I used as external method the last proposed by Stefan Gruenwald:

import numpy as np


def factorial(n):
    return reduce((lambda x,y: x*y),range(1,n+1))

Main code (I used a framework proposed by JoshAdel in another post, look for how-can-i-get-an-array-of-alternating-values-in-python):

from timeit import Timer
from utils import factorial
import scipy

    n = 100

    # test the time for the factorial function obtained in different ways:

    if __name__ == '__main__':

        setupstr="""
    import scipy, numpy, math
    from utils import factorial
    n = 100
    """

        method1="""
    factorial(n)
    """

        method2="""
    scipy.math.factorial(n)  # same algo as numpy.math.factorial, math.factorial
    """

        nl = 1000
        t1 = Timer(method1, setupstr).timeit(nl)
        t2 = Timer(method2, setupstr).timeit(nl)

        print 'method1', t1
        print 'method2', t2

        print factorial(n)
        print scipy.math.factorial(n)

Which provides:

method1 0.0195569992065
method2 0.00638914108276

93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000


Process finished with exit code 0

Which loop is faster, while or for?

Set the loop iterations to 10,000.

Find the time in milliseconds>Run Loop>find time in milliseconds and subtract the first timer.

Do it for both codes, what ever one has the lowest milliseconds it runs faster. You might want to run the test multiple times and average them out to reduce the likelihood of background processes influencing the test.

You are likely to get really similar times on both of them, but I am interested to see if one is always just slightly faster.

Loading basic HTML in Node.js

I just found one way using the fs library. I'm not certain if it's the cleanest though.

var http = require('http'),
    fs = require('fs');


fs.readFile('./index.html', function (err, html) {
    if (err) {
        throw err; 
    }       
    http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        response.end();  
    }).listen(8000);
});

The basic concept is just raw file reading and dumping the contents. Still open to cleaner options, though!

Build query string for System.Net.HttpClient get

I couldn't find a better solution than creating a extension method to convert a Dictionary to QueryStringFormat. The solution proposed by Waleed A.K. is good as well.

Follow my solution:

Create the extension method:

public static class DictionaryExt
{
    public static string ToQueryString<TKey, TValue>(this Dictionary<TKey, TValue> dictionary)
    {
        return ToQueryString<TKey, TValue>(dictionary, "?");
    }

    public static string ToQueryString<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, string startupDelimiter)
    {
        string result = string.Empty;
        foreach (var item in dictionary)
        {
            if (string.IsNullOrEmpty(result))
                result += startupDelimiter; // "?";
            else
                result += "&";

            result += string.Format("{0}={1}", item.Key, item.Value);
        }
        return result;
    }
}

And them:

var param = new Dictionary<string, string>
          {
            { "param1", "value1" },
            { "param2", "value2" },
          };
param.ToQueryString(); //By default will add (?) question mark at begining
//"?param1=value1&param2=value2"
param.ToQueryString("&"); //Will add (&)
//"&param1=value1&param2=value2"
param.ToQueryString(""); //Won't add anything
//"param1=value1&param2=value2"

css absolute position won't work with margin-left:auto margin-right: auto

Working JSFiddle below. When using position absolute, margin: 0 auto will not work, but you can do like this (will also scale):

left: 50%;
transform: translateX(-50%);

Update: Working JSFiddle

How to specify the default error page in web.xml?

You can also do something like that:

<error-page>
    <error-code>403</error-code>
    <location>/403.html</location>
</error-page>

<error-page>
    <location>/error.html</location>
</error-page>

For error code 403 it will return the page 403.html, and for any other error code it will return the page error.html.

Jquery sortable 'change' event element position

UPDATED: 26/08/2016 to use the latest jquery and jquery ui version plus bootstrap to style it.

$(function() {
    $('#sortable').sortable({
        start: function(event, ui) {
            var start_pos = ui.item.index();
            ui.item.data('start_pos', start_pos);
        },
        change: function(event, ui) {
            var start_pos = ui.item.data('start_pos');
            var index = ui.placeholder.index();
            if (start_pos < index) {
                $('#sortable li:nth-child(' + index + ')').addClass('highlights');
            } else {
                $('#sortable li:eq(' + (index + 1) + ')').addClass('highlights');
            }
        },
        update: function(event, ui) {
            $('#sortable li').removeClass('highlights');
        }
    });
});

Working with dictionaries/lists in R

To extend a little bit answer of Calimo I present few more things you may find useful while creating this quasi dictionaries in R:

a) how to return all the VALUES of the dictionary:

>as.numeric(foo)
[1] 12 22 33

b) check whether dictionary CONTAINS KEY:

>'tic' %in% names(foo)
[1] TRUE

c) how to ADD NEW key, value pair to dictionary:

c(foo,tic2=44)

results:

tic       tac       toe     tic2
12        22        33        44 

d) how to fulfill the requirement of REAL DICTIONARY - that keys CANNOT repeat(UNIQUE KEYS)? You need to combine b) and c) and build function which validates whether there is such key, and do what you want: e.g don't allow insertion, update value if the new differs from the old one, or rebuild somehow key(e.g adds some number to it so it is unique)

e) how to DELETE pair BY KEY from dictionary:

foo<-foo[which(foo!=foo[["tac"]])]

How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

If you are using ES6 you can:

var sample = [1, 2, 3]

var result = sample.filter(elem => elem !== 2)

/* output */
[1, 3]

Also take notice filter does not update the existing array it will return a new filtered array every time.

Automatically create an Enum based on values in a database lookup table?

enum builder class

public class XEnum
{
    private EnumBuilder enumBuilder;
    private int index;
    private AssemblyBuilder _ab;
    private AssemblyName _name;
    public XEnum(string enumname)
    {
        AppDomain currentDomain = AppDomain.CurrentDomain;
        _name = new AssemblyName("MyAssembly");
        _ab = currentDomain.DefineDynamicAssembly(
            _name, AssemblyBuilderAccess.RunAndSave);

        ModuleBuilder mb = _ab.DefineDynamicModule("MyModule");

        enumBuilder = mb.DefineEnum(enumname, TypeAttributes.Public, typeof(int));


    }
    /// <summary>
    /// adding one string to enum
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public FieldBuilder add(string s)
    {
        FieldBuilder f = enumBuilder.DefineLiteral(s, index);
        index++;
        return f;
    }
    /// <summary>
    /// adding array to enum
    /// </summary>
    /// <param name="s"></param>
    public void addRange(string[] s)
    {
        for (int i = 0; i < s.Length; i++)
        {
            enumBuilder.DefineLiteral(s[i], i);
        }
    }
    /// <summary>
    /// getting index 0
    /// </summary>
    /// <returns></returns>
    public object getEnum()
    {
        Type finished = enumBuilder.CreateType();
        _ab.Save(_name.Name + ".dll");
        Object o1 = Enum.Parse(finished, "0");
        return o1;
    }
    /// <summary>
    /// getting with index
    /// </summary>
    /// <param name="i"></param>
    /// <returns></returns>
    public object getEnum(int i)
    {
        Type finished = enumBuilder.CreateType();
        _ab.Save(_name.Name + ".dll");
        Object o1 = Enum.Parse(finished, i.ToString());
        return o1;
    }
}

create an object

string[] types = { "String", "Boolean", "Int32", "Enum", "Point", "Thickness", "long", "float" };
XEnum xe = new XEnum("Enum");
        xe.addRange(types);
        return xe.getEnum();

Handling NULL values in Hive

Try to include length > 0 as well.

column1 is not NULL AND column1 <> '' AND length(column1) > 0 

Hadoop cluster setup - java.net.ConnectException: Connection refused

Make sure HDFS is online. Start it by $HADOOP_HOME/sbin/start-dfs.sh Once you do that, your test with telnet localhost 9001should work.

What is the difference between HTTP and REST?

As I understand it, REST enforces the use of the available HTTP commands as they were meant to be used.

For example, I could do:

GET
http://example.com?method=delete&item=xxx

But with rest I would use the "DELETE" request method, removing the need for the "method" query param

DELETE
http://example.com?item=xxx

Bootstrap get div to align in the center

When I align elements in center I use the bootstrap class text-center:

<div class="text-center">Centered content goes here</div>

changing permission for files and folder recursively using shell command in mac

I do not have a Mac OSx machine to test this on but in bash on Linux I use something like the following to chmod only directories:

find . -type d -exec chmod 755 {} \+

but this also does the same thing:

chmod 755 `find . -type d`

and so does this:

chmod 755 $(find . -type d)

The last two are using different forms of subcommands. The first is using backticks (older and depreciated) and the other the $() subcommand syntax.

So I think in your case that the following will do what you want.

chmod 777 $(find "/Users/Test/Desktop/PATH")

symfony 2 No route found for "GET /"

I have also tried that error , I got it right by just adding /hello/any name because it is path that there must be an hello/name

example : instead of just putting http://localhost/app_dev.php

put it like this way http://localhost/name_of_your_project/web/app_dev.php/hello/ai

it will display Hello Ai . I hope I answer your question.

How can I right-align text in a DataGridView column?

I know this is old, but for those surfing this question, the answer by MUG4N will align all columns that use the same defaultcellstyle. I'm not using autogeneratecolumns so that is not acceptable. Instead I used:

e.Column.DefaultCellStyle = new DataGridViewCellStyle(e.Column.DefaultCellStyle);
e.Column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

In this case e is from:

Grd_ColumnAdded(object sender, DataGridViewColumnEventArgs e)  

How to submit a form with JavaScript by clicking a link?

document.getElementById("theForm").submit();

It works perfect in my case.

you can use it in function also like,

function submitForm()
{
     document.getElementById("theForm").submit();
} 

Set "theForm" as your form ID. It's done.

React Error: Target Container is not a DOM Element

For those that implemented react js in some part of the website and encounter this issue. Just add a condition to check if the element exist on that page before you render the react component.

<div id="element"></div>

...

const someElement = document.getElementById("element")
    
if(someElement) {
  ReactDOM.render(<Yourcomponent />, someElement)
}

MISCONF Redis is configured to save RDB snapshots

Thanks everyone for checking the problem, apparently the error was produced during bgsave.

For me, typing config set stop-writes-on-bgsave-error no in a shell and restarting Redis solved the problem.

Why do we assign a parent reference to the child object in Java?

This situation happens when you have several implementations. Let me explain. Supppose you have several sorting algorithm and you want to choose at runtime the one to implement, or you want to give to someone else the capability to add his implementation. To solve this problem you usually create an abstract class (Parent) and have different implementation (Child). If you write:

Child c = new Child();

you bind your implementation to Child class and you can't change it anymore. Otherwise if you use:

Parent p = new Child();

as long as Child extends Parent you can change it in the future without modifying the code.

The same thing can be done using interfaces: Parent isn't anymore a class but a java Interface.

In general you can use this approch in DAO pattern where you want to have several DB dependent implementations. You can give a look at FactoryPatter or AbstractFactory Pattern. Hope this can help you.

node.js remove file

Here is a small snippet of I made for this purpose,

var fs = require('fs');
var gutil = require('gulp-util');

fs.exists('./www/index.html', function(exists) {
  if(exists) {
    //Show in green
    console.log(gutil.colors.green('File exists. Deleting now ...'));
    fs.unlink('./www/index.html');
  } else {
    //Show in red
    console.log(gutil.colors.red('File not found, so not deleting.'));
  }
});

Convert String to java.util.Date

I think your date format does not make sense. There is no 13:00 PM. Remove the "aaa" at the end of your format or turn the HH into hh.

Nevertheless, this works fine for me:

String testDate = "29-Apr-2010,13:00:14 PM";
DateFormat formatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa");
Date date = formatter.parse(testDate);
System.out.println(date);

It prints "Thu Apr 29 13:00:14 CEST 2010".

Remove a file from the list that will be committed

if you have already pushed your commit then. do

git checkout origin/<remote-branch> <filename>
git commit --amend

AND If you have not pushed the changes on the server you can use

git reset --soft HEAD~1

How can I check if a date is the same day as datetime.today()?

You can set the hours, minutes, seconds and microseconds to whatever you like

datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)

but trutheality's answer is probably best when they are all to be zero and you can just compare the .date()s of the times

Maybe it is faster though if you have to compare hundreds of datetimes because you only need to do the replace() once vs hundreds of calls to date()

C# 'or' operator?

just like in C and C++, the boolean or operator is ||

if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
{
    // Do stuff here
}

How to add DOM element script to head section?

try this

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'url';    

document.getElementsByTagName('head')[0].appendChild(script);

How to save a Python interactive session?

The %history command is awesome, but unfortunately it won't let you save things that were %paste 'd into the sesh. To do that I think you have to do %logstart at the beginning (although I haven't confirmed this works).

What I like to do is

%history -o -n -p -f filename.txt

which will save the output, line numbers, and '>>>' before each input (o, n, and p options). See the docs for %history here.

jquery, selector for class within id

I think your asking to select only <span class = "my_class">hello</span> this element, You have do like this, If I am understand your question correctly this is the answer,

$("#my_id [class='my_class']").addClass('test');

DEMO

PHP preg_replace special characters

$newstr = preg_replace('/[^a-zA-Z0-9\']/', '_', "There wouldn't be any");
$newstr = str_replace("'", '', $newstr);

I put them on two separate lines to make the code a little more clear.

Note: If you're looking for Unicode support, see Filip's answer below. It will match all characters that register as letters in addition to A-z.

pip or pip3 to install packages for Python 3?

Given an activated Python 3.6 virtualenv in somepath/venv, the following aliases resolved the various issues on a macOS Sierra where pip insisted on pointing to Apple's 2.7 Python.

alias pip='python somepath/venv/lib/python3.6/site-packages/pip/__main__.py'

This didn't work so well when I had to do sudo pip as the root user doesn't know anything about my alias or the virtualenv, so I had to add an extra alias to handle this as well. It's a hack, but it works, and I know what it does:

alias sudopip='sudo somepath/venv/bin/python somepath/venv/lib/python3.6/site-packages/pip/__main__.py'

background:

pip3 did not exist to start (command not found) with and which pip would return /opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin/pip, the Apple Python.

Python 3.6 was installed via macports.

After activation of the 3.6 virtualenv I wanted to work with, which python would return somepath/venv/bin/python

Somehow pip install would do the right thing and hit my virtualenv, but pip list would rattle off Python 2.7 packages.

For Python, this is batting way beneath my expectations in terms of beginner-friendliness.

rsync copy over only certain types of files using include option

Here's the important part from the man page:

As the list of files/directories to transfer is built, rsync checks each name to be transferred against the list of include/exclude patterns in turn, and the first matching pattern is acted on: if it is an exclude pattern, then that file is skipped; if it is an include pattern then that filename is not skipped; if no matching pattern is found, then the filename is not skipped.

To summarize:

  • Not matching any pattern means a file will be copied!
  • The algorithm quits once any pattern matches

Also, something ending with a slash is matching directories (like find -type d would).

Let's pull apart this answer from above.

rsync -zarv  --prune-empty-dirs --include "*/"  --include="*.sh" --exclude="*" "$from" "$to"
  1. Don't skip any directories
  2. Don't skip any .sh files
  3. Skip everything
  4. (Implicitly, don't skip anything, but the rule above prevents the default rule from ever happening.)

Finally, the --prune-empty-directories keeps the first rule from making empty directories all over the place.

How to convert a Map to List in Java?

// you can use this
List<Value> list = new ArrayList<Value>(map.values());

// or you may use 
List<Value> list = new ArrayList<Value>();
for (Map.Entry<String, String> entry : map.entrySet())
{
list.add(entry.getValue());    
}

How do I convert hex to decimal in Python?

If by "hex data" you mean a string of the form

s = "6a48f82d8e828ce82b82"

you can use

i = int(s, 16)

to convert it to an integer and

str(i)

to convert it to a decimal string.

Violation Long running JavaScript task took xx ms

Adding my insights here as this thread was the "go to" stackoverflow question on the topic.

My problem was in a Material-UI app (early stages)

  • placement of custom Theme provider was the cause

when I did some calculations forcing rendering of the page (one component, "display results", depends on what is set in others, "input sections").

Everything was fine until I updated the "state" that forces the "results component" to rerender. The main issue here was that I had a material-ui theme (https://material-ui.com/customization/theming/#a-note-on-performance) in the same renderer (App.js / return.. ) as the "results component", SummaryAppBarPure

Solution was to lift the ThemeProvider one level up (Index.js), and wrapping the App component here, thus not forcing the ThemeProvider to recalculate and draw / layout / reflow.

before

in App.js:

  return (
    <>
      <MyThemeProvider>
      <Container className={classes.appMaxWidth}>

        <SummaryAppBarPure
//...

in index.js

ReactDOM.render(
  <React.StrictMode>
      <App />
//...

after

in App.js:

return (
    <>
      {/* move theme to index. made reflow problem go away */}
      {/* <MyThemeProvider> */}
      <Container className={classes.appMaxWidth}>

        <SummaryAppBarPure
//...

in index.js

ReactDOM.render(
  <React.StrictMode>
    <MyThemeProvider>
      <App />
//...

How to use Scanner to accept only valid int as input

What you could do is also to take the next token as a String, converts this string to a char array and test that each character in the array is a digit.

I think that's correct, if you don't want to deal with the exceptions.

Read the current full URL with React?

this.props.location is a react-router feature, you'll have to install if you want to use it.

Note: doesn't return the full url.

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel

Ok, finally got it.

Change this line in %windir%\System32\inetsrv\Config\ApplicationHost.config

<add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />

To

<add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler,runtimeVersionv2.0" />

If this is not enough

Add this following line to the Web.config

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>

How do I enable the column selection mode in Eclipse?

As RichieHindle pointed out the shortcut for column (block) selection is Alt+Shift+A. The problem I ran into is that the Android SDK on Eclipse uses 3 shortcuts that all start with Alt+Shift+A, so if you type that, you'll be given a choice of continuing with D, S, or R.

To solve this I redefined the column selection as Alt+Shift+A,A (Alt, Shift, A pressed together and then followed by a subsequent A). To do this go to Windows > Preferences then type keys or navigate to General > Keys. Under the Keys enter the filter text of block selection to quickly find the shortcut listing for toggle block selection. Here you can adjust the shortcut for column selection as you wish.

How to replace spaces in file names using a bash script

This only finds files inside the current directory and renames them. I have this aliased.

find ./ -name "* *" -type f -d 1 | perl -ple '$file = $_; $file =~ s/\s+/_/g; rename($_, $file);

Multiple "style" attributes in a "span" tag: what's supposed to happen?

Separate your rules with a semi colon in a single declaration:

<span style="color:blue;font-style:italic">Test</span>

Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

Based on answers of neeraj t and Everton Fernandes Rosario I wrote in Kotlin, where password is an id of an EditText in your layout.

// Show passwords' symbols.
private fun showPassword() {
    password.run {
        val cursorPosition = selectionStart
        transformationMethod = HideReturnsTransformationMethod.getInstance()
        setSelection(cursorPosition)
    }
}

// Show asterisks.
private fun hidePassword() {
    password.run {
        val cursorPosition = selectionStart
        transformationMethod = PasswordTransformationMethod.getInstance()
        setSelection(cursorPosition)
    }
}

How to install PyQt5 on Windows?

easiest way, I think download Eric, unzip go to sources, open python directory, drag the install script into the python icon, not folder, follow prompts

How can I list ALL DNS records?

For Windows:

You may find the need to check the status of your domains DNS records, or check the Name Servers to see which records the servers are pulling.

  1. Launch Windows Command Prompt by navigating to Start > Command Prompt or via Run > CMD.

  2. Type NSLOOKUP and hit Enter. The default Server is set to your local DNS, the Address will be your local IP.

  3. Set the DNS Record type you wish to lookup by typing set type=## where ## is the record type, then hit Enter. You may use ANY, A, AAAA, A+AAAA, CNAME, MX, NS, PTR, SOA, or SRV as the record type.

  4. Now enter the domain name you wish to query then hit Enter.. In this example, we will use Managed.com.

  5. NSLOOKUP will now return the record entries for the domain you entered.

  6. You can also change the Name Servers which you are querying. This is useful if you are checking the records before DNS has fully propagated. To change the Name Server type server [name server]. Replace [name server] with the Name Servers you wish to use. In this example, we will set these as NSA.managed.com.

  7. Once changed, change the query type (Step 3) if needed then enter new a new domain (Step 4.)

For Linux:

1) Check DNS Records Using Dig Command Dig stands for domain information groper is a flexible tool for interrogating DNS name servers. It performs DNS lookups and displays the answers that are returned from the name server(s) that were queried. Most DNS administrators use dig to troubleshoot DNS problems because of its flexibility, ease of use and clarity of output. Other lookup tools tend to have less functionality than dig.

2) Check DNS Records Using NSlookup Command Nslookup is a program to query Internet domain name servers. Nslookup has two modes interactive and non-interactive.

Interactive mode allows the user to query name servers for information about various hosts and domains or to print a list of hosts in a domain.

Non-interactive mode is used to print just the name and requested information for a host or domain. It’s network administration tool which will help them to check and troubleshoot DNS related issues.

3) Check DNS Records Using Host Command host is a simple utility for performing DNS lookups. It is normally used to convert names to IP addresses and vice versa. When no arguments or options are given, host prints a short summary of its command line arguments and options.

Copy filtered data to another sheet using VBA

When i need to copy data from filtered table i use range.SpecialCells(xlCellTypeVisible).copy. Where the range is range of all data (without a filter).

Example:

Sub copy()
     'source worksheet
     dim ws as Worksheet
     set ws = Application.Worksheets("Data")' set you source worksheet here
     dim data_end_row_number as Integer
     data_end_row_number = ws.Range("B3").End(XlDown).Row.Number
    'enable filter
    ws.Range("B2:F2").AutoFilter Field:=2, Criteria1:="hockey", VisibleDropDown:=True
    ws.Range("B3:F" & data_end_row_number).SpecialCells(xlCellTypeVisible).Copy
    Application.Worksheets("Hoky").Range("B3").Paste
    'You have to add headers to Hoky worksheet
end sub

Execution time of C program

(All answers here are lacking, if your sysadmin changes the systemtime, or your timezone has differing winter- and sommer-times. Therefore...)

On linux use: clock_gettime(CLOCK_MONOTONIC_RAW, &time_variable); It's not affected if the system-admin changes the time, or you live in a country with winter-time different from summer-time, etc.

#include <stdio.h>
#include <time.h>

#include <unistd.h> /* for sleep() */

int main() {
    struct timespec begin, end;
    clock_gettime(CLOCK_MONOTONIC_RAW, &begin);

    sleep(1);      // waste some time

    clock_gettime(CLOCK_MONOTONIC_RAW, &end);

    printf ("Total time = %f seconds\n",
            (end.tv_nsec - begin.tv_nsec) / 1000000000.0 +
            (end.tv_sec  - begin.tv_sec));

}

man clock_gettime states:

CLOCK_MONOTONIC
              Clock  that  cannot  be set and represents monotonic time since some unspecified starting point.  This clock is not affected by discontinuous jumps in the system time
              (e.g., if the system administrator manually changes the clock), but is affected by the incremental adjustments performed by adjtime(3) and NTP.

Show image using file_get_contents

you can do like this :

<?php
    $file = 'your_images.jpg';

    header('Content-Type: image/jpeg');
    header('Content-Length: ' . filesize($file));
    echo file_get_contents($file);
?>

converting epoch time with milliseconds to datetime

Use datetime.datetime.fromtimestamp:

>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'

%f directive is only supported by datetime.datetime.strftime, not by time.strftime.

UPDATE Alternative using %, str.format:

>>> import time
>>> s, ms = divmod(1236472051807, 1000)  # (1236472051, 807)
>>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
>>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'

Switch/toggle div (jQuery)

Use this:

<script type="text/javascript" language="javascript">
    $("#toggle").click(function() { $("#login-form, #recover-password").toggle(); });
</script>

Your HTML should look like:

<a id="toggle" href="javascript:void(0);">forgot password?</a>
<div id="login-form"></div>
<div id="recover-password" style="display:none;"></div>

Hey, all right! One line! I <3 jQuery.

How can I get my webapp's base URL in ASP.NET MVC?

This works fine for me (also with a load balancer):

@{
    var urlHelper = new UrlHelper(Html.ViewContext.RequestContext);
    var baseurl = urlHelper.Content(“~”);
}

<script>
    var base_url = "@baseurl";
</script>

Especially if you are using non-standard port numbers, using Request.Url.Authority appears like a good lead at first, but fails in a LB environment.

Qt: How do I handle the event of the user pressing the 'X' (close) button?

also you can reimplement protected member QWidget::closeEvent()

void YourWidgetWithXButton::closeEvent(QCloseEvent *event)
{
    // do what you need here
    // then call parent's procedure
    QWidget::closeEvent(event);
}

C++ "Access violation reading location" Error

You haven't posted the findvertex method, but Access Reading Violation with an offset like 0x00000048 means that the Vertex* f; in your getCost function is receiving null, and when trying to access the member adj in the null Vertex pointer (that is, in f), it is offsetting to adj (in this case, 72 bytes ( 0x48 bytes in decimal )), it's reading near the 0 or null memory address.

Doing a read like this violates Operating-System protected memory, and more importantly means whatever you're pointing at isn't a valid pointer. Make sure findvertex isn't returning null, or do a comparisong for null on f before using it to keep yourself sane (or use an assert):

assert( f != null ); // A good sanity check

EDIT:

If you have a map for doing something like a find, you can just use the map's find method to make sure the vertex exists:

Vertex* Graph::findvertex(string s)
{
    vmap::iterator itr = map1.find( s );
    if ( itr == map1.end() )
    {
        return NULL;
    }
    return itr->second;
}

Just make sure you're still careful to handle the error case where it does return NULL. Otherwise, you'll keep getting this access violation.

Rotating a Vector in 3D Space

If you want to rotate a vector you should construct what is known as a rotation matrix.

Rotation in 2D

Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are

    x' = x cos ? - y sin ?
    y' = x sin ? + y cos ?

To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider

    Unit vector along X axis = <1, 0>
    x' = 1 cos 90 - 0 sin 90 = 0
    y' = 1 sin 90 + 0 cos 90 = 1
    New coordinates of the vector, <x', y'> = <0, 1>  ?  Y-axis

When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is

    |cos ?   -sin ?| |x| = |x cos ? - y sin ?| = |x'|
    |sin ?    cos ?| |y|   |x sin ? + y cos ?|   |y'|

Rotation in 3D

That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be

    |cos ?   -sin ?   0| |x|   |x cos ? - y sin ?|   |x'|
    |sin ?    cos ?   0| |y| = |x sin ? + y cos ?| = |y'|
    |  0       0      1| |z|   |        z        |   |z'|

around the Y-axis would be

    | cos ?    0   sin ?| |x|   | x cos ? + z sin ?|   |x'|
    |   0      1       0| |y| = |         y        | = |y'|
    |-sin ?    0   cos ?| |z|   |-x sin ? + z cos ?|   |z'|

around the X-axis would be

    |1     0           0| |x|   |        x        |   |x'|
    |0   cos ?    -sin ?| |y| = |y cos ? - z sin ?| = |y'|
    |0   sin ?     cos ?| |z|   |y sin ? + z cos ?|   |z'|

Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.

Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.

I hope this clarifies basic rotation.

Rotation not Revolution

The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.

Composition

I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).

Rotation around Arbitrary Vector

A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.

How to execute an SSIS package from .NET?

You can use this Function if you have some variable in the SSIS.

    Package pkg;

    Microsoft.SqlServer.Dts.Runtime.Application app;
    DTSExecResult pkgResults;
    Variables vars;

    app = new Microsoft.SqlServer.Dts.Runtime.Application();
    pkg = app.LoadPackage(" Location of your SSIS package", null);

    vars = pkg.Variables;

    // your variables
    vars["somevariable1"].Value = "yourvariable1";
    vars["somevariable2"].Value = "yourvariable2";

    pkgResults = pkg.Execute(null, vars, null, null, null);

    if (pkgResults == DTSExecResult.Success)
    {
        Console.WriteLine("Package ran successfully");
    }
    else
    {

        Console.WriteLine("Package failed");
    }

How do I make an HTTP request in Swift?

Basic Swift 3+ Solution

guard let url = URL(string: "http://www.stackoverflow.com") else { return }

let task = URLSession.shared.dataTask(with: url) { data, response, error in

  guard let data = data, error == nil else { return }

  print(NSString(data: data, encoding: String.Encoding.utf8.rawValue))
}

task.resume()

Why does instanceof return false for some literals?

For me the confusion caused by

"str".__proto__ // #1
=> String

So "str" istanceof String should return true because how istanceof works as below:

"str".__proto__ == String.prototype // #2
=> true

Results of expression #1 and #2 conflict each other, so there should be one of them wrong.

#1 is wrong

I figure out that it caused by the __proto__ is non standard property, so use the standard one:Object.getPrototypeOf

Object.getPrototypeOf("str") // #3
=> TypeError: Object.getPrototypeOf called on non-object

Now there's no confusion between expression #2 and #3

Installing pip packages to $HOME folder

You can specify the -t option (--target) to specify the destination directory. See pip install --help for detailed information. This is the command you need:

pip install -t path_to_your_home package-name

for example, for installing say mxnet, in my $HOME directory, I type:

pip install -t /home/foivos/ mxnet

How to run an EXE file in PowerShell with parameters with spaces and quotes

An alternative answer is to use a Base64 encoded command switch:

powershell -EncodedCommand "QwA6AFwAUAByAG8AZwByAGEAbQAgAEYAaQBsAGUAcwBcAEkASQBTAFwATQBpAGMAcgBvAHMAbwBmAHQAIABXAGUAYgAgAEQAZQBwAGwAbwB5AFwAbQBzAGQAZQBwAGwAbwB5AC4AZQB4AGUAIAAtAHYAZQByAGIAOgBzAHkAbgBjACAALQBzAG8AdQByAGMAZQA6AGQAYgBmAHUAbABsAHMAcQBsAD0AIgBEAGEAdABhACAAUwBvAHUAcgBjAGUAPQBtAHkAcwBvAHUAcgBjAGUAOwBJAG4AdABlAGcAcgBhAHQAZQBkACAAUwBlAGMAdQByAGkAdAB5AD0AZgBhAGwAcwBlADsAVQBzAGUAcgAgAEkARAA9AHMAYQA7AFAAdwBkAD0AcwBhAHAAYQBzAHMAIQA7AEQAYQB0AGEAYgBhAHMAZQA9AG0AeQBkAGIAOwAiACAALQBkAGUAcwB0ADoAZABiAGYAdQBsAGwAcwBxAGwAPQAiAEQAYQB0AGEAIABTAG8AdQByAGMAZQA9AC4AXABtAHkAZABlAHMAdABzAG8AdQByAGMAZQA7AEkAbgB0AGUAZwByAGEAdABlAGQAIABTAGUAYwB1AHIAaQB0AHkAPQBmAGEAbABzAGUAOwBVAHMAZQByACAASQBEAD0AcwBhADsAUAB3AGQAPQBzAGEAcABhAHMAcwAhADsARABhAHQAYQBiAGEAcwBlAD0AbQB5AGQAYgA7ACIALABjAG8AbQBwAHUAdABlAHIAbgBhAG0AZQA9ADEAMAAuADEAMAAuADEAMAAuADEAMAAsAHUAcwBlAHIAbgBhAG0AZQA9AGEAZABtAGkAbgBpAHMAdAByAGEAdABvAHIALABwAGEAcwBzAHcAbwByAGQAPQBhAGQAbQBpAG4AcABhAHMAcwAiAA=="

When decoded, you'll see it's the OP's original snippet with all arguments and double quotes preserved.

powershell.exe -EncodedCommand

Accepts a base-64-encoded string version of a command. Use this parameter
to submit commands to Windows PowerShell that require complex quotation
marks or curly braces.

The original command:

 C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe -verb:sync -source:dbfullsql="Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;" -dest:dbfullsql="Data Source=.\mydestsource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;",computername=10.10.10.10,username=administrator,password=adminpass"

It turns into this when encoded as Base64:

QwA6AFwAUAByAG8AZwByAGEAbQAgAEYAaQBsAGUAcwBcAEkASQBTAFwATQBpAGMAcgBvAHMAbwBmAHQAIABXAGUAYgAgAEQAZQBwAGwAbwB5AFwAbQBzAGQAZQBwAGwAbwB5AC4AZQB4AGUAIAAtAHYAZQByAGIAOgBzAHkAbgBjACAALQBzAG8AdQByAGMAZQA6AGQAYgBmAHUAbABsAHMAcQBsAD0AIgBEAGEAdABhACAAUwBvAHUAcgBjAGUAPQBtAHkAcwBvAHUAcgBjAGUAOwBJAG4AdABlAGcAcgBhAHQAZQBkACAAUwBlAGMAdQByAGkAdAB5AD0AZgBhAGwAcwBlADsAVQBzAGUAcgAgAEkARAA9AHMAYQA7AFAAdwBkAD0AcwBhAHAAYQBzAHMAIQA7AEQAYQB0AGEAYgBhAHMAZQA9AG0AeQBkAGIAOwAiACAALQBkAGUAcwB0ADoAZABiAGYAdQBsAGwAcwBxAGwAPQAiAEQAYQB0AGEAIABTAG8AdQByAGMAZQA9AC4AXABtAHkAZABlAHMAdABzAG8AdQByAGMAZQA7AEkAbgB0AGUAZwByAGEAdABlAGQAIABTAGUAYwB1AHIAaQB0AHkAPQBmAGEAbABzAGUAOwBVAHMAZQByACAASQBEAD0AcwBhADsAUAB3AGQAPQBzAGEAcABhAHMAcwAhADsARABhAHQAYQBiAGEAcwBlAD0AbQB5AGQAYgA7ACIALABjAG8AbQBwAHUAdABlAHIAbgBhAG0AZQA9ADEAMAAuADEAMAAuADEAMAAuADEAMAAsAHUAcwBlAHIAbgBhAG0AZQA9AGEAZABtAGkAbgBpAHMAdAByAGEAdABvAHIALABwAGEAcwBzAHcAbwByAGQAPQBhAGQAbQBpAG4AcABhAHMAcwAiAA==

and here is how to replicate at home:

$command = 'C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe -verb:sync -source:dbfullsql="Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;" -dest:dbfullsql="Data Source=.\mydestsource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;",computername=10.10.10.10,username=administrator,password=adminpass"'
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
$encodedCommand

#  The clip below copies the base64 string to your clipboard for right click and paste.
$encodedCommand | Clip

Babel command not found

There are two problems here. First, you need a package.json file. Telling npm to install without one will throw the npm WARN enoent ENOENT: no such file or directory error. In your project directory, run npm init to generate a package.json file for the project.

Second, local binaries probably aren't found because the local ./node_modules/.bin is not in $PATH. There are some solutions in How to use package installed locally in node_modules?, but it might be easier to just wrap your babel-cli commands in npm scripts. This works because npm run adds the output of npm bin (node_modules/.bin) to the PATH provided to scripts.

Here's a stripped-down example package.json which returns the locally installed babel-cli version:

{
  "scripts": {
    "babel-version": "babel --version"
  },
  "devDependencies": {
    "babel-cli": "^6.6.5"
  }
}

Call the script with this command: npm run babel-version.

Putting scripts in package.json is quite useful but often overlooked. Much more in the docs: How npm handles the "scripts" field

Redirect form to different URL based on select option element

Just use a onchnage Event for select box.

<select id="selectbox" name="" onchange="javascript:location.href = this.value;">
    <option value="https://www.yahoo.com/" selected>Option1</option>
    <option value="https://www.google.co.in/">Option2</option>
    <option value="https://www.gmail.com/">Option3</option>

</select>

And if selected option to be loaded at the page load then add some javascript code

<script type="text/javascript">
    window.onload = function(){
        location.href=document.getElementById("selectbox").value;
    }       
</script>

for jQuery: Remove the onchange event from <select> tag

jQuery(function () {
    // remove the below comment in case you need chnage on document ready
    // location.href=jQuery("#selectbox").val(); 
    jQuery("#selectbox").change(function () {
        location.href = jQuery(this).val();
    })
})

Check that a input to UITextField is numeric only

In Swift 4:

let formatString = "12345"
if let number = Decimal(string:formatString){

    print("String contains only number")
}
else{
    print("String doesn't contains only number")
}

center a row using Bootstrap 3

I know this question was specifically targeted at Bootstrap 3, but in case Bootstrap 4 users stumble upon this question, here is how i centered rows in v4:

<div class="container">
  <div class="row justify-content-center">
  ...

More related to this topic can be found on bootstrap site.

Difference between Spring MVC and Struts MVC

The main difference between struts & spring MVC is about the difference between Aspect Oriented Programming (AOP) & Object oriented programming (OOP).

Spring makes application loosely coupled by using Dependency Injection.The core of the Spring Framework is the IoC container.

OOP can do everything that AOP does but different approach. In other word, AOP complements OOP by providing another way of thinking about program structure.

Practically, when you want to apply same changes for many files. It should be exhausted work with Struts to add same code for tons of files. Instead Spring write new changes somewhere else and inject to the files.

Some related terminologies of AOP is cross-cutting concerns, Aspect, Dependency Injection...

Summing radio input values

Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:

<script type="text/javascript">   $(function() { //jQuery trick to say after all the HTML is parsed.     $("input[type=radio]").click(function() {       var total = 0;       $("input[type=radio]:checked").each(function() {         total += parseFloat($(this).val());       });        $("#totalSum").val(total);     });   }); </script> 

EDIT: This code works for me

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body>   <strong>Choose a base package:</strong>   <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942   <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313   <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829   <strong>Choose an add on:</strong>   <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0   <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146)   <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455)   <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764)   <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073)   <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382)   <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691)   <strong>Your total is:</strong>   <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" />   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>   <script type="text/javascript">       $("input[type=radio]").click(function() {         var total = 0;         $("input[type=radio]:checked").each(function() {           total += parseFloat($(this).val());         });          $("#totalSum").val(total);       });     </script> </body> </html> 

How to save all console output to file in R?

  1. If you want to get error messages saved in a file

    zz <- file("Errors.txt", open="wt")
    sink(zz, type="message")
    

    the output will be:

    Error in print(errr) : object 'errr' not found
    Execution halted
    

    This output will be saved in a file named Errors.txt

  2. In case, you want printed values of console to a file you can use 'split' argument:

    zz <- file("console.txt", open="wt")
    sink(zz,  split=TRUE)
    print("cool")
    print(errr)
    

    output will be:

    [1] "cool"
    

    in console.txt file. So all your console output will be printed in a file named console.txt

How to implement endless list with RecyclerView?

Although there are so many answers to the question, I would like to share our experience of creating the endless list view. We have recently implemented custom Carousel LayoutManager that can work in the cycle by scrolling the list infinitely as well as up to a certain point. Here is a detailed description on GitHub.

I suggest you take a look at this article with short but valuable recommendations on creating custom LayoutManagers: http://cases.azoft.com/create-custom-layoutmanager-android/

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

This typed error-message also shows while an if-statement comparison is done where there is an array and for example a bool or int. See for example:

... code snippet ...

if dataset == bool:
    ....

... code snippet ...

This clause has dataset as array and bool is euhm the "open door"... True or False.

In case the function is wrapped within a try-statement you will receive with except Exception as error: the message without its error-type:

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Absolute and Flexbox in React Native

The first step would be to add

position: 'absolute',

then if you want the element full width, add

left: 0,
right: 0,

then, if you want to put the element in the bottom, add

bottom: 0,
// don't need set top: 0

if you want to position the element at the top, replace bottom: 0 by top: 0

Use Toast inside Fragment

user2564789 said it right
But you can also use this in the place of getActivity()
which will make your toast look like this


     Toast.makeText(this,"Message",Toast.LENGTH_SHORT).show();
    

ImportError: No module named PIL

I had the same issue and tried many of the solutions listed above.

I then remembered that I have multiple versions of Python installed AND I use the PyCharm IDE (which is where I was getting this error message), so the solution in my case was:

In PyCharm:

go to File>Settings>Project>Python Interpreter

click "+" (install)

locate Pillow from the list and install it

Hope this helps anyone who may be in a similar situation!

Show how many characters remaining in a HTML text box using JavaScript

try this code in here...this is done using javascript onKeyUp() function...

<script>
function toCount(entrance,exit,text,characters) {  
var entranceObj=document.getElementById(entrance);  
var exitObj=document.getElementById(exit);  
var length=characters - entranceObj.value.length;  
if(length <= 0) {  
length=0;  
text='<span class="disable"> '+text+' <\/span>';  
entranceObj.value=entranceObj.value.substr(0,characters);  
}  
exitObj.innerHTML = text.replace("{CHAR}",length);  
}
</script>

textarea counter demo

PHP remove special character from string

You want str replace, because performance-wise it's much cheaper and still fits your needs!

$title = str_replace( array( '\'', '"', ',' , ';', '<', '>' ), ' ', $rawtitle);

(Unless this is all about security and sql injection, in that case, I'd rather to go with a POSITIVE list of ALLOWED characters... even better, stick with tested, proven routines.)

Btw, since the OP talked about title-setting: I wouldn't replace special chars with nothing, but with a space. A superficious space is less of a problem than two words glued together...

How to replace a string in a SQL Server Table Column

UPDATE CustomReports_Ta
SET vchFilter = REPLACE(CAST(vchFilter AS nvarchar(max)), '\\Ingl-report\Templates', 'C:\Customer_Templates')
where CAST(vchFilter AS nvarchar(max)) LIKE '%\\Ingl-report\Templates%'

Without the CAST function I got an error

Argument data type ntext is invalid for argument 1 of replace function.

Convert JSON String To C# Object

You probably don't want to just declare routes_list as an object type. It doesn't have a .test property, so you really aren't going to get a nice object back. This is one of those places where you would be better off defining a class or a struct, or make use of the dynamic keyword.

If you really want this code to work as you have it, you'll need to know that the object returned by DeserializeObject is a generic dictionary of string,object. Here's the code to do it that way:

var json_serializer = new JavaScriptSerializer();
var routes_list = (IDictionary<string, object>)json_serializer.DeserializeObject("{ \"test\":\"some data\" }");
Console.WriteLine(routes_list["test"]);

If you want to use the dynamic keyword, you can read how here.

If you declare a class or struct, you can call Deserialize instead of DeserializeObject like so:

class MyProgram {
    struct MyObj {
        public string test { get; set; }
    }

    static void Main(string[] args) {
        var json_serializer = new JavaScriptSerializer();
        MyObj routes_list = json_serializer.Deserialize<MyObj>("{ \"test\":\"some data\" }");
        Console.WriteLine(routes_list.test);

        Console.WriteLine("Done...");
        Console.ReadKey(true);
    }
}

Getting multiple values with scanf()

You can do this with a single call, like so:

scanf( "%i %i %i %i", &minx, &maxx, &miny, &maxy);

The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

  1. Why is this happening?

    The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, was officially deprecated in PHP v5.5.0 and removed in PHP v7.

    It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.

    The manual has contained warnings against its use in new code since June 2011.

  2. How can I fix it?

    As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.

    They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.

    Hashphp.org has an excellent tutorial on migrating from ext/mysql to PDO.

  3. I understand that it's possible to suppress deprecation errors by setting error_reporting in php.ini to exclude E_DEPRECATED:

    error_reporting = E_ALL ^ E_DEPRECATED
    

    What will happen if I do that?

    Yes, it is possible to suppress such error messages and continue using the old ext/mysql extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.

    Note also that this technique will suppress all E_DEPRECATED messages, not just those to do with the ext/mysql extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @—however this will suppress all errors raised by that expression, not just E_DEPRECATED ones.


What should you do?

  • You are starting a new project.

    There is absolutely no reason to use ext/mysql—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.

  • You have (your own) legacy codebase that currently depends upon ext/mysql.

    It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.

    • Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.

      Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.

    • The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.

      Consider whether you really need to upgrade to PHP v5.5 at this time.

      You should begin planning to replace ext/mysql with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.

      However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

  • You are using a third party project that depends upon ext/mysql.

    Consider whether you really need to upgrade to PHP v5.5 at this time.

    Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

    It is absolutely essential to perform regression testing.

How does JPA orphanRemoval=true differ from the ON DELETE CASCADE DML clause

An example taken form here:

When an Employee entity object is removed, the remove operation is cascaded to the referenced Address entity object. In this regard, orphanRemoval=true and cascade=CascadeType.REMOVE are identical, and if orphanRemoval=true is specified, CascadeType.REMOVE is redundant.

The difference between the two settings is in the response to disconnecting a relationship. For example, such as when setting the address field to null or to another Address object.

  • If orphanRemoval=true is specified the disconnected Address instance is automatically removed. This is useful for cleaning up dependent objects (e.g. Address) that should not exist without a reference from an owner object (e.g. Employee).

  • If only cascade=CascadeType.REMOVE is specified, no automatic action is taken since disconnecting a relationship is not a remove operation.

To avoid dangling references as a result of orphan removal, this feature should only be enabled for fields that hold private non shared dependent objects.

I hope this makes it more clear.

Is there a common Java utility to break a list into batches?

A one-liner in Java 8 would be:

import static java.util.function.Function.identity;
import static java.util.stream.Collectors.*;

private static <T> Collection<List<T>> partition(List<T> xs, int size) {
    return IntStream.range(0, xs.size())
            .boxed()
            .collect(collectingAndThen(toMap(identity(), xs::get), Map::entrySet))
            .stream()
            .collect(groupingBy(x -> x.getKey() / size, mapping(Map.Entry::getValue, toList())))
            .values();

}

Remove querystring from URL

var path = "path/to/myfile.png?foo=bar#hash";

console.log(
    path.replace(/(\?.*)|(#.*)/g, "")
);

How to use OrderBy with findAll in Spring Data

I try in this example to show you a complete example to personalize your OrderBy sorts

 import java.util.List;
 import org.springframework.data.domain.Page;
 import org.springframework.data.domain.Sort;
 import org.springframework.data.jpa.repository.*;
 import org.springframework.data.repository.query.Param;
 import org.springframework.stereotype.Repository;
 import org.springframework.data.domain.Sort;
 /**
 * Spring Data  repository for the User entity.
 */
 @SuppressWarnings("unused")
 @Repository
 public interface UserRepository extends JpaRepository<User, Long> {
 List <User> findAllWithCustomOrderBy(Sort sort);
 }

you will use this example : A method for build dynamically a object that instance of Sort :

import org.springframework.data.domain.Sort;
public class SampleOrderBySpring{
 Sort dynamicOrderBySort = createSort();
     public static void main( String[] args )
     {
       System.out.println("default sort \"firstName\",\"name\",\"age\",\"size\" ");
       Sort defaultSort = createStaticSort();
       System.out.println(userRepository.findAllWithCustomOrderBy(defaultSort ));


       String[] orderBySortedArray = {"name", "firstName"};
       System.out.println("default sort ,\"name\",\"firstName\" ");
       Sort dynamicSort = createDynamicSort(orderBySortedArray );
       System.out.println(userRepository.findAllWithCustomOrderBy(dynamicSort ));
      }
      public Sort createDynamicSort(String[] arrayOrdre) {
        return  Sort.by(arrayOrdre);
        }

   public Sort createStaticSort() {
        String[] arrayOrdre  ={"firstName","name","age","size");
        return  Sort.by(arrayOrdre);
        }
}

MongoDB: How to find the exact version of installed MongoDB

From the Java API:

Document result = mongoDatabase.runCommand(new Document("buildInfo", 1));
String version = (String) result.get("version");
List<Integer> versionArray = (List<Integer>) result.get("versionArray");

How do I correctly setup and teardown for my pytest class with tests?

As @Bruno suggested, using pytest fixtures is another solution that is accessible for both test classes or even just simple test functions. Here's an example testing python2.7 functions:

import pytest

@pytest.fixture(scope='function')
def some_resource(request):
    stuff_i_setup = ["I setup"]

    def some_teardown():
        stuff_i_setup[0] += " ... but now I'm torn down..."
        print stuff_i_setup[0]
    request.addfinalizer(some_teardown)

    return stuff_i_setup[0]

def test_1_that_needs_resource(some_resource):
    print some_resource + "... and now I'm testing things..."

So, running test_1... produces:

I setup... and now I'm testing things...
I setup ... but now I'm torn down...

Notice that stuff_i_setup is referenced in the fixture, allowing that object to be setup and torn down for the test it's interacting with. You can imagine this could be useful for a persistent object, such as a hypothetical database or some connection, that must be cleared before each test runs to keep them isolated.

C++ delete vector, objects, free memory

There are two separate things here:

  1. object lifetime
  2. storage duration

For example:

{
    vector<MyObject> v;
    // do some stuff, push some objects onto v
    v.clear(); // 1
    // maybe do some more stuff
} // 2

At 1, you clear v: this destroys all the objects it was storing. Each gets its destructor called, if your wrote one, and anything owned by that MyObject is now released. However, vector v has the right to keep the raw storage around in case you want it later.

If you decide to push some more things into it between 1 and 2, this saves time as it can reuse the old memory.

At 2, the vector v goes out of scope: any objects you pushed into it since 1 will be destroyed (as if you'd explicitly called clear again), but now the underlying storage is also released (v won't be around to reuse it any more).


If I change the example so v becomes a pointer to a dynamically-allocated vector, you need to explicitly delete it, as the pointer going out of scope at 2 doesn't do that for you. It's better to use something like std::unique_ptr in that case, but if you don't and v is leaked, the storage it allocated will be leaked as well. As above, you need to make sure v is deleted, and calling clear isn't sufficient.

Powershell's Get-date: How to get Yesterday at 22:00 in a variable?

(Get-Date (Get-Date -Format d)).AddHours(-2)

Parsing JSON giving "unexpected token o" error

I had the same problem when I submitted data using jQuery AJAX:

$.ajax({
   url:...
   success:function(data){
      //server response's data is JSON
      //I use jQuery's parseJSON method 
      $.parseJSON(data);//it's ERROR
   }
});

If the response is JSON, and you use this method, the data you get is a JavaScript object, but if you use dataType:"text", data is a JSON string. Then the use of $.parseJSON is okay.

How to hide a <option> in a <select> menu with CSS?

Simple answer: You can't. Form elements have very limited styling capabilities.

The best alternative would be to set disabled=true on the option (and maybe a gray colour, since only IE does that automatically), and this will make the option unclickable.

Alternatively, if you can, completely remove the option element.

PostgreSQL visual interface similar to phpMyAdmin?

pgAdmin 4 is a powerful and popular web-based database management tool for PostgreSQL - http://www.pgadmin.org/

Output single character in C

Be careful of difference between 'c' and "c"

'c' is a char suitable for formatting with %c

"c" is a char* pointing to a memory block with a length of 2 (with the null terminator).

Inserting into Oracle and retrieving the generated sequence ID

Expanding a bit on the answers from @Guru and @Ronnis, you can hide the sequence and make it look more like an auto-increment using a trigger, and have a procedure that does the insert for you and returns the generated ID as an out parameter.

create table batch(batchid number,
    batchname varchar2(30),
    batchtype char(1),
    source char(1),
    intarea number)
/

create sequence batch_seq start with 1
/

create trigger batch_bi
before insert on batch
for each row
begin
    select batch_seq.nextval into :new.batchid from dual;
end;
/

create procedure insert_batch(v_batchname batch.batchname%TYPE,
    v_batchtype batch.batchtype%TYPE,
    v_source batch.source%TYPE,
    v_intarea batch.intarea%TYPE,
    v_batchid out batch.batchid%TYPE)
as
begin
    insert into batch(batchname, batchtype, source, intarea)
    values(v_batchname, v_batchtype, v_source, v_intarea)
    returning batchid into v_batchid;
end;
/

You can then call the procedure instead of doing a plain insert, e.g. from an anoymous block:

declare
    l_batchid batch.batchid%TYPE;
begin
    insert_batch(v_batchname => 'Batch 1',
        v_batchtype => 'A',
        v_source => 'Z',
        v_intarea => 1,
        v_batchid => l_batchid);
    dbms_output.put_line('Generated id: ' || l_batchid);

    insert_batch(v_batchname => 'Batch 99',
        v_batchtype => 'B',
        v_source => 'Y',
        v_intarea => 9,
        v_batchid => l_batchid);
    dbms_output.put_line('Generated id: ' || l_batchid);
end;
/

Generated id: 1
Generated id: 2

You can make the call without an explicit anonymous block, e.g. from SQL*Plus:

variable l_batchid number;
exec insert_batch('Batch 21', 'C', 'X', 7, :l_batchid);

... and use the bind variable :l_batchid to refer to the generated value afterwards:

print l_batchid;
insert into some_table values(:l_batch_id, ...);

Calling method using JavaScript prototype

I know this post is from 4 years ago, but because of my C# background I was looking for a way to call the base class without having to specify the class name but rather obtain it by a property on the subclass. So my only change to Christoph's answer would be

From this:

MyClass.prototype.doStuff.call(this /*, args...*/);

To this:

this.constructor.prototype.doStuff.call(this /*, args...*/);

conversion from string to json object android

Here is the code, and you can decide which
(synchronized)StringBuffer or faster StringBuilder to use.

Benchmark shows StringBuilder is Faster.

public class Main {
            int times = 777;
            long t;

            {
                StringBuffer sb = new StringBuffer();
                t = System.currentTimeMillis();
                for (int i = times; i --> 0 ;) {
                    sb.append("");
                    getJSONFromStringBuffer(String stringJSON);
                }
                System.out.println(System.currentTimeMillis() - t);
            }

            {
                StringBuilder sb = new StringBuilder();
                t = System.currentTimeMillis();
                for (int i = times; i --> 0 ;) {
                     getJSONFromStringBUilder(String stringJSON);
                    sb.append("");
                }
                System.out.println(System.currentTimeMillis() - t);
            }
            private String getJSONFromStringBUilder(String stringJSONArray) throws JSONException {
                return new StringBuffer(
                       new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
                           .append(" ")
                           .append(
                       new JSONArray(employeeID).getJSONObject(0).getString("cat"))
                      .toString();
            }
            private String getJSONFromStringBuffer(String stringJSONArray) throws JSONException {
                return new StringBuffer(
                       new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
                           .append(" ")
                           .append(
                       new JSONArray(employeeID).getJSONObject(0).getString("cat"))
                      .toString();
            }
        }

How can I access a hover state in reactjs?

React components expose all the standard Javascript mouse events in their top-level interface. Of course, you can still use :hover in your CSS, and that may be adequate for some of your needs, but for the more advanced behaviors triggered by a hover you'll need to use the Javascript. So to manage hover interactions, you'll want to use onMouseEnter and onMouseLeave. You then attach them to handlers in your component like so:

<ReactComponent
    onMouseEnter={() => this.someHandler}
    onMouseLeave={() => this.someOtherHandler}
/>

You'll then use some combination of state/props to pass changed state or properties down to your child React components.

How can I refresh c# dataGridView after update ?

Rebind your DatagridView to the source.

DataGridView dg1 = new DataGridView();
dg1.DataSource = src1;

// Update Data in src1

dg1.DataSource = null;
dg1.DataSource = src1;

How to set up fixed width for <td>?

Ok, I just figured out where was the problem - in Bootstrap is set up as a default value width for select element, thus, the solution is:

tr. something {
  td {
    select {
      width: 90px;
    }
  }
}

Anything else doesn't work me.

How do you get the length of a string?

You don't need to use jquery.

var myString = 'abc';
var n = myString.length;

n will be 3.

How to fix UITableView separator on iOS 7?

This is default by iOS7 design. try to do the below:

[tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];

You can set the 'Separator Inset' from the storyboard:

enter image description here

enter image description here

Can a table have two foreign keys?

Yes, MySQL allows this. You can have multiple foreign keys on the same table.

Get more details here FOREIGN KEY Constraints

How to cast an object in Objective-C

Remember, Objective-C is a superset of C, so typecasting works as it does in C:

myEditController = [[SelectionListViewController alloc] init];
((SelectionListViewController *)myEditController).list = listOfItems;

Error:(23, 17) Failed to resolve: junit:junit:4.12

Here is what I did to solve the same problem. I am behind a firewall, which is same issue as yours I suppose. So I had tried removing the

testCompile 'junit:junit:4.12' line 

but that didnt work for me. I tried adding below lines of code:

repositories {
    maven { url 'http://repo1.maven.org/maven2' }
}

Even that did not work for me.

I tried removing (-) and readding (+) Junit4.12 from the library dependencies under Module Settings. Still that did not work for me.

Tried syncing and rebuilding project several times. Still did not work for me.

Finally what I did was to manually download the Junit4.12.jar file from mvnrepository website. I put this jar file in the Androids Workspace under the Project folder inside libs folder. Then go to Module Settings > Dependencies Tab > (+) > File Dependency > under Sleect path window, expand the 'libs' folder and you will find the Jar file you copied inside there. Select the File and click 'OK' Now remove the previous version of junit4.12 from the list of dependencies.

You should have one entry "libs\junit-4.12.jar" in the Dependencies list. Now click 'OK'.

Now Gradle will rebuild the project and you should be good to go.

Hope this helps!

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

This can happen if you have a table and forget to assign UITableViewDelegate and UITableViewDataSource to the class

C++ unordered_map using a custom class type as the key

Most basic possible copy/paste complete runnable example of using a custom class as the key for an unordered_map (basic implementation of a sparse matrix):

// UnorderedMapObjectAsKey.cpp

#include <iostream>
#include <vector>
#include <unordered_map>

struct Pos
{
  int row;
  int col;

  Pos() { }
  Pos(int row, int col)
  {
    this->row = row;
    this->col = col;
  }

  bool operator==(const Pos& otherPos) const
  {
    if (this->row == otherPos.row && this->col == otherPos.col) return true;
    else return false;
  }

  struct HashFunction
  {
    size_t operator()(const Pos& pos) const
    {
      size_t rowHash = std::hash<int>()(pos.row);
      size_t colHash = std::hash<int>()(pos.col) << 1;
      return rowHash ^ colHash;
    }
  };
};

int main(void)
{
  std::unordered_map<Pos, int, Pos::HashFunction> umap;

  // at row 1, col 2, set value to 5
  umap[Pos(1, 2)] = 5;

  // at row 3, col 4, set value to 10
  umap[Pos(3, 4)] = 10;

  // print the umap
  std::cout << "\n";
  for (auto& element : umap)
  {
    std::cout << "( " << element.first.row << ", " << element.first.col << " ) = " << element.second << "\n";
  }
  std::cout << "\n";

  return 0;
}

PostgreSQL: ERROR: operator does not exist: integer = character varying

I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).

If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::.

Something along these lines:

create view view1
as 
select table1.col1,table2.col1,table3.col3
from table1 
inner join
table2 
inner join 
table3
on 
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;

Notice the varchar typecasting on the table1.col4.

Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.

Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).

Prevent multiple instances of a given app in .NET?

It sounds like there are 3 fundamental techniques that have been suggested so far.

  1. Derive from the Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase class and set the IsSingleInstance property to true. (I believe a caveat here is that this won't work with WPF applications, will it?)
  2. Use a named mutex and check if it's already been created.
  3. Get a list of running processes and compare the names of the processes. (This has the caveat of requiring your process name to be unique relative to any other processes running on a given user's machine.)

Any caveats I've missed?

Replace preg_replace() e modifier with preg_replace_callback

preg_replace shim with eval support

This is very inadvisable. But if you're not a programmer, or really prefer terrible code, you could use a substitute preg_replace function to keep your /e flag working temporarily.

/**
 * Can be used as a stopgap shim for preg_replace() calls with /e flag.
 * Is likely to fail for more complex string munging expressions. And
 * very obviously won't help with local-scope variable expressions.
 *
 * @license: CC-BY-*.*-comment-must-be-retained
 * @security: Provides `eval` support for replacement patterns. Which
 *   poses troubles for user-supplied input when paired with overly
 *   generic placeholders. This variant is only slightly stricter than
 *   the C implementation, but still susceptible to varexpression, quote
 *   breakouts and mundane exploits from unquoted capture placeholders.
 * @url: https://stackoverflow.com/q/15454220
 */
function preg_replace_eval($pattern, $replacement, $subject, $limit=-1) {
    # strip /e flag
    $pattern = preg_replace('/(\W[a-df-z]*)e([a-df-z]*)$/i', '$1$2', $pattern);
    # warn about most blatant misuses at least
    if (preg_match('/\(\.[+*]/', $pattern)) {
        trigger_error("preg_replace_eval(): regex contains (.*) or (.+) placeholders, which easily causes security issues for unconstrained/user input in the replacement expression. Transform your code to use preg_replace_callback() with a sane replacement callback!");
    }
    # run preg_replace with eval-callback
    return preg_replace_callback(
        $pattern,
        function ($matches) use ($replacement) {
            # substitute $1/$2/… with literals from $matches[]
            $repl = preg_replace_callback(
                '/(?<!\\\\)(?:[$]|\\\\)(\d+)/',
                function ($m) use ($matches) {
                    if (!isset($matches[$m[1]])) { trigger_error("No capture group for '$m[0]' eval placeholder"); }
                    return addcslashes($matches[$m[1]], '\"\'\`\$\\\0'); # additionally escapes '$' and backticks
                },
                $replacement
            );
            # run the replacement expression
            return eval("return $repl;");
        },
        $subject,
        $limit
    );
}

In essence, you just include that function in your codebase, and edit preg_replace to preg_replace_eval wherever the /e flag was used.

Pros and cons:

  • Really just tested with a few samples from Stack Overflow.
  • Does only support the easy cases (function calls, not variable lookups).
  • Contains a few more restrictions and advisory notices.
  • Will yield dislocated and less comprehensible errors for expression failures.
  • However is still a usable temporary solution and doesn't complicate a proper transition to preg_replace_callback.
  • And the license comment is just meant to deter people from overusing or spreading this too far.

Replacement code generator

Now this is somewhat redundant. But might help those users who are still overwhelmed with manually restructuring their code to preg_replace_callback. While this is effectively more time consuming, a code generator has less trouble to expand the /e replacement string into an expression. It's a very unremarkable conversion, but likely suffices for the most prevalent examples.

To use this function, edit any broken preg_replace call into preg_replace_eval_replacement and run it once. This will print out the according preg_replace_callback block to be used in its place.

/**
 * Use once to generate a crude preg_replace_callback() substitution. Might often
 * require additional changes in the `return …;` expression. You'll also have to
 * refit the variable names for input/output obviously.
 *
 * >>>  preg_replace_eval_replacement("/\w+/", 'strtopupper("$1")', $ignored);
 */
function preg_replace_eval_replacement($pattern, $replacement, $subjectvar="IGNORED") {
    $pattern = preg_replace('/(\W[a-df-z]*)e([a-df-z]*)$/i', '$1$2', $pattern);
    $replacement = preg_replace_callback('/[\'\"]?(?<!\\\\)(?:[$]|\\\\)(\d+)[\'\"]?/', function ($m) { return "\$m[{$m[1]}]"; }, $replacement);
    $ve = "var_export";
    $bt = debug_backtrace(0, 1)[0];
    print "<pre><code>
    #----------------------------------------------------
    # replace preg_*() call in '$bt[file]' line $bt[line] with:
    #----------------------------------------------------
    \$OUTPUT_VAR = preg_replace_callback(
        {$ve($pattern, TRUE)},
        function (\$m) {
            return {$replacement};
        },
        \$YOUR_INPUT_VARIABLE_GOES_HERE
    )
    #----------------------------------------------------
    </code></pre>\n";
}

Take in mind that mere copy&pasting is not programming. You'll have to adapt the generated code back to your actual input/output variable names, or usage context.

  • Specificially the $OUTPUT = assignment would have to go if the previous preg_replace call was used in an if.
  • It's best to keep temporary variables or the multiline code block structure though.

And the replacement expression may demand more readability improvements or rework.

  • For instance stripslashes() often becomes redundant in literal expressions.
  • Variable-scope lookups require a use or global reference for/within the callback.
  • Unevenly quote-enclosed "-$1-$2" capture references will end up syntactically broken by the plain transformation into "-$m[1]-$m[2].

The code output is merely a starting point. And yes, this would have been more useful as an online tool. This code rewriting approach (edit, run, edit, edit) is somewhat impractical. Yet could be more approachable to those who are accustomed to task-centric coding (more steps, more uncoveries). So this alternative might curb a few more duplicate questions.

JavaScript null check

An “undefined variable” is different from the value undefined.

An undefined variable:

var a;
alert(b); // ReferenceError: b is not defined

A variable with the value undefined:

var a;
alert(a); // Alerts “undefined”

When a function takes an argument, that argument is always declared even if its value is undefined, and so there won’t be any error. You are right about != null followed by !== undefined being useless, though.

Convert php array to Javascript

It can be done in a safer way.

If your PHP array contains special characters, you need to use rawurlencode() in PHP and then use decodeURIComponent() in JS to escape those. And parse the JSON to native js. Try this:

var data = JSON.parse(
        decodeURIComponent(
            "<?=rawurlencode(json_encode($data));?>"
        )
    );

console.log(data);

How to compare two dates in php

I know this is late, but for future reference, put the date format into a recognised format by using str_replace then your function will work. (replace the underscore with a dash)

//change the format to dashes instead of underscores, then get the timestamp
$date1 = strtotime(str_replace("_", "-",$date1));
$date2 = strtotime(str_replace("_", "-",$date2));

//compare the dates
if($date1 < $date2){
   //convert the date back to underscore format if needed when printing it out.
   echo '1 is small='.$date1.','.date('d_m_y',$date1);
}else{
   echo '2 is small='.$date2.','.date('d_m_y',$date2);
}

What does "Table does not support optimize, doing recreate + analyze instead" mean?

That's really an informational message.

Likely, you're doing OPTIMIZE on an InnoDB table (table using the InnoDB storage engine, rather than the MyISAM storage engine).

InnoDB doesn't support the OPTIMIZE the way MyISAM does. It does something different. It creates an empty table, and copies all of the rows from the existing table into it, and essentially deletes the old table and renames the new table, and then runs an ANALYZE to gather statistics. That's the closest that InnoDB can get to doing an OPTIMIZE.

The message you are getting is basically MySQL server repeating what the InnoDB storage engine told MySQL server:

Table does not support optimize is the InnoDB storage engine saying...

"I (the InnoDB storage engine) don't do an OPTIMIZE operation like my friend (the MyISAM storage engine) does."

"doing recreate + analyze instead" is the InnoDB storage engine saying...

"I have decided to perform a different set of operations which will achieve an equivalent result."

How to open adb and use it to send commands

The adb tool can be found in sdk/platform-tools/

If you don't see this directory in your SDK, launch the SDK Manager and install "Android SDK Platform-tools"

Also update your PATH environment variable to include the platform-tools/ directory, so you can execute adb from any location.

How do you round a float to 2 decimal places in JRuby?

sprintf('%.2f', number) is a cryptic, but very powerful way of formatting numbers. The result is always a string, but since you're rounding I assume you're doing it for presentation purposes anyway. sprintf can format any number almost any way you like, and lots more.

Full sprintf documentation: http://www.ruby-doc.org/core-2.0.0/Kernel.html#method-i-sprintf

How to update a single pod without touching other dependencies

It's 2015

So because pod update SomePod touches everything in the latest versions of cocoapods, I found a workaround.

Follow the next steps:

  1. Remove SomePod from the Podfile

  2. Run pod install

pods will now remove SomePod from our project and from the Podfile.lock file.

  1. Put back SomePod into the Podfile

  2. Run pod install again

This time the latest version of our pod will be installed and saved in the Podfile.lock.

Neatest way to remove linebreaks in Perl

Whenever I go through input and want to remove or replace characters I run it through little subroutines like this one.

sub clean {

    my $text = shift;

    $text =~ s/\n//g;
    $text =~ s/\r//g;

    return $text;
}

It may not be fancy but this method has been working flawless for me for years.

How to avoid Sql Query Timeout

Your query is probably fine. "The semaphore timeout period has expired" is a Network error, not a SQL Server timeout.

There is apparently some sort of network problem between you and the SQL Server.

edit: However, apparently the query runs for 15-20 min before giving the network error. That is a very long time, so perhaps the network error could be related to the long execution time. Optimization of the underlying View might help.

If [MyTable] in your example is a View, can you post the View Definition so that we can have a go at optimizing it?

Preloading CSS Images

I can confirm that my original code seems to work. I was casually sticking to an image with a wrong path.

Here's a test : http://paragraphe.org/slidetoggletest/test.html

<script>
    var pic = new Image();
    var pic2 = new Image();
    var pic3 = new Image();
    pic.src="images/inputs/input1.png";
    pic2.src="images/inputs/input2.png";
    pic3.src="images/inputs/input3.png";
</script>

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

First, this is not an error. The 3xx denotes a redirection. The real errors are 4xx (client error) and 5xx (server error).

If a client gets a 304 Not Modified, then it's the client's responsibility to display the resouce in question from its own cache. In general, the proxy shouldn't worry about this. It's just the messenger.

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

var fileName = @"C:\ExcelFile.xlsx";
var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\""; ;
using (var conn = new OleDbConnection(connectionString))
{
    conn.Open();

    var sheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
    using (var cmd = conn.CreateCommand())
    {
        cmd.CommandText = "SELECT * FROM [" + sheets.Rows[0]["TABLE_NAME"].ToString() + "] ";

        var adapter = new OleDbDataAdapter(cmd);
        var ds = new DataSet();
        adapter.Fill(ds);
    }
}

How to upgrade glibc from version 2.13 to 2.15 on Debian?

I was able to install libc6 2.17 in Debian Wheezy by editing the recommendations in perror's answer:

IMPORTANT
You need to exit out of your display manager by pressing CTRL-ALT-F1. Then you can stop x (slim) with sudo /etc/init.d/slim stop

(replace slim with mdm or lightdm or whatever)

Add the following line to the file /etc/apt/sources.list:

deb http://ftp.debian.org/debian experimental main

Should be changed to:

deb http://ftp.debian.org/debian sid main

Then follow the rest of perror's post:

Update your package database:

apt-get update

Install the eglibc package:

apt-get -t sid install libc6-amd64 libc6-dev libc6-dbg

IMPORTANT
After done updating libc6, restart computer, and you should comment out or remove the sid source you just added (deb http://ftp.debian.org/debian sid main), or else you risk upgrading your whole distro to sid.

Hope this helps. It took me a while to figure out.

JSONDecodeError: Expecting value: line 1 column 1

in my case, some characters like " , :"'{}[] " maybe corrupt the JSON format, so use try json.loads(str) except to check your input

MSBUILD : error MSB1008: Only one project can be specified

In vs2012 just try to create a Build definition "Test Build" using the default TFS template "DefaultTemplate....xaml" (usually a copy of it)

It will fail with the usual self-explaining-error: "MSBUILD : error MSB1008: Only one project can be specified.Switch: Activities"

Off course somewhere in the default TFS template some " are missing so msbuild will receive as parameter a non escaped directory containing spaces so will result in multiple projects(?!)

So NEVER use spaces in you TFS Build Definition names, pretty sad and simple at the same time

Passing in class names to react components

As other have stated, use an interpreted expression with curly braces.

But do not forget to set a default.
Others has suggested using a OR statement to set a empty string if undefined.

But it would be even better to declare your Props.

Full example:

import React, { Component } from 'react';
import PropTypes from 'prop-types';

class Pill extends Component {

  render() {

    return (
      <button className={`pill ${ this.props.className }`}>{this.props.children}</button>
    );
  }

}

Pill.propTypes = {
  className: PropTypes.string,
};

Pill.defaultProps = {
  className: '',
};

Where can I set environment variables that crontab will use?

Another way - inspired by this this answer - to "inject" variables is the following (fcron example):

%daily 00 12 \
    set -a; \
    . /path/to/file/containing/vars; \
    set +a; \
    /path/to/script/using/vars

From help set:

-a Mark variables which are modified or created for export.

Using + rather than - causes these flags to be turned off.

So everything in between set - and set + gets exported to env and is then available for other scripts, etc. Without using set the variables get sourced but live in set only.

Aside from that it's also useful to pass variables when a program requires a non-root account to run but you'd need some variables inside that other user's environment. Below is an example passing in nullmailer vars to format the e-mail header:

su -s /bin/bash -c "set -a; \
                    . /path/to/nullmailer-vars; \
                    set +a; \
                    /usr/sbin/logcheck" logcheck

How do I write a SQL query for a specific date range and date time using SQL Server 2008?

"SELECT Applicant.applicantId, Applicant.lastName, Applicant.firstName, Applicant.middleName, Applicant.status,Applicant.companyId, Company.name, Applicant.createDate FROM (Applicant INNER JOIN Company ON Applicant.companyId = Company.companyId) WHERE Applicant.createDate between  '" +dateTimePicker1.Text.ToString() + "'and '"+dateTimePicker2.Text.ToString() +"'";

this is what i did!!

Remove border from IFrame

After going mad trying to remove the border in IE7, I found that the frameBorder attribute is case sensitive.

You have to set the frameBorder attribute with a capital B.

<iframe frameBorder="0"></iframe>

collapse cell in jupyter notebook

You don't need to do much except to enable the extensions:

http://localhost:8888/nbextensions?nbextension=collapsible_headings
http://localhost:8888/nbextensions?nbextension=codefolding/main

enter image description here

Most probable you will find all your extensions in here:

http://localhost:8888/nbextensions

enter image description here

How to change the version of the 'default gradle wrapper' in IntelliJ IDEA?

./gradlew wrapper --gradle-version=5.4.1 --distribution-type=bin

https://gradle.org/install/#manually

To check:

 ./gradlew tasks

To input it without command:

go to-> gradle/wrapper/gradle-wrapper.properties distribution url and change it to the updated zip version

output:

 ./gradlew tasks
Downloading https://services.gradle.org/distributions/gradle-5.4.1-bin.zip
...................................................................................

Welcome to Gradle 5.4.1!

Here are the highlights of this release:
 - Run builds with JDK12
 - New API for Incremental Tasks
 - Updates to native projects, including Swift 5 support

For more details see https://docs.gradle.org/5.4.1/release-notes.html

Starting a Gradle Daemon (subsequent builds will be faster)

> Starting Daemon 

What is the syntax meaning of RAISERROR()

The severity level 16 in your example code is typically used for user-defined (user-detected) errors. The SQL Server DBMS itself emits severity levels (and error messages) for problems it detects, both more severe (higher numbers) and less so (lower numbers).

The state should be an integer between 0 and 255 (negative values will give an error), but the choice is basically the programmer's. It is useful to put different state values if the same error message for user-defined error will be raised in different locations, e.g. if the debugging/troubleshooting of problems will be assisted by having an extra indication of where the error occurred.

Is there a Social Security Number reserved for testing/examples?

There are multiple number groups and some particular numbers that will never be allocated:

Consider using one of these (the obviously invalid 000-00-0000 would be a good one IMO).

(Answer has been updated to provide source information beyond Wikipedia and remove information that is no longer accurate after the SSA made its randomization change in mid 2011.)

Multiple aggregations of the same column using pandas GroupBy.agg()

Would something like this work:

In [7]: df.groupby('dummy').returns.agg({'func1' : lambda x: x.sum(), 'func2' : lambda x: x.prod()})
Out[7]: 
              func2     func1
dummy                        
1     -4.263768e-16 -0.188565

How to exclude particular class name in CSS selector?

Method 1

The problem with your code is that you are selecting the .remode_hover that is a descendant of .remode_selected. So the first part of getting your code to work correctly is by removing that space

.reMode_selected.reMode_hover:hover

Then, in order to get the style to not work, you have to override the style set by the :hover. In other words, you need to counter the background-color property. So the final code will be

.reMode_selected.reMode_hover:hover {
  background-color:inherit;
}
.reMode_hover:hover {
  background-color: #f0ac00;
}

Fiddle

Method 2

An alternative method would be to use :not(), as stated by others. This will return any element that doesn't have the class or property stated inside the parenthesis. In this case, you would put .remode_selected in there. This will target all elements that don't have a class of .remode_selected

Fiddle

However, I would not recommend this method, because of the fact that it was introduced in CSS3, so browser support is not ideal.

Method 3

A third method would be to use jQuery. You can target the .not() selector, which would be similar to using :not() in CSS, but with much better browser support

Fiddle

How good is Java's UUID.randomUUID?

Does anybody have any experience to share?

There are 2^122 possible values for a type-4 UUID. (The spec says that you lose 2 bits for the type, and a further 4 bits for a version number.)

Assuming that you were to generate 1 million random UUIDs a second, the chances of a duplicate occurring in your lifetime would be vanishingly small. And to detect the duplicate, you'd have to solve the problem of comparing 1 million new UUIDs per second against all of the UUIDs you have previously generated1!

The chances that anyone has experienced (i.e. actually noticed) a duplicate in real life are even smaller than vanishingly small ... because of the practical difficulty of looking for collisions.

Now of course, you will typically be using a pseudo-random number generator, not a source of truly random numbers. But I think we can be confident that if you are using a creditable provider for your cryptographic strength random numbers, then it will be cryptographic strength, and the probability of repeats will be the same as for an ideal (non-biased) random number generator.

However, if you were to use a JVM with a "broken" crypto- random number generator, all bets are off. (And that might include some of the workarounds for "shortage of entropy" problems on some systems. Or the possibility that someone has tinkered with your JRE, either on your system or upstream.)


1 - Assuming that you used "some kind of binary btree" as proposed by an anonymous commenter, each UUID is going to need O(NlogN) bits of RAM memory to represent N distinct UUIDs assuming low density and random distribution of the bits. Now multiply that by 1,000,000 and the number of seconds that you are going to run the experiment for. I don't think that is practical for the length of time needed to test for collisions of a high quality RNG. Not even with (hypothetical) clever representations.

How to downgrade to older version of Gradle

got it resolved:

uninstall the entire android studio

uninstalling android with the following commands

rm -Rf /Applications/Android\ Studio.app  
rm -Rf ~/Library/Preferences/AndroidStudio*  
rm -Rf ~/Library/Preferences/com.google.android.*  
rm -Rf ~/Library/Preferences/com.android.*  
rm -Rf ~/Library/Application\ Support/AndroidStudio*  
rm -Rf ~/Library/Logs/AndroidStudio*  
rm -Rf ~/Library/Caches/AndroidStudio*  
rm -Rf ~/.AndroidStudio*  
rm -Rf ~/.gradle  
rm -Rf ~/.android  
rm -Rf ~/Library/Android*  
rm -Rf /usr/local/var/lib/android-sdk/  
rm -Rf /Users/<username>/.tooling/gradle

Remove your project and clone it again and then goto Gradle Scripts and open gradle-wrapper.properties and change the below url which ever version you need

distributionUrl=https\://services.gradle.org/distributions/gradle-4.2-all.zip

Converting xml to string using C#

There's a much simpler way to convert your XmlDocument to a string; use the OuterXml property. The OuterXml property returns a string version of the xml.

public string GetXMLAsString(XmlDocument myxml)
{
    return myxml.OuterXml;
}

How do I get a list of all the duplicate items using pandas in python?

This may not be a solution to the question, but to illustrate examples:

import pandas as pd

df = pd.DataFrame({
    'A': [1,1,3,4],
    'B': [2,2,5,6],
    'C': [3,4,7,6],
})

print(df)
df.duplicated(keep=False)
df.duplicated(['A','B'], keep=False)

The outputs:

   A  B  C
0  1  2  3
1  1  2  4
2  3  5  7
3  4  6  6

0    False
1    False
2    False
3    False
dtype: bool

0     True
1     True
2    False
3    False
dtype: bool

how to hide keyboard after typing in EditText in android?

You can see marked answer on top. But i used getDialog().getCurrentFocus() and working well. I post this answer cause i cant type "this" in my oncreatedialog.

So this is my answer. If you tried marked answer and not worked , you can simply try this:

InputMethodManager inputManager = (InputMethodManager) getActivity().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getDialog().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

Can I run Keras model on gpu?

I'm using Anaconda on Windows 10, with a GTX 1660 Super. I first installed the CUDA environment following this step-by-step. However there is now a keras-gpu metapackage available on Anaconda which apparently doesn't require installing CUDA and cuDNN libraries beforehand (mine were already installed anyway).

This is what worked for me to create a dedicated environment named keras_gpu:

# need to downgrade from tensorflow 2.1 for my particular setup
conda create --name keras_gpu keras-gpu=2.3.1 tensorflow-gpu=2.0

To add on @johncasey 's answer but for TensorFlow 2.0, adding this block works for me:

import tensorflow as tf
from tensorflow.python.keras import backend as K

# adjust values to your needs
config = tf.compat.v1.ConfigProto( device_count = {'GPU': 1 , 'CPU': 8} )
sess = tf.compat.v1.Session(config=config) 
K.set_session(sess)

This post solved the set_session error I got: you need to use the keras backend from the tensorflow path instead of keras itself.

Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'

Try this:

jsonResponse = json.loads(response.decode('utf-8'))

Resize a picture to fit a JLabel

Outline

Here are the steps to follow.

  • Read the picture as a BufferedImage.
  • Resize the BufferedImage to another BufferedImage that's the size of the JLabel.
  • Create an ImageIcon from the resized BufferedImage.

You do not have to set the preferred size of the JLabel. Once you've scaled the image to the size you want, the JLabel will take the size of the ImageIcon.

Read the picture as a BufferedImage

BufferedImage img = null;
try {
    img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
    e.printStackTrace();
}

Resize the BufferedImage

Image dimg = img.getScaledInstance(label.getWidth(), label.getHeight(),
        Image.SCALE_SMOOTH);

Make sure that the label width and height are the same proportions as the original image width and height. In other words, if the picture is 600 x 900 pixels, scale to 100 X 150. Otherwise, your picture will be distorted.

Create an ImageIcon

ImageIcon imageIcon = new ImageIcon(dimg);

Can Python test the membership of multiple values in a list?

how can you be pythonic without lambdas! .. not to be taken seriously .. but this way works too:

orig_array = [ ..... ]
test_array = [ ... ]

filter(lambda x:x in test_array, orig_array) == test_array

leave out the end part if you want to test if any of the values are in the array:

filter(lambda x:x in test_array, orig_array)

get number of columns of a particular row in given excel using Java

Sometimes using row.getLastCellNum() gives you a higher value than what is actually filled in the file.
I used the method below to get the last column index that contains an actual value.

private int getLastFilledCellPosition(Row row) {
        int columnIndex = -1;

        for (int i = row.getLastCellNum() - 1; i >= 0; i--) {
            Cell cell = row.getCell(i);

            if (cell == null || CellType.BLANK.equals(cell.getCellType()) || StringUtils.isBlank(cell.getStringCellValue())) {
                continue;
            } else {
                columnIndex = cell.getColumnIndex();
                break;
            }
        }

        return columnIndex;
    }

jQuery scrollTop() doesn't seem to work in Safari or Chrome (Windows)

I was having this problem in Safari and Chrome (Mac) and discovered that .scrollTop would work on $("body") but not $("html, body"), FF and IE however works the other way round. A simple browser detect fixes the issue:

if($.browser.safari)
    bodyelem = $("body")
else
    bodyelem = $("html,body")

bodyelem.scrollTop(100)

The jQuery browser value for Chrome is Safari, so you only need to do a detect on that.

Hope this helps someone.

What is the easiest way to initialize a std::vector with hardcoded elements?

If you can, use the modern C++[11,14,17,...] way:

std::vector<int> vec = {10,20,30};

The old way of looping over a variable-length array or using sizeof() is truly terrible on the eyes and completely unnecessary in terms of mental overhead. Yuck.

How to Deep clone in javascript

my addition to all the answers

function deepCopy(arr) {
  if (typeof arr !== 'object') return arr
  if (Array.isArray(arr)) return [...arr].map(deepCopy)
  for (const prop in arr) 
    copy[prop] = deepCopy(arr[prop])
  return copy
}

How to overwrite styling in Twitter Bootstrap

I know this is an old question but still, I came across a similar problem and i realized that my "not working" css code in my bootstrapOverload.css file was written after the media queries. when I moved it above media queries it started working.

Just in case someone else is facing the same problem

How to export data from Excel spreadsheet to Sql Server 2008 table

From your SQL Server Management Studio, you open Object Explorer, go to your database where you want to load the data into, right click, then pick Tasks > Import Data.

This opens the Import Data Wizard, which typically works pretty well for importing from Excel. You can pick an Excel file, pick what worksheet to import data from, you can choose what table to store it into, and what the columns are going to be. Pretty flexible indeed.

You can run this as a one-off, or you can store it as a SQL Server Integration Services (SSIS) package into your file system, or into SQL Server itself, and execute it over and over again (even scheduled to run at a given time, using SQL Agent).

Update: yes, yes, yes, you can do all those things you keep asking - have you even tried at least once to run that wizard??

OK, here it comes - step by step:

Step 1: pick your Excel source

enter image description here

Step 2: pick your SQL Server target database

enter image description here

Step 3: pick your source worksheet (from Excel) and your target table in your SQL Server database; see the "Edit Mappings" button!

enter image description here

Step 4: check (and change, if needed) your mappings of Excel columns to SQL Server columns in the table:

enter image description here

Step 5: if you want to use it later on, save your SSIS package to SQL Server:

enter image description here

Step 6: - success! This is on a 64-bit machine, works like a charm - just do it!!

Call to undefined function App\Http\Controllers\ [ function name ]

say you define the static getFactorial function inside a CodeController

then this is the way you need to call a static function, because static properties and methods exists with in the class, not in the objects created using the class.

CodeController::getFactorial($index);

----------------UPDATE----------------

To best practice I think you can put this kind of functions inside a separate file so you can maintain with more easily.

to do that

create a folder inside app directory and name it as lib (you can put a name you like).

this folder to needs to be autoload to do that add app/lib to composer.json as below. and run the composer dumpautoload command.

"autoload": {
    "classmap": [
                "app/commands",
                "app/controllers",
                ............
                "app/lib"
    ]
},

then files inside lib will autoloaded.

then create a file inside lib, i name it helperFunctions.php

inside that define the function.

if ( ! function_exists('getFactorial'))
{

    /**
     * return the factorial of a number
     *
     * @param $number
     * @return string
     */
    function getFactorial($date)
    {
        $fact = 1;

        for($i = 1; $i <= $num ;$i++)
            $fact = $fact * $i;

        return $fact;

     }
}

and call it anywhere within the app as

$fatorial_value = getFactorial(225);

"The system cannot find the file C:\ProgramData\Oracle\Java\javapath\java.exe"

<>\Common Files\Oracle\Java\javapath\ is now created as a junction, no symlinks anymore

Parsing JSON using C

I used JSON-C for a work project and would recommend it. Lightweight and is released with open licensing.

Documentation is included in the distribution. You basically have *_add functions to create JSON objects, equivalent *_put functions to release their memory, and utility functions that convert types and output objects in string representation.

The licensing allows inclusion with your project. We used it in this way, compiling JSON-C as a static library that is linked in with the main build. That way, we don't have to worry about dependencies (other than installing Xcode).

JSON-C also built for us under OS X (x86 Intel) and Linux (x86 Intel) without incident. If your project needs to be portable, this is a good start.

How to scroll HTML page to given anchor?

Smoothly scroll to the proper position (2019)

Get correct y coordinate and use window.scrollTo({top: y, behavior: 'smooth'})

const id = 'anchorName2';
const yourElement = document.getElementById(id);
const y = yourElement.getBoundingClientRect().top + window.pageYOffset;

window.scrollTo({top: y, behavior: 'smooth'});

With offset

scrollIntoView is a good option too but it may not works perfectly in some cases. For example when you need additional offset. With scrollTo you just need to add that offset like this:

const yOffset = -10; 

window.scrollTo({top: y + yOffset, behavior: 'smooth'});

How to validate IP address in Python?

The IPy module (a module designed for dealing with IP addresses) will throw a ValueError exception for invalid addresses.

>>> from IPy import IP
>>> IP('127.0.0.1')
IP('127.0.0.1')
>>> IP('277.0.0.1')
Traceback (most recent call last):
 ...
ValueError: '277.0.0.1': single byte must be 0 <= byte < 256
>>> IP('foobar')
Traceback (most recent call last):
 ...
ValueError: invalid literal for long() with base 10: 'foobar'

However, like Dustin's answer, it will accept things like "4" and "192.168" since, as mentioned, these are valid representations of IP addresses.

If you're using Python 3.3 or later, it now includes the ipaddress module:

>>> import ipaddress
>>> ipaddress.ip_address('127.0.0.1')
IPv4Address('127.0.0.1')
>>> ipaddress.ip_address('277.0.0.1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.3/ipaddress.py", line 54, in ip_address
    address)
ValueError: '277.0.0.1' does not appear to be an IPv4 or IPv6 address
>>> ipaddress.ip_address('foobar')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.3/ipaddress.py", line 54, in ip_address
    address)
ValueError: 'foobar' does not appear to be an IPv4 or IPv6 address

For Python 2, you can get the same functionality using ipaddress if you install python-ipaddress:

pip install ipaddress

This module is compatible with Python 2 and provides a very similar API to that of the ipaddress module included in the Python Standard Library since Python 3.3. More details here. In Python 2 you will need to explicitly convert the IP address string to unicode: ipaddress.ip_address(u'127.0.0.1').

How to implement a Keyword Search in MySQL?

SELECT 
    *
FROM 
    yourtable
WHERE 
    id LIKE '%keyword%' 
    OR position LIKE '%keyword%'
    OR category LIKE '%keyword%'
    OR location LIKE '%keyword%'
    OR description LIKE '%keyword%'
    OR refno LIKE '%keyword%';

Post Build exited with code 1

I was able to fix my Code 1 by running Visual Studio as Admin. Apparently it didn't have access to execute the shell commands without Admin.

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

Making an iframe responsive

iframe{
  max-width: 100% !important;
}

What are the differences between using the terminal on a mac vs linux?

If you did a new or clean install of OS X version 10.3 or more recent, the default user terminal shell is bash.

Bash is essentially an enhanced and GNU freeware version of the original Bourne shell, sh. If you have previous experience with bash (often the default on GNU/Linux installations), this makes the OS X command-line experience familiar, otherwise consider switching your shell either to tcsh or to zsh, as some find these more user-friendly.

If you upgraded from or use OS X version 10.2.x, 10.1.x or 10.0.x, the default user shell is tcsh, an enhanced version of csh('c-shell'). Early implementations were a bit buggy and the programming syntax a bit weird so it developed a bad rap.

There are still some fundamental differences between mac and linux as Gordon Davisson so aptly lists, for example no useradd on Mac and ifconfig works differently.

The following table is useful for knowing the various unix shells.

sh      The original Bourne shell   Present on every unix system 
ksh     Original Korn shell         Richer shell programming environment than sh 
csh     Original C-shell            C-like syntax; early versions buggy 
tcsh    Enhanced C-shell            User-friendly and less buggy csh implementation 
bash    GNU Bourne-again shell      Enhanced and free sh implementation 
zsh     Z shell                     Enhanced, user-friendly ksh-like shell

You may also find these guides helpful:

http://homepage.mac.com/rgriff/files/TerminalBasics.pdf

http://guides.macrumors.com/Terminal
http://www.ofb.biz/safari/article/476.html

On a final note, I am on Linux (Ubuntu 11) and Mac osX so I use bash and the thing I like the most is customizing the .bashrc (source'd from .bash_profile on OSX) file with aliases, some examples below. I now placed all my aliases in a separate .bash_aliases file and include it with:

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

in the .bashrc or .bash_profile file.

Note that this is an example of a mac-linux difference because on a Mac you can't have the --color=auto. The first time I did this (without knowing) I redefined ls to be invalid which was a bit alarming until I removed --auto-color !

You may also find https://unix.stackexchange.com/q/127799/10043 useful

# ~/.bash_aliases
# ls variants
#alias l='ls -CF' 
alias la='ls -A' 
alias l='ls -alFtr' 
alias lsd='ls -d .*' 
# Various
alias h='history | tail'
alias hg='history | grep'
alias mv='mv -i' 
alias zap='rm -i'
# One letter quickies:
alias p='pwd'
alias x='exit'
alias {ack,ak}='ack-grep'
# Directories
alias s='cd ..'
alias play='cd ~/play/'
# Rails
alias src='script/rails console'
alias srs='script/rails server'
alias raked='rake db:drop db:create db:migrate db:seed' 
alias rvm-restart='source '\''/home/durrantm/.rvm/scripts/rvm'\'''
alias rrg='rake routes | grep '
alias rspecd='rspec --drb '
#
# DropBox - syncd
WORKBASE="~/Dropbox/97_2012/work"
alias work="cd $WORKBASE"
alias code="cd $WORKBASE/ror/code"
#
# DropNot - NOT syncd !
WORKBASE_GIT="~/Dropnot"
alias {dropnot,not}="cd $WORKBASE_GIT"
alias {webs,ww}="cd $WORKBASE_GIT/webs"
alias {setups,docs}="cd $WORKBASE_GIT/setups_and_docs"
alias {linker,lnk}="cd $WORKBASE_GIT/webs/rails_v3/linker"
#
# git
alias {gsta,gst}='git status' 
# Warning: gst conflicts with gnu-smalltalk (when used).
alias {gbra,gb}='git branch'
alias {gco,go}='git checkout'
alias {gcob,gob}='git checkout -b '
alias {gadd,ga}='git add '
alias {gcom,gc}='git commit'
alias {gpul,gl}='git pull '
alias {gpus,gh}='git push '
alias glom='git pull origin master'
alias ghom='git push origin master'
alias gg='git grep '
#
# vim
alias v='vim'
#
# tmux
alias {ton,tn}='tmux set -g mode-mouse on'
alias {tof,tf}='tmux set -g mode-mouse off'
#
# dmc
alias {dmc,dm}='cd ~/Dropnot/webs/rails_v3/dmc/'
alias wf='cd ~/Dropnot/webs/rails_v3/dmc/dmWorkflow'
alias ws='cd ~/Dropnot/webs/rails_v3/dmc/dmStaffing'

How to quickly check if folder is empty (.NET)?

I'm sure the other answers are faster, and your question asked for whether or not a folder contained files or folders... but I'd think most of the time people would consider a directory empty if it contains no files. ie It's still "empty" to me if it contains empty subdirectories... this may not fit for your usage, but may for others!

  public bool DirectoryIsEmpty(string path)
  {
    int fileCount = Directory.GetFiles(path).Length;
    if (fileCount > 0)
    {
        return false;
    }

    string[] dirs = Directory.GetDirectories(path);
    foreach (string dir in dirs)
    {
      if (! DirectoryIsEmpty(dir))
      {
        return false;
      }
    }

    return true;
  }

JavaScript: client-side vs. server-side validation

I came across an interesting link that make a distinction between gross, systematic, random errors.

Client-Side validation suits perfectly for preventing gross and random errors. Typically a max length for texture and input. Do not mimic the server-side validation rule; provide your own gross, rule of thumb validation rule (ex. 200 characters on client-side; n on server-side dictated by a strong business rule).

Server-side validation suits perfectly for preventing systematic errors; it will enforce business rules.

In a project I'm involved in, the validation is done on the server through ajax requests. On the client I display error messages accordingly.

Further reading: gross, systematic, random errors:

https://answers.yahoo.com/question/index?qid=20080918203131AAEt6GO

What to do on TransactionTooLargeException

With so many places where TransactionTooLargeException can happen-- here's one more new to Android 8--a crash when someone merely starts to type into an EditText if the content is too big.

It's related to the AutoFillManager (new in API 26) and the following code in StartSessionLocked():

    mSessionId = mService.startSession(mContext.getActivityToken(),
            mServiceClient.asBinder(), id, bounds, value, mContext.getUserId(),
            mCallback != null, flags, mContext.getOpPackageName());

If I understand correctly, this calls the autofill service-- passing the AutofillManagerClient within the binder. And when the EditText has a lot of content, it seems to cause the TTLE.

A few things may mitigate it (or did as I was testing anyway): Add android:importantForAutofill="noExcludeDescendants" in the EditText's xml layout declaration. Or in code:

EditText et = myView.findViewById(R.id.scriptEditTextView);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    et.setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS);
}

A 2nd awful, terrible workaround might also be to override the performClick() and onWindowFocusChanged() methods to catch the error in a TextEdit subclass itself. But I don't think that's wise really...

How to select a value in dropdown javascript?

I realize that this is an old question, but I'll post the solution for my use case, in case others run into the same situation I did when implementing James Hill's answer (above).

I found this question while trying to solve the same issue. James' answer got me 90% there. However, for my use case, selecting the item from the dropdown also triggered an action on the page from dropdown's onchange event. James' code as written did not trigger this event (at least in Firefox, which I was testing in). As a result, I made the following minor change:

function setSelectedValue(object, value) {
    for (var i = 0; i < object.options.length; i++) {
        if (object.options[i].text === value) {
            object.options[i].selected = true;
            object.onchange();
            return;
        }
    }

    // Throw exception if option `value` not found.
    var tag = object.nodeName;
    var str = "Option '" + value + "' not found";

    if (object.id != '') {
        str = str + " in //" + object.nodeName.toLowerCase()
              + "[@id='" + object.id + "']."
    }

    else if (object.name != '') {
        str = str + " in //" + object.nodeName.toLowerCase()
              + "[@name='" + object.name + "']."
    }

    else {
        str += "."
    }

    throw str;
}

Note the object.onchange() call, which I added to the original solution. This calls the handler to make certain that the action on the page occurs.

Edit

Added code to throw an exception if option value is not found; this is needed for my use case.

Python: most idiomatic way to convert None to empty string?

I use max function:

max(None, '')  #Returns blank
max("Hello",'') #Returns Hello

Works like a charm ;) Just put your string in the first parameter of the function.

Download and open PDF file using Ajax

The following code worked for me

//Parameter to be passed
var data = 'reportid=R3823&isSQL=1&filter=[]';
var xhr = new XMLHttpRequest();
xhr.open("POST", "Reporting.jsp"); //url.It can pdf file path
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.responseType = "blob";
xhr.onload = function () {
    if (this.status === 200) {
        var blob = new Blob([xhr.response]);
        const url = window.URL.createObjectURL(blob);
        var a = document.createElement('a');
        a.href = url;
        a.download = 'myFile.pdf';
        a.click();
        setTimeout(function () {
            // For Firefox it is necessary to delay revoking the ObjectURL
            window.URL.revokeObjectURL(data)
                , 100
        })
    }
};
xhr.send(data);

How to split and modify a string in NodeJS?

If you're using lodash and in the mood for a too-cute-for-its-own-good one-liner:

_.map(_.words('123, 124, 234,252'), _.add.bind(1, 1));

It's surprisingly robust thanks to lodash's powerful parsing capabilities.

If you want one that will also clean non-digit characters out of the string (and is easier to follow...and not quite so cutesy):

_.chain('123, 124, 234,252, n301')
   .replace(/[^\d,]/g, '')
   .words()
   .map(_.partial(_.add, 1))
   .value();

2017 edit:

I no longer recommend my previous solution. Besides being overkill and already easy to do without a third-party library, it makes use of _.chain, which has a variety of issues. Here's the solution I would now recommend:

const str = '123, 124, 234,252';
const arr = str.split(',').map(n => parseInt(n, 10) + 1);

My old answer is still correct, so I'll leave it for the record, but there's no need to use it nowadays.

Form inline inside a form horizontal in twitter bootstrap?

I know this is an old answer but here is what I usually do:

CSS:

.form-control-inline {
   width: auto;
   float:left;
   margin-right: 5px;
}

Then wrap the fields you want to be inlined in a div and add .form-control-inline to the input, example:

HTML

<label class="control-label">Date of birth:</label>
<div>
<select class="form-control form-control-inline" name="year"> ... </select>
<select class="form-control form-control-inline" name="month"> ... </select>
<select class="form-control form-control-inline" name="day"> ... </select>
</div>

Microsoft.ACE.OLEDB.12.0 is not registered

Just install 32bit version of ADBE in passive mode:

run cmd in administrator mode and run this code:

AccessDatabaseEngine.exe /passive

http://www.microsoft.com/en-us/download/details.aspx?id=13255

window.open with headers

Use POST instead

Although it is easy to construct a GET query using window.open(), it's a bad idea (see below). One workaround is to create a form that submits a POST request. Like so:

<form id="helper" action="###/your_page###" style="display:none">
<inputtype="hidden" name="headerData" value="(default)">
</form>

<input type="button" onclick="loadNnextPage()" value="Click me!">

<script>
function loadNnextPage() {
  document.getElementById("helper").headerData.value = "New";
  document.getElementById("helper").submit();
}
</script>

Of course you will need something on the server side to handle this; as others have suggested you could create a "proxy" script that sends headers on your behalf and returns the results.

Problems with GET

  • Query strings get stored in browser history,
  • can be shoulder-surfed
  • copy-pasted,
  • and often you don't want it to be easy to "refresh" the same transaction.

Compare two files line by line and generate the difference in another file

diff(1) is not the answer, but comm(1) is.

NAME
       comm - compare two sorted files line by line

SYNOPSIS
       comm [OPTION]... FILE1 FILE2

...

       -1     suppress lines unique to FILE1

       -2     suppress lines unique to FILE2

       -3     suppress lines that appear in both files

So

comm -2 -3 file1 file2 > file3

The input files must be sorted. If they are not, sort them first. This can be done with a temporary file, or...

comm -2 -3 <(sort file1) <(sort file2) > file3

provided that your shell supports process substitution (bash does).

How to save a list to a file and read it as a list type?

You can use pickle module for that. This module have two methods,

  1. Pickling(dump): Convert Python objects into string representation.
  2. Unpickling(load): Retrieving original objects from stored string representstion.

https://docs.python.org/3.3/library/pickle.html

Code:

>>> import pickle
>>> l = [1,2,3,4]
>>> with open("test.txt", "wb") as fp:   #Pickling
...   pickle.dump(l, fp)
... 
>>> with open("test.txt", "rb") as fp:   # Unpickling
...   b = pickle.load(fp)
... 
>>> b
[1, 2, 3, 4]

Also Json

  1. dump/dumps: Serialize
  2. load/loads: Deserialize

https://docs.python.org/3/library/json.html

Code:

>>> import json
>>> with open("test.txt", "w") as fp:
...     json.dump(l, fp)
...
>>> with open("test.txt", "r") as fp:
...     b = json.load(fp)
...
>>> b
[1, 2, 3, 4]

Select unique or distinct values from a list in UNIX shell script

Unique, as requested, (but not sorted);
uses fewer system resources for less than ~70 elements (as tested with time);
written to take input from stdin,
(or modify and include in another script):
(Bash)

bag2set () {
    # Reduce a_bag to a_set.
    local -i i j n=${#a_bag[@]}
    for ((i=0; i < n; i++)); do
        if [[ -n ${a_bag[i]} ]]; then
            a_set[i]=${a_bag[i]}
            a_bag[i]=$'\0'
            for ((j=i+1; j < n; j++)); do
                [[ ${a_set[i]} == ${a_bag[j]} ]] && a_bag[j]=$'\0'
            done
        fi
    done
}
declare -a a_bag=() a_set=()
stdin="$(</dev/stdin)"
declare -i i=0
for e in $stdin; do
    a_bag[i]=$e
    i=$i+1
done
bag2set
echo "${a_set[@]}"

PHP new line break in emails

Try \r\n in place of \n

The difference between \n and \r\n

It should be noted that this is applicable to line returns in emails. For other scenarios, please refer to rokjarc's answer.

Reference an Element in a List of Tuples

Here's a quick example:

termList = []
termList.append(('term1', [1,2,3,4]))
termList.append(('term2', [5,6,7,8]))
termList.append(('term3', [9,10,11,12]))

result = [x[1] for x in termList if x[0] == 'term3']

print(result)

What are the differences between git branch, fork, fetch, merge, rebase and clone?

Here is Oliver Steele's image of how it all fits together:

enter image description here

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

My site configuration file is example.conf in sites-available folder So you can create a symbolic link as

ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

jQuery: Setting select list 'selected' based on text, failing strangely

If you want to selected value on drop-down text bases so you should use below changes: Here below is example and country name is dynamic:

    <select id="selectcountry">
    <option value="1">India</option>
    <option value="2">Ireland</option>
    </select>
    <script>
     var country_name ='India'
     $('#selectcountry').find('option:contains("' + country_name + '")').attr('selected', 'selected');
    </script>

Transport security has blocked a cleartext HTTP

?? Set Allow Arbitrary Loads to NO !!!

You must always use HTTPS for your networking stuff. But if you really can't, just add an exception to the info.plist

For example, if you are using http://google.com and getting that error, You MUST change it to https://google.com (with s) since it supports perfectly.

But if you can't somehow, (and you cant convince backend developers to support SSL), add JUST this unsecured domain to the info.plist (instead of making it available for ALL UNSECURE NET!)

Expception

Android Studio - ADB Error - "...device unauthorized. Please check the confirmation dialog on your device."

I've got the same message too. In my case, I have changed my dev environment to another notebook pc and my device is samsung galaxy note 2014 edition. My OS is windows 7

My galaxy note condition listed as following

  • developer option activated
  • USB debugging checked

The error message was "device unauthorized. Please check the..."

In general, the location of the default android setting was C:/Users/Your_login_name/.android then I copied and pasted all files in the '.android' folder to my new pc's setting folder.

After that the problem was gone.

I think the problem was adbkey file mismatched. Also, I didn't have any menu name such as revoke adb authorization.

Is it possible to set the equivalent of a src attribute of an img tag in CSS?

i used the empty div solution, with this CSS:

#throbber {
    background-image: url(/Content/pictures/ajax-loader.gif);
    background-repeat: no-repeat;
    width: 48px;
    height: 48px;
    min-width: 48px;
    min-height: 48px;
}

HTML:

<div id="throbber"></div>

Python IndentationError unindent does not match any outer indentation level

I had the same problem quite a few times. It happened especially when i tried to paste a few lines of code from an editor online, the spaces are not registered properly as 'tabs' or 'spaces'.

However the fix was quite simple. I just had to remove the spacing across all the lines of code in that specific set and space it again with the tabs correctly. This fixed my problem.

Refresh Page C# ASP.NET

Response.Redirect(Request.Url.ToString());

Java Currency Number format

I know this is an old question but...

import java.text.*;

public class FormatCurrency
{
    public static void main(String[] args)
    {
        double price = 123.4567;
        DecimalFormat df = new DecimalFormat("#.##");
        System.out.print(df.format(price));
    }
}

VS 2012: Scroll Solution Explorer to current file

Yes, you can find that under

Tools - > Options - > Projects and Solutions - > Track Active Item in Solution Explorer

It's off by default (as you've noticed), but once it's on, Solution Explorer will expand folders and highlight the current document as you switch between files.

Subset dataframe by multiple logical conditions of rows to remove

You can also accomplish this by breaking things up into separate logical statements by including & to separate the statements.

subset(my.df, my.df$v1 != "b" & my.df$v1 != "d" & my.df$v1 != "e")

This is not elegant and takes more code but might be more readable to newer R users. As pointed out in a comment above, subset is a "convenience" function that is best used when working interactively.

java.net.BindException: Address already in use: JVM_Bind <null>:80

I completely forgot that I had previously installed another version of Apache Tomcat, which was causing this problem. So, just try uninstalling the previous version. Hope it helps.

SQL query for extracting year from a date

SELECT date_column_name FROM table_name WHERE EXTRACT(YEAR FROM date_column_name) = 2020

Excel VBA - Sum up a column

I have a label on my form receiving the sum of numbers from Column D in Sheet1. I am only interested in rows 2 to 50, you can use a row counter if your row count is dynamic. I have some blank entries as well in column D and they are ignored.

Me.lblRangeTotal = Application.WorksheetFunction.Sum(ThisWorkbook.Sheets("Sheet1").Range("D2:D50"))

Java Error: illegal start of expression

public static int [] locations={1,2,3};

public static test dot=new test();

Declare the above variables above the main method and the code compiles fine.

public static void main(String[] args){