Programs & Examples On #Apple expose

Deleting an element from an array in PHP

Remove an array element based on a key:

Use the unset function like below:

$a = array(
       'salam',
       '10',
       1
);

unset($a[1]);

print_r($a);

/*

    Output:

        Array
        (
            [0] => salam
            [2] => 1
        )

*/

Remove an array element based on value:

Use the array_search function to get an element key and use the above manner to remove an array element like below:

$a = array(
       'salam',
       '10',
       1
);

$key = array_search(10, $a);

if ($key !== false) {
    unset($a[$key]);
}

print_r($a);

/*

    Output:

        Array
        (
            [0] => salam
            [2] => 1
        )

*/

Oracle 'Partition By' and 'Row_Number' keyword

I know this is an old thread but PARTITION is the equiv of GROUP BY not ORDER BY. ORDER BY in this function is . . . ORDER BY. It's just a way to create uniqueness out of redundancy by adding a sequence number. Or you may eliminate the other redundant records by the WHERE clause when referencing the aliased column for the function. However, DISTINCT in the SELECT statement would probably accomplish the same thing in that regard.

Raise error in a Bash script

Here's a simple trap that prints the last argument of whatever failed to STDERR, reports the line it failed on, and exits the script with the line number as the exit code. Note these are not always great ideas, but this demonstrates some creative application you could build on.

trap 'echo >&2 "$_ at $LINENO"; exit $LINENO;' ERR

I put that in a script with a loop to test it. I just check for a hit on some random numbers; you might use actual tests. If I need to bail, I call false (which triggers the trap) with the message I want to throw.

For elaborated functionality, have the trap call a processing function. You can always use a case statement on your arg ($_) if you need to do more cleanup, etc. Assign to a var for a little syntactic sugar -

trap 'echo >&2 "$_ at $LINENO"; exit $LINENO;' ERR
throw=false
raise=false

while :
do x=$(( $RANDOM % 10 ))
   case "$x" in
   0) $throw "DIVISION BY ZERO" ;;
   3) $raise "MAGIC NUMBER"     ;;
   *) echo got $x               ;;
   esac
done

Sample output:

# bash tst
got 2
got 8
DIVISION BY ZERO at 6
# echo $?
6

Obviously, you could

runTest1 "Test1 fails" # message not used if it succeeds

Lots of room for design improvement.

The draw backs include the fact that false isn't pretty (thus the sugar), and other things tripping the trap might look a little stupid. Still, I like this method.

Search and replace a particular string in a file using Perl

You could also do this:

#!/usr/bin/perl

use strict;
use warnings;

$^I = '.bak'; # create a backup copy 

while (<>) {
   s/<PREF>/ABCD/g; # do the replacement
   print; # print to the modified file
}

Invoke the script with by

./script.pl input_file

You will get a file named input_file, containing your changes, and a file named input_file.bak, which is simply a copy of the original file.

How can I Remove .DS_Store files from a Git repository?

Step 1

This will remove every .DS_Store file in a directory (including subdirectories)

find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch

Step 2

Add this to .gitignore to prevent any DS_Store files in the root directory and every subdirectory from going to git!

**/.DS_Store

From the git docs:

  • A leading "**" followed by a slash means match in all directories. For example, "**/foo" matches file or directory "foo" anywhere, the same as pattern "foo". "**/foo/bar" matches file or directory "bar" anywhere that is directly under directory "foo".

Adding days to a date in Java

Calendar cal = Calendar.getInstance();    
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.YEAR, 2012);
cal.add(Calendar.DAY_OF_MONTH, 5);

You can also substract days like Calendar.add(Calendar.DAY_OF_MONTH, -5);

When to create variables (memory management)

It's really a matter of opinion. In your example, System.out.println(5) would be slightly more efficient, as you only refer to the number once and never change it. As was said in a comment, int is a primitive type and not a reference - thus it doesn't take up much space. However, you might want to set actual reference variables to null only if they are used in a very complicated method. All local reference variables are garbage collected when the method they are declared in returns.

getting the X/Y coordinates of a mouse click on an image with jQuery

You can use pageX and pageY to get the position of the mouse in the window. You can also use jQuery's offset to get the position of an element.

So, it should be pageX - offset.left for how far from the left of the image and pageY - offset.top for how far from the top of the image.

Here is an example:

$(document).ready(function() {
  $('img').click(function(e) {
    var offset = $(this).offset();
    alert(e.pageX - offset.left);
    alert(e.pageY - offset.top);
  });
});

I've made a live example here and here is the source.

To calculate how far from the bottom or right, you would have to use jQuery's width and height methods.

PHP - Getting the index of a element from a array

an array does not contain index when elements are associative. An array in php can contain mixed values like this:

$var = array("apple", "banana", "foo" => "grape", "carrot", "bar" => "donkey");   
print_r($var);

Gives you:

Array
(
    [0] => apple
    [1] => banana
    [foo] => grape
    [2] => carrot
    [bar] => donkey
)

What are you trying to achieve since you need the index value in an associative array?

PHP: If internet explorer 6, 7, 8 , or 9

Here is a great resource for detecting browsers in php: http://php.net/manual/en/function.get-browser.php

Here is one of the examples that seems the simplest:

<?php
function get_user_browser()
{
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    $ub = '';
    if(preg_match('/MSIE/i',$u_agent))
    {
        $ub = "ie";
    }
    elseif(preg_match('/Firefox/i',$u_agent))
    {
        $ub = "firefox";
    }
    elseif(preg_match('/Safari/i',$u_agent))
    {
        $ub = "safari";
    }
    elseif(preg_match('/Chrome/i',$u_agent))
    {
        $ub = "chrome";
    }
    elseif(preg_match('/Flock/i',$u_agent))
    {
        $ub = "flock";
    }
    elseif(preg_match('/Opera/i',$u_agent))
    {
        $ub = "opera";
    }

    return $ub;
}
?>

Then later in your code you could say something like

$browser = get_user_browser();
if($browser == "ie"){
    //do stuff
}

std::string to char*

Conversion in OOP style

converter.hpp

class StringConverter {
    public: static char * strToChar(std::string str);
};

converter.cpp

char * StringConverter::strToChar(std::string str)
{
    return (char*)str.c_str();
}

usage

StringConverter::strToChar("converted string")

Switch on Enum in Java

You might be using the enums incorrectly in the switch cases. In comparison with the above example by CoolBeans.. you might be doing the following:

switch(day) {
    case Day.MONDAY:
        // Something..
        break;
    case Day.FRIDAY:
        // Something friday
        break;
}

Make sure that you use the actual enum values instead of EnumType.EnumValue

Eclipse points out this mistake though..

Evaluating a mathematical expression in a string

The reason eval and exec are so dangerous is that the default compile function will generate bytecode for any valid python expression, and the default eval or exec will execute any valid python bytecode. All the answers to date have focused on restricting the bytecode that can be generated (by sanitizing input) or building your own domain-specific-language using the AST.

Instead, you can easily create a simple eval function that is incapable of doing anything nefarious and can easily have runtime checks on memory or time used. Of course, if it is simple math, than there is a shortcut.

c = compile(stringExp, 'userinput', 'eval')
if c.co_code[0]==b'd' and c.co_code[3]==b'S':
    return c.co_consts[ord(c.co_code[1])+ord(c.co_code[2])*256]

The way this works is simple, any constant mathematic expression is safely evaluated during compilation and stored as a constant. The code object returned by compile consists of d, which is the bytecode for LOAD_CONST, followed by the number of the constant to load (usually the last one in the list), followed by S, which is the bytecode for RETURN_VALUE. If this shortcut doesn't work, it means that the user input isn't a constant expression (contains a variable or function call or similar).

This also opens the door to some more sophisticated input formats. For example:

stringExp = "1 + cos(2)"

This requires actually evaluating the bytecode, which is still quite simple. Python bytecode is a stack oriented language, so everything is a simple matter of TOS=stack.pop(); op(TOS); stack.put(TOS) or similar. The key is to only implement the opcodes that are safe (loading/storing values, math operations, returning values) and not unsafe ones (attribute lookup). If you want the user to be able to call functions (the whole reason not to use the shortcut above), simple make your implementation of CALL_FUNCTION only allow functions in a 'safe' list.

from dis import opmap
from Queue import LifoQueue
from math import sin,cos
import operator

globs = {'sin':sin, 'cos':cos}
safe = globs.values()

stack = LifoQueue()

class BINARY(object):
    def __init__(self, operator):
        self.op=operator
    def __call__(self, context):
        stack.put(self.op(stack.get(),stack.get()))

class UNARY(object):
    def __init__(self, operator):
        self.op=operator
    def __call__(self, context):
        stack.put(self.op(stack.get()))


def CALL_FUNCTION(context, arg):
    argc = arg[0]+arg[1]*256
    args = [stack.get() for i in range(argc)]
    func = stack.get()
    if func not in safe:
        raise TypeError("Function %r now allowed"%func)
    stack.put(func(*args))

def LOAD_CONST(context, arg):
    cons = arg[0]+arg[1]*256
    stack.put(context['code'].co_consts[cons])

def LOAD_NAME(context, arg):
    name_num = arg[0]+arg[1]*256
    name = context['code'].co_names[name_num]
    if name in context['locals']:
        stack.put(context['locals'][name])
    else:
        stack.put(context['globals'][name])

def RETURN_VALUE(context):
    return stack.get()

opfuncs = {
    opmap['BINARY_ADD']: BINARY(operator.add),
    opmap['UNARY_INVERT']: UNARY(operator.invert),
    opmap['CALL_FUNCTION']: CALL_FUNCTION,
    opmap['LOAD_CONST']: LOAD_CONST,
    opmap['LOAD_NAME']: LOAD_NAME
    opmap['RETURN_VALUE']: RETURN_VALUE,
}

def VMeval(c):
    context = dict(locals={}, globals=globs, code=c)
    bci = iter(c.co_code)
    for bytecode in bci:
        func = opfuncs[ord(bytecode)]
        if func.func_code.co_argcount==1:
            ret = func(context)
        else:
            args = ord(bci.next()), ord(bci.next())
            ret = func(context, args)
        if ret:
            return ret

def evaluate(expr):
    return VMeval(compile(expr, 'userinput', 'eval'))

Obviously, the real version of this would be a bit longer (there are 119 opcodes, 24 of which are math related). Adding STORE_FAST and a couple others would allow for input like 'x=5;return x+x or similar, trivially easily. It can even be used to execute user-created functions, so long as the user created functions are themselves executed via VMeval (don't make them callable!!! or they could get used as a callback somewhere). Handling loops requires support for the goto bytecodes, which means changing from a for iterator to while and maintaining a pointer to the current instruction, but isn't too hard. For resistance to DOS, the main loop should check how much time has passed since the start of the calculation, and certain operators should deny input over some reasonable limit (BINARY_POWER being the most obvious).

While this approach is somewhat longer than a simple grammar parser for simple expressions (see above about just grabbing the compiled constant), it extends easily to more complicated input, and doesn't require dealing with grammar (compile take anything arbitrarily complicated and reduces it to a sequence of simple instructions).

react change class name on state change

Below is a fully functional example of what I believe you're trying to do (with a functional snippet).

Explanation

Based on your question, you seem to be modifying 1 property in state for all of your elements. That's why when you click on one, all of them are being changed.

In particular, notice that the state tracks an index of which element is active. When MyClickable is clicked, it tells the Container its index, Container updates the state, and subsequently the isActive property of the appropriate MyClickables.

Example

_x000D_
_x000D_
class Container extends React.Component {_x000D_
  state = {_x000D_
    activeIndex: null_x000D_
  }_x000D_
_x000D_
  handleClick = (index) => this.setState({ activeIndex: index })_x000D_
_x000D_
  render() {_x000D_
    return <div>_x000D_
      <MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />_x000D_
      <MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>_x000D_
      <MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>_x000D_
    </div>_x000D_
  }_x000D_
}_x000D_
_x000D_
class MyClickable extends React.Component {_x000D_
  handleClick = () => this.props.onClick(this.props.index)_x000D_
  _x000D_
  render() {_x000D_
    return <button_x000D_
      type='button'_x000D_
      className={_x000D_
        this.props.isActive ? 'active' : 'album'_x000D_
      }_x000D_
      onClick={ this.handleClick }_x000D_
    >_x000D_
      <span>{ this.props.name }</span>_x000D_
    </button>_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Container />, document.getElementById('app'))
_x000D_
button {_x000D_
  display: block;_x000D_
  margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
.album>span:after {_x000D_
  content: ' (an album)';_x000D_
}_x000D_
_x000D_
.active {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.active>span:after {_x000D_
  content: ' ACTIVE';_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

Update: "Loops"

In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.

// New render method for `Container`
render() {
  const clickables = [
    { name: "a" },
    { name: "b" },
    { name: "c" },
  ]

  return <div>
      { clickables.map(function(clickable, i) {
          return <MyClickable key={ clickable.name }
            name={ clickable.name }
            index={ i }
            isActive={ this.state.activeIndex === i }
            onClick={ this.handleClick }
          />
        } )
      }
  </div>
}

Initializing C dynamic arrays

You need to allocate a block of memory and use it as an array as:

int *arr = malloc (sizeof (int) * n); /* n is the length of the array */
int i;

for (i=0; i<n; i++)
{
  arr[i] = 0;
}

If you need to initialize the array with zeros you can also use the memset function from C standard library (declared in string.h).

memset (arr, 0, sizeof (int) * n);

Here 0 is the constant with which every locatoin of the array will be set. Note that the last argument is the number of bytes to be set the the constant. Because each location of the array stores an integer therefore we need to pass the total number of bytes as this parameter.

Also if you want to clear the array to zeros, then you may want to use calloc instead of malloc. calloc will return the memory block after setting the allocated byte locations to zero.

After you have finished, free the memory block free (arr).

EDIT1

Note that if you want to assign a particular integer in locations of an integer array using memset then it will be a problem. This is because memset will interpret the array as a byte array and assign the byte you have given, to every byte of the array. So if you want to store say 11243 in each location then it will not be possible.

EDIT2

Also note why every time setting an int array to 0 with memset may not work: Why does "memset(arr, -1, sizeof(arr)/sizeof(int))" not clear an integer array to -1? as pointed out by @Shafik Yaghmour

Are querystring parameters secure in HTTPS (HTTP + SSL)?

remember, SSL/TLS operates at the Transport Layer, so all the crypto goo happens under the application-layer HTTP stuff.

http://en.wikipedia.org/wiki/File:IP_stack_connections.svg

that's the long way of saying, "Yes!"

What is process.env.PORT in Node.js?

In many environments (e.g. Heroku), and as a convention, you can set the environment variable PORT to tell your web server what port to listen on.

So process.env.PORT || 3000 means: whatever is in the environment variable PORT, or 3000 if there's nothing there.

So you pass that to app.listen, or to app.set('port', ...), and that makes your server able to accept a "what port to listen on" parameter from the environment.

If you pass 3000 hard-coded to app.listen(), you're always listening on port 3000, which might be just for you, or not, depending on your requirements and the requirements of the environment in which you're running your server.

The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

I forgot to select the column (or set/map the property to a column value):

IQueryable<SampleTable> queryable = from t in dbcontext.SampleTable
                                    where ...
                                    select new DataModel { Name = t.Name };

Calling queryable.OrderBy("Id") will throw exception, even though DataModel has property Id defined.

The correct query is:

IQueryable<SampleTable> queryable = from t in dbcontext.SampleTable
                                    where ...
                                    select new DataModel { Name = t.Name, Id = t.Id };

How can I change a file's encoding with vim?

From the doc:

:write ++enc=utf-8 russian.txt

So you should be able to change the encoding as part of the write command.

how to configure config.inc.php to have a loginform in phpmyadmin

$cfg['Servers'][$i]['AllowNoPassword'] = false;

how to fetch array keys with jQuery?

Use an object (key/value pairs, the nearest JavaScript has to an associative array) for this and not the array object. Other than that, I believe that is the most elegant way

var foo = {};
foo['alfa'] = "first item";
foo['beta'] = "second item";

for (var key in foo) {
        console.log(key);
}

Note: JavaScript doesn't guarantee any particular order for the properties. So you cannot expect the property that was defined first to appear first, it might come last.

EDIT:

In response to your comment, I believe that this article best sums up the cases for why arrays in JavaScript should not be used in this fashion -

How to revert to origin's master branch's version of file

I've faced same problem and came across to this thread but my problem was with upstream. Below git command worked for me.

Syntax

git checkout {remoteName}/{branch} -- {../path/file.js}

Example

git checkout upstream/develop -- public/js/index.js

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

"Case" can return single value only, but you can use complex type:

create type foo as (a int, b text);
select (case 1 when 1 then (1,'qq')::foo else (2,'ww')::foo end).*;

Why doesn't the height of a container element increase if it contains floated elements?

The floated elements do not add to the height of the container element, and hence if you don't clear them, container height won't increase...

I'll show you visually:

enter image description here

enter image description here

enter image description here

More Explanation:

<div>
  <div style="float: left;"></div>
  <div style="width: 15px;"></div> <!-- This will shift 
                                        besides the top div. Why? Because of the top div 
                                        is floated left, making the 
                                        rest of the space blank -->

  <div style="clear: both;"></div> 
  <!-- Now in order to prevent the next div from floating beside the top ones, 
       we use `clear: both;`. This is like a wall, so now none of the div's 
       will be floated after this point. The container height will now also include the 
       height of these floated divs -->
  <div></div>
</div>

You can also add overflow: hidden; on container elements, but I would suggest you use clear: both; instead.

Also if you might like to self-clear an element you can use

.self_clear:after {
  content: "";
  clear: both;
  display: table;
}

How Does CSS Float Work?

What is float exactly and what does it do?

  • The float property is misunderstood by most beginners. Well, what exactly does float do? Initially, the float property was introduced to flow text around images, which are floated left or right. Here's another explanation by @Madara Uchicha.

    So, is it wrong to use the float property for placing boxes side by side? The answer is no; there is no problem if you use the float property in order to set boxes side by side.

  • Floating an inline or block level element will make the element behave like an inline-block element.

    Demo

  • If you float an element left or right, the width of the element will be limited to the content it holds, unless width is defined explicitly ...

  • You cannot float an element center. This is the biggest issue I've always seen with beginners, using float: center;, which is not a valid value for the float property. float is generally used to float/move content to the very left or to the very right. There are only four valid values for float property i.e left, right, none (default) and inherit.

  • Parent element collapses, when it contains floated child elements, in order to prevent this, we use clear: both; property, to clear the floated elements on both the sides, which will prevent the collapsing of the parent element. For more information, you can refer my another answer here.

  • (Important) Think of it where we have a stack of various elements. When we use float: left; or float: right; the element moves above the stack by one. Hence the elements in the normal document flow will hide behind the floated elements because it is on stack level above the normal floated elements. (Please don't relate this to z-index as that is completely different.)


Taking a case as an example to explain how CSS floats work, assuming we need a simple 2 column layout with a header, footer, and 2 columns, so here is what the blueprint looks like...

enter image description here

In the above example, we will be floating only the red boxes, either you can float both to the left, or you can float on to left, and another to right as well, depends on the layout, if it's 3 columns, you may float 2 columns to left where another one to the right so depends, though in this example, we have a simplified 2 column layout so will float one to left and the other to the right.

Markup and styles for creating the layout explained further down...

<div class="main_wrap">
    <header>Header</header>
    <div class="wrapper clear">
        <div class="floated_left">
            This<br />
            is<br />
            just<br />
            a<br />
            left<br />
            floated<br />
            column<br />
        </div>
        <div class="floated_right">
            This<br />
            is<br />
            just<br />
            a<br />
            right<br />
            floated<br />
            column<br />
        </div>
    </div>
    <footer>Footer</footer>
</div>

* {
    -moz-box-sizing: border-box;       /* Just for demo purpose */
    -webkkit-box-sizing: border-box;   /* Just for demo purpose */
    box-sizing: border-box;            /* Just for demo purpose */
    margin: 0;
    padding: 0;
}

.main_wrap {
    margin: 20px;
    border: 3px solid black;
    width: 520px;
}

header, footer {
    height: 50px;
    border: 3px solid silver;
    text-align: center;
    line-height: 50px;
}

.wrapper {
    border: 3px solid green;
}

.floated_left {
    float: left;
    width: 200px;
    border: 3px solid red;
}

.floated_right {
    float: right;
    width: 300px;
    border: 3px solid red;
}

.clear:after {
    clear: both;
    content: "";
    display: table;
}

Let's go step by step with the layout and see how float works..

First of all, we use the main wrapper element, you can just assume that it's your viewport, then we use header and assign a height of 50px so nothing fancy there. It's just a normal non floated block level element which will take up 100% horizontal space unless it's floated or we assign inline-block to it.

The first valid value for float is left so in our example, we use float: left; for .floated_left, so we intend to float a block to the left of our container element.

Column floated to the left

And yes, if you see, the parent element, which is .wrapper is collapsed, the one you see with a green border didn't expand, but it should right? Will come back to that in a while, for now, we have got a column floated to left.

Coming to the second column, lets it float this one to the right

Another column floated to the right

Here, we have a 300px wide column which we float to the right, which will sit beside the first column as it's floated to the left, and since it's floated to the left, it created empty gutter to the right, and since there was ample of space on the right, our right floated element sat perfectly beside the left one.

Still, the parent element is collapsed, well, let's fix that now. There are many ways to prevent the parent element from getting collapsed.

  • Add an empty block level element and use clear: both; before the parent element ends, which holds floated elements, now this one is a cheap solution to clear your floating elements which will do the job for you but, I would recommend not to use this.

Add, <div style="clear: both;"></div> before the .wrapper div ends, like

<div class="wrapper clear">
    <!-- Floated columns -->
    <div style="clear: both;"></div>
</div>

Demo

Well, that fixes very well, no collapsed parent anymore, but it adds unnecessary markup to the DOM, so some suggest, to use overflow: hidden; on the parent element holding floated child elements which work as intended.

Use overflow: hidden; on .wrapper

.wrapper {
    border: 3px solid green;
    overflow: hidden;
}

Demo

That saves us an element every time we need to clear float but as I tested various cases with this, it failed in one particular one, which uses box-shadow on the child elements.

Demo (Can't see the shadow on all 4 sides, overflow: hidden; causes this issue)

So what now? Save an element, no overflow: hidden; so go for a clear fix hack, use the below snippet in your CSS, and just as you use overflow: hidden; for the parent element, call the class below on the parent element to self-clear.

.clear:after {
    clear: both;
    content: "";
    display: table;
}

<div class="wrapper clear">
    <!-- Floated Elements -->
</div>

Demo

Here, shadow works as intended, also, it self-clears the parent element which prevents to collapse.

And lastly, we use footer after we clear the floated elements.

Demo


When is float: none; used anyways, as it is the default, so any use to declare float: none;?

Well, it depends, if you are going for a responsive design, you will use this value a lot of times, when you want your floated elements to render one below another at a certain resolution. For that float: none; property plays an important role there.


Few real-world examples of how float is useful.

  • The first example we already saw is to create one or more than one column layouts.
  • Using img floated inside p which will enable our content to flow around.

Demo (Without floating img)

Demo 2 (img floated to the left)

  • Using float for creating horizontal menu - Demo

Float second element as well, or use `margin`

Last but not the least, I want to explain this particular case where you float only single element to the left but you do not float the other, so what happens?

Suppose if we remove float: right; from our .floated_right class, the div will be rendered from extreme left as it isn't floated.

Demo

So in this case, either you can float the to the left as well

OR

You can use margin-left which will be equal to the size of the left floated column i.e 200px wide.

How to connect mySQL database using C++

I had to include -lmysqlcppconn to my build in order to get it to work.

Google Maps Api v3 - find nearest markers

First you have to add the eventlistener

google.maps.event.addListener(map, 'click', find_closest_marker);

Then create a function that loops through the array of markers and uses the haversine formula to calculate the distance of each marker from the click.

function rad(x) {return x*Math.PI/180;}
function find_closest_marker( event ) {
    var lat = event.latLng.lat();
    var lng = event.latLng.lng();
    var R = 6371; // radius of earth in km
    var distances = [];
    var closest = -1;
    for( i=0;i<map.markers.length; i++ ) {
        var mlat = map.markers[i].position.lat();
        var mlng = map.markers[i].position.lng();
        var dLat  = rad(mlat - lat);
        var dLong = rad(mlng - lng);
        var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(rad(lat)) * Math.cos(rad(lat)) * Math.sin(dLong/2) * Math.sin(dLong/2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        var d = R * c;
        distances[i] = d;
        if ( closest == -1 || d < distances[closest] ) {
            closest = i;
        }
    }

    alert(map.markers[closest].title);
}

This keeps track of the closest markers and alerts its title.

I have my markers as an array on my map object

Get login username in java

System.getProperty("user.name")

Access denied for root user in MySQL command-line

this might help on Ubuntu:

go to /etc/mysql/my.cnf and comment this line:

bind-address           = 127.0.0.1

Hope this helps someone, I've been searching for this a while too

Cheers

Why does AngularJS include an empty option in select?

Something similar was happening to me too and was caused by an upgrade to angular 1.5.ng-init seems to be being parsed for type in newer versions of Angular. In older Angular ng-init="myModelName=600" would map to an option with value "600" i.e. <option value="600">First</option> but in Angular 1.5 it won't find this as it seems to be expecting to find an option with value 600 i.e <option value=600>First</option>. Angular would then insert a random first item:

<option value="? number:600 ?"></option>

Angular < 1.2.x

<select ng-model="myModelName" ng-init="myModelName=600">
  <option value="600">First</option>
  <option value="700">Second</option>
</select>

Angular > 1.2

<select ng-model="myModelName" ng-init="myModelName='600'">
  <option value="600">First</option>
  <option value="700">Second</option>
</select>

Simplest way to read json from a URL in java

The easiest way: Use gson, google's own goto json library. https://code.google.com/p/google-gson/

Here is a sample. I'm going to this free geolocator website and parsing the json and displaying my zipcode. (just put this stuff in a main method to test it out)

    String sURL = "http://freegeoip.net/json/"; //just a string

    // Connect to the URL using java's native library
    URL url = new URL(sURL);
    URLConnection request = url.openConnection();
    request.connect();

    // Convert to a JSON object to print data
    JsonParser jp = new JsonParser(); //from gson
    JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
    JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object. 
    String zipcode = rootobj.get("zip_code").getAsString(); //just grab the zipcode

PHP error: Notice: Undefined index:

I did define all the variables that was the first thing I checked. I know it's not required in PHP, but old habits die hard. Then I sanatized the info like this:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name1"])) {
    $name1Err = " First Name is a required field.";
  } else {
      $name1 = test_input($_POST["name1"]);
    // check if name only contains letters and whitespace
      if (!preg_match("/^[a-zA-Z ]*$/",$name1)) {
      $name1Err = "Only letters and white space allowed";

of course test_input is another function that does a trim, strilashes, and htmlspecialchars. I think the input is pretty well sanitized. Not trying to be rude just showing what I did. When it came to the email I also checked to see if it was the proper format. I think the real answer is in the fact that some variables are local and some are global. I have got it working without errors for now so, while I'm extremely busy right now I'll accept shutting off errors as my answer. Don't worry I'll figure it out it's just not vitally important right now!

copy-item With Alternate Credentials

that evidently powershell's cmdlets such as copy-item, test-path, etc do not support alternate credentials...

It looks like they do here, copy-item certainly includes a -Credential parameter.

PS C:\> gcm -syn copy-item
Copy-Item [-Path] <String[]> [[-Destination] <String>] [-Container] [-Force] [-Filter <String>] [-I
nclude <String[]>] [-Exclude <String[]>] [-Recurse] [-PassThru] [-Credential <PSCredential>] [...]

Bulk Record Update with SQL

Or you can simply update without using join like this:

Update t1 set  t1.Description = t2.Description from @tbl2 t2,tbl1 t1
where t1.ID= t2.ID

PHP remove all characters before specific string

You can use strstr to do this.

echo strstr($str, 'www/audio');

Unable to show a Git tree in terminal

How can you get the tree-like view of commits in terminal?

git log --graph --oneline --all

is a good start.

You may get some strange letters. They are ASCII codes for colors and structure. To solve this problem add the following to your .bashrc:

export LESS="-R"

such that you do not need use Tig's ASCII filter by

git log --graph --pretty=oneline --abbrev-commit | tig   // Masi needed this 

The article text-based graph from Git-ready contains other options:

git log --graph --pretty=oneline --abbrev-commit

git log graph

Regarding the article you mention, I would go with Pod's answer: ad-hoc hand-made output.


Jakub Narebski mentions in the comments tig, a ncurses-based text-mode interface for git. See their releases.
It added a --graph option back in 2007.

In Java, can you modify a List while iterating through it?

Use Java 8's removeIf(),

To remove safely,

letters.removeIf(x -> !x.equals("A"));

READ_EXTERNAL_STORAGE permission for Android

You have to ask for the permission at run time:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
        && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
            REQUEST_PERMISSION);
    dialog.dismiss();
    return;
}

And in the callback below you can access the storage without a problem.

@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_PERMISSION) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Permission granted.
        } else {
            // User refused to grant permission.
        }
    }
}

Correctly ignore all files recursively under a specific folder except for a specific file type

The best answer is to add a Resources/.gitignore file under Resources containing:

# Ignore any file in this directory except for this file and *.foo files
*
!/.gitignore
!*.foo

If you are unwilling or unable to add that .gitignore file, there is an inelegant solution:

# Ignore any file but *.foo under Resources. Update this if we add deeper directories
Resources/*
!Resources/*/
!Resources/*.foo
Resources/*/*
!Resources/*/*/
!Resources/*/*.foo
Resources/*/*/*
!Resources/*/*/*/
!Resources/*/*/*.foo
Resources/*/*/*/*
!Resources/*/*/*/*/
!Resources/*/*/*/*.foo

You will need to edit that pattern if you add directories deeper than specified.

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

try this...    
<script type="text/javascript">
    function test(){
    var av=document.getElementById("mytext").value;
    alert(av);
    }
    </script>

    <input type="text" value="" id="mytext">
    <input type="button" onclick="test()" value="go" />

In OS X Lion, LANG is not set to UTF-8, how to fix it?

I had this issue with MacOS High Sierria.

Screenshot 1

You can set up locale as well as language to UTF-8 format using below command :

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

Screenshot 2

Now in order to check whether locale environment is updated use below command :

Locale

Screenshot 3

How to Clear Console in Java?

You can easily implement clrscr() using simple for loop printing "\b".

Using VBA code, how to export Excel worksheets as image in Excel 2003?

Winand, Quality was also an issue for me so I did this:

For Each ws In ActiveWorkbook.Worksheets
    If ws.PageSetup.PrintArea <> "" Then
        'Reverse the effects of page zoom on the exported image
        zoom_coef = 100 / ws.Parent.Windows(1).Zoom
        areas = Split(ws.PageSetup.PrintArea, ",")
        areaNo = 0
        For Each a In areas
            Set area = ws.Range(a)
            ' Change xlPrinter to xlScreen to see zooming white space
            area.CopyPicture Appearance:=xlPrinter, Format:=xlPicture
            Set chartobj = ws.ChartObjects.Add(0, 0, area.Width * zoom_coef, area.Height * zoom_coef)
            chartobj.Chart.Paste
            'scale the image before export
            ws.Shapes(chartobj.Index).ScaleHeight 3, msoFalse, msoScaleFromTopLeft
            ws.Shapes(chartobj.Index).ScaleWidth 3, msoFalse, msoScaleFromTopLeft
            chartobj.Chart.Export ws.Name & "-" & areaNo & ".png", "png"
            chartobj.delete
            areaNo = areaNo + 1
        Next
    End If
Next

See here:https://robp30.wordpress.com/2012/01/11/improving-the-quality-of-excel-image-export/

How to save final model using keras?

You can save the best model using keras.callbacks.ModelCheckpoint()

Example:

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model_checkpoint_callback = keras.callbacks.ModelCheckpoint("best_Model.h5",save_best_only=True)
history = model.fit(x_train,y_train,
          epochs=10,
          validation_data=(x_valid,y_valid),
          callbacks=[model_checkpoint_callback])

This will save the best model in your working directory.

What's the difference between "app.render" and "res.render" in express.js?

along with these two variants, there is also jade.renderFile which generates html that need not be passed to the client.

usage-

var jade = require('jade');

exports.getJson = getJson;

function getJson(req, res) {
    var html = jade.renderFile('views/test.jade', {some:'json'});
    res.send({message: 'i sent json'});
}

getJson() is available as a route in app.js.

How do I skip an iteration of a `foreach` loop?

You could also flip your if test:


foreach ( int number in numbers )
{
     if ( number >= 0 )
     {
        //process number
     }
 }

How can I use jQuery in Greasemonkey?

If you want to use jQuery on a site where it is already included, this is the way to go (inspired by BrunoLM):

var $ = unsafeWindow.jQuery;

I know this wasn't the original intent of the question, but it is increasingly becoming a common case and you didn't explicitly exclude this case. ;)

jQuery event handlers always execute in order they were bound - any way around this?

Here's a solution for jQuery 1.4.x (unfortunately, the accepted answer didn't work for jquery 1.4.1)

$.fn.bindFirst = function(name, fn) {
    // bind as you normally would
    // don't want to miss out on any jQuery magic
    this.bind(name, fn);

    // Thanks to a comment by @Martin, adding support for
    // namespaced events too.
    var handlers = this.data('events')[name.split('.')[0]];
    // take out the handler we just inserted from the end
    var copy = {1: null};

    var last = 0, lastValue = null;
    $.each(handlers, function(name, value) {
        //console.log(name + ": " + value);
        var isNumber = !isNaN(name);
        if(isNumber) {last = name; lastValue = value;};

        var key = isNumber ? (parseInt(name) + 1) : name;
        copy[key] = value;
    });
    copy[1] = lastValue;
    this.data('events')[name.split('.')[0]] = copy;
};

How do I get list of methods in a Python class?

Say you want to know all methods associated with list class Just Type The following

 print (dir(list))

Above will give you all methods of list class

Is there any difference between GROUP BY and DISTINCT

MusiGenesis' response is functionally the correct one with regard to your question as stated; the SQL Server is smart enough to realize that if you are using "Group By" and not using any aggregate functions, then what you actually mean is "Distinct" - and therefore it generates an execution plan as if you'd simply used "Distinct."

However, I think it's important to note Hank's response as well - cavalier treatment of "Group By" and "Distinct" could lead to some pernicious gotchas down the line if you're not careful. It's not entirely correct to say that this is "not a question about aggregates" because you're asking about the functional difference between two SQL query keywords, one of which is meant to be used with aggregates and one of which is not.

A hammer can work to drive in a screw sometimes, but if you've got a screwdriver handy, why bother?

(for the purposes of this analogy, Hammer : Screwdriver :: GroupBy : Distinct and screw => get list of unique values in a table column)

How do I import an SQL file using the command line in MySQL?

For information, I just had the default root + without password. It didn't work with all previous answers.

  • I created a new user with all privileges and a password. It worked.

  • -ppassword WITHOUT SPACE.

How to get the function name from within that function?

Any constructor exposes a property name, which is the function name. You access the constructor via an instance (using new) or a prototype:

function Person() {
  console.log(this.constructor.name); //Person
}

var p = new Person();
console.log(p.constructor.name); //Person

console.log(Person.prototype.constructor.name);  //Person

Java double comparison epsilon

If you can use BigDecimal, then use it, else:

/**
  *@param precision number of decimal digits
  */
public static boolean areEqualDouble(double a, double b, int precision) {
   return Math.abs(a - b) <= Math.pow(10, -precision);
}

Getting Error "Form submission canceled because the form is not connected"

Quick answer : append the form to the body.

document.body.appendChild(form);

Or, if you're using jQuery as above: $(document.body).append(form);

Details : According to the HTML standards, if the form is not associated to the browsing context(document), the form submission will be aborted.

HTML SPEC see 4.10.21.3.2

In Chrome 56, this spec was applied.

Chrome code diff see @@ -347,9 +347,16 @@

P.S about your question #1. In my opinion, unlike ajax, form submission causes instant page move.
So, showing 'deprecated warning message' is almost impossible.
I also think it's unacceptable that this serious change is not included in the feature change list. Chrome 56 features - www.chromestatus.com/features#milestone%3D56

"Please provide a valid cache path" error in laravel

Try the following:

create these folders under storage/framework:

  • sessions
  • views
  • cache

Now it should work

Python argparse command line flags without arguments

Here's a quick way to do it, won't require anything besides sys.. though functionality is limited:

flag = "--flag" in sys.argv[1:]

[1:] is in case if the full file name is --flag

Get file size, image width and height before upload

A working jQuery validate example:

   $(function () {
        $('input[type=file]').on('change', function() {
            var $el = $(this);
            var files = this.files;
            var image = new Image();
            image.onload = function() {
                $el
                    .attr('data-upload-width', this.naturalWidth)
                    .attr('data-upload-height', this.naturalHeight);
            }

            image.src = URL.createObjectURL(files[0]);
        });

        jQuery.validator.unobtrusive.adapters.add('imageminwidth', ['imageminwidth'], function (options) {
            var params = {
                imageminwidth: options.params.imageminwidth.split(',')
            };

            options.rules['imageminwidth'] = params;
            if (options.message) {
                options.messages['imageminwidth'] = options.message;
            }
        });

        jQuery.validator.addMethod("imageminwidth", function (value, element, param) {
            var $el = $(element);
            if(!element.files && element.files[0]) return true;
            return parseInt($el.attr('data-upload-width')) >=  parseInt(param["imageminwidth"][0]);
        });

    } (jQuery));

Opening a folder in explorer and selecting a file

Use this method:

Process.Start(String, String)

First argument is an application (explorer.exe), second method argument are arguments of the application you run.

For example:

in CMD:

explorer.exe -p

in C#:

Process.Start("explorer.exe", "-p")

Programmatically change the src of an img tag

if you use the JQuery library use this instruction:

$("#imageID").attr('src', 'srcImage.jpg');

How to check if the key pressed was an arrow key in Java KeyListener?

Just to complete the answer (using the KeyEvent is the way to go) but up arrow is 38 and down arrow is 40 so:

    else if (e.getKeyCode()==38)
    {
            //Up arrow key code
    }
    else if (e.getKeyCode()==40)
    {
            //down arrow key code
    }

ReactJS - Add custom event listener to component

First off, custom events don't play well with React components natively. So you cant just say <div onMyCustomEvent={something}> in the render function, and have to think around the problem.

Secondly, after taking a peek at the documentation for the library you're using, the event is actually fired on document.body, so even if it did work, your event handler would never trigger.

Instead, inside componentDidMount somewhere in your application, you can listen to nv-enter by adding

document.body.addEventListener('nv-enter', function (event) {
    // logic
});

Then, inside the callback function, hit a function that changes the state of the component, or whatever you want to do.

Getting "cannot find Symbol" in Java project in Intellij

I was having the same problem except that I was importing the classes for which dependencies were not resolving somehow. I refreshed maven projects, Rebuild Project. It still did not resolve. Looks like IntelliJ was caching something incorrectly. I restarted IntelliJ and that resolved the dependencies. I guess it cleared the cache somehow.

Create database from command line

createdb is a command line utility which you can run from bash and not from psql. To create a database from psql, use the create database statement like so:

create database [databasename];

Note: be sure to always end your SQL statements with ;

How do I use WebRequest to access an SSL encrypted site using https?

This one worked for me:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

editing PATH variable on mac

use

~/.bash_profile

or

~/.MacOSX/environment.plist

(see Runtime Configuration Guidelines)

How to Set Focus on Input Field using JQuery

Try this, to set the focus to the first input field:

$(this).parent().siblings('div.bottom').find("input.post").focus();

SQL Server equivalent to MySQL enum data type?

The best solution I've found in this is to create a lookup table with the possible values as a primary key, and create a foreign key to the lookup table.

How to split a string in Ruby and get all items except the first one?

You probably mistyped a few things. From what I gather, you start with a string such as:

string = "test1, test2, test3, test4, test5"

Then you want to split it to keep only the significant substrings:

array = string.split(/, /)

And in the end you only need all the elements excluding the first one:

# We extract and remove the first element from array
first_element = array.shift

# Now array contains the expected result, you can check it with
puts array.inspect

Did that answer your question ?

GROUP BY + CASE statement

For TSQL I like to encapsulate case statements in an outer apply. This prevents me from having to have the case statement written twice, allows reference to the case statement by alias in future joins and avoids the need for positional references.

select oa.day, 
model.name, 
attempt.type, 
oa.result
COUNT(*) MyCount 
FROM attempt attempt, prod_hw_id prod_hw_id, model model
WHERE time >= '2013-11-06 00:00:00'  
AND time < '2013-11-07 00:00:00'
AND attempt.hard_id = prod_hw_id.hard_id
AND prod_hw_id.model_id = model.model_id
OUTER APPLY (
    SELECT CURRENT_DATE-1 AS day,
     CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END result
    ) oa    
group by oa.day, 
model.name, 
attempt.type, 
oa.result
order by model.name, attempt.type, oa.result;

Determining the version of Java SDK on the Mac

On modern macOS, the correct path is /Library/Java/JavaVirtualMachines.

You can also avail yourself of the command /usr/libexec/java_home, which will scan that directory for you and return a list.

Adding new line of data to TextBox

Because you haven't specified what front end (GUI technology) you're using it would be hard to make a specific recommendation. In WPF you could create a listbox and for each new line of chat add a new listboxitem to the end of the collection. This link provides some suggestions as to how you may achieve the same result in a winforms environment.

How can I insert a line break into a <Text> component in React Native?

You can do it as follows:

{'Create\nYour Account'}

chai test array equality doesn't work as expected

import chai from 'chai';
const arr1 = [2, 1];
const arr2 = [2, 1];
chai.expect(arr1).to.eql(arr2); // Will pass. `eql` is data compare instead of object compare.

iPhone and WireShark

I had to do something very similar to find out why my iPhone was bleeding cellular network data, eating 80% of my 500Mb allowance in a couple of days.

Unfortunately I had to packet sniff whilst on 3G/4G and couldn't rely on being on wireless. So if you need an "industrial" solution then this is how you sniff all traffic (not just http) on any network.

Basic recipe:

  1. Install VPN server
  2. Run packet sniffer on VPN server
  3. Connect iPhone to VPN server and perform operations
  4. Download .pcap from VPN server and use your favourite .pcap analyser on it.

Detailed'ish instructions:

  1. Get yourself a linux server, I used Fedora 20 64bit from Digirtal Ocean on a $5/month box
  2. Configure OpenVPN on it. OpenVPN has comprehensive instructions
  3. Ensure you configure the Routing all traffic through the VPN section
  4. Be aware the instructions for (3) are all iptables which has been superseded, at time of writing, by firewall-cmd. This website explains the firewall-cmd to use
  5. Check that you can connect your iPhone to the VPN. I did this by downloading the free OpenVPN software. I then set up a OpenVPN certificate. You can embed your ca, crt & key files by opening up and embedding the --- BEGIN CERTIFACTE --- ---- END CERTIFICATE --- in < ca > < /ca > < crt >< /crt>< key > < /key > blocks. Note that I had to do this in Mac with text editor, when I used notepad.exe on Win it didn't work. I then emailed this to my iphone and picked installed it.
  6. Check the iPhone connects to VPN and routes it's traffic through (google what's my IP should return the VPN server IP when you run it on iPhone)
  7. Now that you can connect go to your linux server & install wireshark (yum install wireshark)
  8. This installs tshark, which is a command line packet sniffer. Run this in the background with screen tshark -i tun0 -x -w capture.pcap -F pcap (assuming vpn device is tun0)
  9. Now when you want to capture traffic simply start the VPN on your machine
  10. When complete switch off the VPN
  11. Download the .pcap file from your server, and run analysis as you normally would. It's been decrypted on the server when it arrives so the traffic is viewable in plain text (obviously https still encrypted)

Note that the above implementation is not security focussed it's simply about getting a detailed packet capture of all of your iPhone's traffic on 3G/4G/Wireless networks

How to remove extension from string (only real extension!)

You can set the length of the regular expression pattern by using the {x,y} operator. {3,4} would match if the preceeding pattern occurs 3 or 4 times.

But I don't think you really need it. What will you do with a file named "This.is"?

Killing a process created with Python's subprocess.Popen()

Only use Popen kill method

process = subprocess.Popen(
    task.getExecutable(), 
    stdout=subprocess.PIPE, 
    stderr=subprocess.PIPE, 
    shell=True
)
process.kill()

How to get root view controller?

Unless you have a good reason, in your root controller do this:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(onTheEvent:)
                                             name:@"ABCMyEvent"
                                           object:nil];

And when you want to notify it:

[[NSNotificationCenter defaultCenter] postNotificationName:@"ABCMyEvent"
                                                object:self];                

How to find a parent with a known class in jQuery?

<div id="412412412" class="input-group date">
     <div class="input-group-prepend">
          <button class="btn btn-danger" type="button">Button Click</button>
          <input type="text" class="form-control" value="">
      </div>
</div>

In my situation, i use this code:

$(this).parent().closest('.date').attr('id')

Hope this help someone.

What should I set JAVA_HOME environment variable on macOS X 10.6?

I'm on Mac OS 10.6.8

The easiest solution works for me is simply put in

$ export JAVA_HOME=$(/usr/libexec/java_home)

To test whether it works, put in

$ echo $JAVA_HOME

it shows

/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home

you can also test

$ which java

How do I keep two side-by-side divs the same height?

I have tried almost all the mentioned methods above, but the flexbox solution won't work correctly with Safari, and the grid layout methods won't work correctly with older versions of IE.

This solution fits all screens and is cross-browser compatible:

.container {margin:15px auto;}
.container ul {margin:0 10px;}
.container li {width:30%; display: table-cell; background-color:#f6f7f7;box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.25);}

@media (max-width: 767px){
    .container li { display: inline-block; width:100%; min-height:auto!important;}
}

The above method will equal cells height, and for the smaller screens like mobile or tablet, we can use the @media method mentioned above.

Laravel 5.2 Missing required parameters for [Route: user.profile] [URI: user/{nickname}/profile]

You have to pass the route parameters to the route method, for example:

<li><a href="{{ route('user.profile', $nickname) }}">Profile</a></li>
<li><a href="{{ route('user.settings', $nickname) }}">Settings</a></li>

It's because, both routes have a {nickname} in the route declaration. I've used $nickname for example but make sure you change the $nickname to appropriate value/variable, for example, it could be something like the following:

<li><a href="{{ route('user.settings', auth()->user()->nickname) }}">Settings</a></li>

Import mysql DB with XAMPP in command LINE

I think the OP's problem was not escaping the slashes. on windows a path like: "c:\user\folderss\myscript.sql" should in the command line be written like either:

 c:\\\user\\\folders\\\myscript.sql

or:

c:/user/folders/myscript.sql

therefore "\u" from "c:\user" was interpreted as a command.

see: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html for more info

What is difference between arm64 and armhf?

Update: Yes, I understand that this answer does not explain the difference between arm64 and armhf. There is a great answer that does explain that on this page. This answer was intended to help set the asker on the right path, as they clearly had a misunderstanding about the capabilities of the Raspberry Pi at the time of asking.

Where are you seeing that the architecture is armhf? On my Raspberry Pi 3, I get:

$ uname -a
armv7l

Anyway, armv7 indicates that the system architecture is 32-bit. The first ARM architecture offering 64-bit support is armv8. See this table for reference.

You are correct that the CPU in the Raspberry Pi 3 is 64-bit, but the Raspbian OS has not yet been updated for a 64-bit device. 32-bit software can run on a 64-bit system (but not vice versa). This is why you're not seeing the architecture reported as 64-bit.

You can follow the GitHub issue for 64-bit support here, if you're interested.

Screen width in React Native

April 10th 2020 Answer:

The suggested answer using Dimensions is now discouraged. See: https://reactnative.dev/docs/dimensions

The recommended approach is using the useWindowDimensions hook in React; https://reactnative.dev/docs/usewindowdimensions which uses a hook based API and will also update your value when the screen value changes (on screen rotation for example):

import {useWindowDimensions} from 'react-native';

const windowWidth = useWindowDimensions().width;
const windowHeight = useWindowDimensions().height;

Note: useWindowDimensions is only available from React Native 0.61.0: https://reactnative.dev/blog/2019/09/18/version-0.61

Best practices when running Node.js with port 80 (Ubuntu / Linode)

Give Safe User Permission To Use Port 80

Remember, we do NOT want to run your applications as the root user, but there is a hitch: your safe user does not have permission to use the default HTTP port (80). You goal is to be able to publish a website that visitors can use by navigating to an easy to use URL like http://ip:port/

Unfortunately, unless you sign on as root, you’ll normally have to use a URL like http://ip:port - where port number > 1024.

A lot of people get stuck here, but the solution is easy. There a few options but this is the one I like. Type the following commands:

sudo apt-get install libcap2-bin
sudo setcap cap_net_bind_service=+ep `readlink -f \`which node\``

Now, when you tell a Node application that you want it to run on port 80, it will not complain.

Check this reference link

Inserting multiple rows in a single SQL query?

If you are inserting into a single table, you can write your query like this (maybe only in MySQL):

INSERT INTO table1 (First, Last)
VALUES
    ('Fred', 'Smith'),
    ('John', 'Smith'),
    ('Michael', 'Smith'),
    ('Robert', 'Smith');

How to get table list in database, using MS SQL 2008?

This query will get you all the tables in the database

USE [DatabaseName];

SELECT * FROM information_schema.tables;

VBA Excel 2-Dimensional Arrays

You need ReDim:

m = 5
n = 8
Dim my_array()
ReDim my_array(1 To m, 1 To n)
For i = 1 To m
  For j = 1 To n
    my_array(i, j) = i * j
  Next
Next

For i = 1 To m
  For j = 1 To n
    Cells(i, j) = my_array(i, j)
  Next
Next

As others have pointed out, your actual problem would be better solved with ranges. You could try something like this:

Dim r1 As Range
Dim r2 As Range
Dim ws1 As Worksheet
Dim ws2 As Worksheet

Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
totalRow = ws1.Range("A1").End(xlDown).Row
totalCol = ws1.Range("A1").End(xlToRight).Column

Set r1 = ws1.Range(ws1.Cells(1, 1), ws1.Cells(totalRow, totalCol))
Set r2 = ws2.Range(ws2.Cells(1, 1), ws2.Cells(totalRow, totalCol))
r2.Value = r1.Value

JavaFX "Location is required." even though it is in the same package

I had sometimes the same Exception.

When i create a FXML-File with the Wizard in Eclipse, i write example.fxml in the name field. Eclipse creates a file, like example.fxml.fxml. With this mistake, the FXMLLoader can't find the right FXML-File. So, my tip, check the name of the FXML-Filename in your start-Method and the real Name of File.

Hopes i could help. Good luck.

How to get substring in C

If the task is only copying 4 characters, try for loops. If it's going to be more advanced and you're asking for a function, try strncpy. http://www.cplusplus.com/reference/clibrary/cstring/strncpy/

strncpy(sub1, baseString, 4);
strncpy(sub1, baseString+4, 4);
strncpy(sub1, baseString+8, 4);

or

for(int i=0; i<4; i++)
    sub1[i] = baseString[i];
sub1[4] = 0;
for(int i=0; i<4; i++)
    sub2[i] = baseString[i+4];
sub2[4] = 0;
for(int i=0; i<4; i++)
    sub3[i] = baseString[i+8];
sub3[4] = 0;

Prefer strncpy if possible.

How do you create a yes/no boolean field in SQL server?

In SQL Server Management Studio of Any Version, Use BIT as Data Type

which will provide you with True or False Value options. in case you want to use Only 1 or 0 then you can use this method:

CREATE TABLE SampleBit(
    bar int NOT NULL CONSTRAINT CK_foo_bar CHECK (bar IN (-1, 0, 1))
)

But I will strictly advise BIT as The BEST Option. Hope fully it's help someone.

Git: Installing Git in PATH with GitHub client for Windows

Thanks everyone who have answered.I have seen all answers and to try to make it easy for everyone

Step 1: Type edit environment and select the option shown

enter image description here

Step 2: Select Path and click on edit

enter image description here

Step 3: In the end add the below statement(you can avoid the first ; if its already there)

;C:\Program Files\Git\bin\git.exe;C:\Program Files\Git\cmd

enter image description here

Step 4:- Click on ok

enter image description here

Step 5 **:- One of the important step which is highlighted by one of the users. thanks to him. Please, **CLOSE command prompt and REOPEN then try to write git.

**

  • Close command prompt and restart before trying the below command

**

Here is the magic

enter image description here

How can I select records ONLY from yesterday?

If you want the timestamp for yesterday try something like:

(CURRENT_TIMESTAMP - INTERVAL '1' DAY)

Batch command date and time in file name

I realise this is a moot question to the OP, but I just brewed this, and I'm a tad proud of myself for thinking outside the box.

Download gawk for Windows at http://gnuwin32.sourceforge.net/packages/gawk.htm .... Then it's a one liner, without all that clunky DOS batch syntax, where it takes six FOR loops to split the strings (WTF? That's really really BAD MAD AND SAD! ... IMHO of course)

If you already know C, C++, Perl, or Ruby then picking-up AWK (which inherits from the former two, and contributes significantly to the latter two) is a piece of the proverbial CAKE!!!

The DOS Batch command:

echo %DATE% %TIME% && echo %DATE% %TIME% | gawk -F"[ /:.]" "{printf(""""%s%02d%02d-%02d%02d%02d\n"""", $4, $3, $2, $5, $6, $7);}"

Prints:

Tue 04/09/2012 10:40:38.25
20120904-104038

Now that's not quite the full story... I'm just going to be lazy and hard-code the rest of my log-file-name in the printf statement, because it's simple... But if anybody knows how to set a %NOW% variable to AWK's output (yeilding the guts of a "generic" now function) then I'm all ears.


EDIT:

A quick search on Stack Overflow filled in that last piece of the puzzle, Batch equivalent of Bash backticks.

So, these three lines of DOS batch:

echo %DATE% %TIME% | awk -F"[ /:.]" "{printf(""""%s%02d%02d-%02d%02d%02d\n"""", $4, $3, $2, $5, $6, $7);}" >%temp%\now.txt
set /p now=<%temp%\now.txt
echo %now%

Produce:

20120904-114434

So now I can include a datetime in the name of the log-file produced by my SQL Server installation (2005+) script thus:

sqlcmd -S .\SQLEXPRESS -d MyDb -e -i MyTSqlCommands.sql >MyTSqlCommands.sql.%now%.log

And I'm a happy camper again (except life was still SOOOOO much easier on Unix).

Defining an abstract class without any abstract methods

Yes you can. Sometimes you may get asked this question that what is the purpose doing this? The answer is: sometimes we have to restrict the class from instantiating by its own. In that case, we want user to extend our Abstract class and instantiate child class

How do I use brew installed Python as the default Python?

Use pyenv instead to install and switch between versions of Python. I've been using rbenv for years which does the same thing, but for Ruby. Before that it was hell managing versions.

Consult pyenv's github page for installation instructions. Basically it goes like this: - Install pyenv using homebrew. brew install pyenv - Add a function to the end of your shell startup script so pyenv can do it's magic. echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi' >> ~/.bash_profile

  • Use pyenv to install however many different versions of Python you need. pyenv install 3.7.7.
  • Set the default (global) version to a modern version you just installed. pyenv global 3.7.7.
  • If you work on a project that needs to use a different version of python, look into pyevn local. This creates a file in your project's folder that specifies the python version. Pyenv will look override the global python version with the version in that file.

Replacing values from a column using a condition in R

# reassign depth values under 10 to zero
df$depth[df$depth<10] <- 0

(For the columns that are factors, you can only assign values that are factor levels. If you wanted to assign a value that wasn't currently a factor level, you would need to create the additional level first:

levels(df$species) <- c(levels(df$species), "unknown") 
df$species[df$depth<10]  <- "unknown" 

Async/Await Class Constructor

You can definitely do this. Basically:

class AsyncConstructor {
    constructor() {
        return (async () => {

            // All async code here
            this.value = await asyncFunction();

            return this; // when done
        })();
    }
}

to create the class use:

let instance = await new AsyncConstructor();

This solution has a few short falls though:

super note: If you need to use super, you cannot call it within the async callback.

TypeScript note: this causes issues with TypeScript because the constructor returns type Promise<MyClass> instead of MyClass. There is no definitive way to resolve this that I know of. One potential way suggested by @blitter is to put /** @type {any} */ at the beginning of the constructor body— I do not know if this works in all situations however.

How do I tell a Python script to use a particular version

I would use the shebang #!/usr/bin/python (first line of code) with the serial number of Python at the end ;)

Then run the Python file as a script, e.g., ./main.py from the command line, rather than python main.py.

It is the same when you want to run Python from a Linux command line.

How to access child's state in React?

If you already have onChange handler for the individual FieldEditors I don't see why you couldn't just move the state up to the FormEditor component and just pass down a callback from there to the FieldEditors that will update the parent state. That seems like a more React-y way to do it, to me.

Something along the line of this perhaps:

const FieldEditor = ({ value, onChange, id }) => {
  const handleChange = event => {
    const text = event.target.value;
    onChange(id, text);
  };

  return (
    <div className="field-editor">
      <input onChange={handleChange} value={value} />
    </div>
  );
};

const FormEditor = props => {
  const [values, setValues] = useState({});
  const handleFieldChange = (fieldId, value) => {
    setValues({ ...values, [fieldId]: value });
  };

  const fields = props.fields.map(field => (
    <FieldEditor
      key={field}
      id={field}
      onChange={handleFieldChange}
      value={values[field]}
    />
  ));

  return (
    <div>
      {fields}
      <pre>{JSON.stringify(values, null, 2)}</pre>
    </div>
  );
};

// To add abillity to dynamically add/remove fields keep the list in state
const App = () => {
  const fields = ["field1", "field2", "anotherField"];

  return <FormEditor fields={fields} />;
};

Original - pre-hooks version:

_x000D_
_x000D_
class FieldEditor extends React.Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
    this.handleChange = this.handleChange.bind(this);_x000D_
  }_x000D_
_x000D_
  handleChange(event) {_x000D_
    const text = event.target.value;_x000D_
    this.props.onChange(this.props.id, text);_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <div className="field-editor">_x000D_
        <input onChange={this.handleChange} value={this.props.value} />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
class FormEditor extends React.Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
    this.state = {};_x000D_
_x000D_
    this.handleFieldChange = this.handleFieldChange.bind(this);_x000D_
  }_x000D_
_x000D_
  handleFieldChange(fieldId, value) {_x000D_
    this.setState({ [fieldId]: value });_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    const fields = this.props.fields.map(field => (_x000D_
      <FieldEditor_x000D_
        key={field}_x000D_
        id={field}_x000D_
        onChange={this.handleFieldChange}_x000D_
        value={this.state[field]}_x000D_
      />_x000D_
    ));_x000D_
_x000D_
    return (_x000D_
      <div>_x000D_
        {fields}_x000D_
        <div>{JSON.stringify(this.state)}</div>_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
// Convert to class component and add ability to dynamically add/remove fields by having it in state_x000D_
const App = () => {_x000D_
  const fields = ["field1", "field2", "anotherField"];_x000D_
_x000D_
  return <FormEditor fields={fields} />;_x000D_
};_x000D_
_x000D_
ReactDOM.render(<App />, document.body);
_x000D_
_x000D_
_x000D_

What are all possible pos tags of NLTK?

The reference is available at the official site

Copy and pasting from there:

  • CC | Coordinating conjunction |
  • CD | Cardinal number |
  • DT | Determiner |
  • EX | Existential there |
  • FW | Foreign word |
  • IN | Preposition or subordinating conjunction |
  • JJ | Adjective |
  • JJR | Adjective, comparative |
  • JJS | Adjective, superlative |
  • LS | List item marker |
  • MD | Modal |
  • NN | Noun, singular or mass |
  • NNS | Noun, plural |
  • NNP | Proper noun, singular |
  • NNPS | Proper noun, plural |
  • PDT | Predeterminer |
  • POS | Possessive ending |
  • PRP | Personal pronoun |
  • PRP$ | Possessive pronoun |
  • RB | Adverb |
  • RBR | Adverb, comparative |
  • RBS | Adverb, superlative |
  • RP | Particle |
  • SYM | Symbol |
  • TO | to |
  • UH | Interjection |
  • VB | Verb, base form |
  • VBD | Verb, past tense |
  • VBG | Verb, gerund or present participle |
  • VBN | Verb, past participle |
  • VBP | Verb, non-3rd person singular present |
  • VBZ | Verb, 3rd person singular present |
  • WDT | Wh-determiner |
  • WP | Wh-pronoun |
  • WP$ | Possessive wh-pronoun |
  • WRB | Wh-adverb |

CSS: how do I create a gap between rows in a table?

Add following rule to tr and it should work

float: left

Sample (Open it in IE9 offcourse :) ): http://jsfiddle.net/zshmN/

EDIT: This isn't a legal or correct solution as pointed out by many, but if you are left with no option and need something this will work in IE9.

So all those who are giving down votes, please let us know correct solution as well

Can we write our own iterator in Java?

Sure. An iterator is just an implementation of the java.util.Iterator interface. If you're using an existing iterable object (say, a LinkedList) from java.util, you'll need to either subclass it and override its iterator function so that you return your own, or provide a means of wrapping a standard iterator in your special Iterator instance (which has the advantage of being more broadly used), etc.

Access to the requested object is only available from the local network phpmyadmin

On Xampp 5.6.3 Windows Path C:\xampp\apache\conf\extra\httpd-xampp.conf comment in this: #Require local

New XAMPP security concept ... #Require local ...

Adding a UISegmentedControl to UITableView

   self.tableView.tableHeaderView = segmentedControl; 

If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.

enter image description here enter image description here

How to get the innerHTML of selectable jquery element?

Use .val() instead of .innerHTML for getting value of selected option

Use .text() for getting text of selected option

Thanks for correcting :)

background:none vs background:transparent what is the difference?

There is no difference between them.

If you don't specify a value for any of the half-dozen properties that background is a shorthand for, then it is set to its default value. none and transparent are the defaults.

One explicitly sets the background-image to none and implicitly sets the background-color to transparent. The other is the other way around.

installing apache: no VCRUNTIME140.dll

I had same problem, my issue was that downloaded Apache 2.4 but 32 bits. Then re-download 64bits version and it's works.

I hope it helps you

define a List like List<int,string>?

Use C# Dictionary datastructure it good for you...

Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("one", 1);
dict.Add("two", 2);

You can retrieve data from Ditionary in a simple way..

foreach (KeyValuePair<string, int> pair in dict)
{
    MessageBox.Show(pair.Key.ToString ()+ "  -  "  + pair.Value.ToString () );
}

For more example using C# Dictionary... C# Dictionary

Navi.

How to convert a Drawable to a Bitmap?

 // get image path from gallery
protected void onActivityResult(int requestCode, int resultcode, Intent intent) {
    super.onActivityResult(requestCode, resultcode, intent);

    if (requestCode == 1) {
        if (intent != null && resultcode == RESULT_OK) {             
            Uri selectedImage = intent.getData();

            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            filePath = cursor.getString(columnIndex);

            //display image using BitmapFactory

            cursor.close(); bmp = BitmapFactory.decodeFile(filepath); 
            iv.setBackgroundResource(0);
            iv.setImageBitmap(bmp);
        }
    }
}

How do I work with dynamic multi-dimensional arrays in C?

Here is working code that defines a subroutine make_3d_array to allocate a multidimensional 3D array with N1, N2 and N3 elements in each dimension, and then populates it with random numbers. You can use the notation A[i][j][k] to access its elements.

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


// Method to allocate a 2D array of floats
float*** make_3d_array(int nx, int ny, int nz) {
    float*** arr;
    int i,j;

    arr = (float ***) malloc(nx*sizeof(float**));

    for (i = 0; i < nx; i++) {
        arr[i] = (float **) malloc(ny*sizeof(float*));

        for(j = 0; j < ny; j++) {
            arr[i][j] = (float *) malloc(nz * sizeof(float));
        }
    }

    return arr;
} 



int main(int argc, char *argv[])
{
    int i, j, k;
    size_t N1=10,N2=20,N3=5;

    // allocates 3D array
    float ***ran = make_3d_array(N1, N2, N3);

    // initialize pseudo-random number generator
    srand(time(NULL)); 

    // populates the array with random numbers
    for (i = 0; i < N1; i++){
        for (j=0; j<N2; j++) {
            for (k=0; k<N3; k++) {
                ran[i][j][k] = ((float)rand()/(float)(RAND_MAX));
            }
        }
   }

    // prints values
    for (i=0; i<N1; i++) {
        for (j=0; j<N2; j++) {
            for (k=0; k<N3; k++) {
                printf("A[%d][%d][%d] = %f \n", i,j,k,ran[i][j][k]);
            }
        }
    }

    free(ran);
}

Clicking a button within a form causes page refresh

I use directive to prevent default behaviour:

module.directive('preventDefault', function() {
    return function(scope, element, attrs) {
        angular.element(element).bind('click', function(event) {
            event.preventDefault();
            event.stopPropagation();
        });
    }
});

And then, in html:

<button class="secondaryButton" prevent-default>Secondary action</button>

This directive can also be used with <a> and all other tags

receiver type *** for instance message is a forward declaration

That basically means that you need to import the .h file containing the declaration of States.

However, there is a lot of other stuff wrong with your code.

  • You're -init'ing an object without +alloc'ing it. That won't work
  • You're declaring an object as a non-pointer type, that won't work either
  • You're not calling [super init] in -init.
  • You've declared the class using @class in the header, but never imported the class.

DataGridView changing cell background color

If you are still intrested in why this didn't work for you at first:

The reason you don't see changes you've made to the cell's style is because you do these changes before the form was shown, and so they are disregarded.

Changing cell styles in the events suggested here will do the job, but they are called multiple times causing your style changes to happen more times than you wish, and so aren't very efficient.

To solve this, either change the style after the point in your code in which the form is shown, or subscribe to the Shown event, and place your changes there (this is event is called significantly less than the other events suggested).

Base64 Java encode and decode a string

For Spring Users , Spring Security has a Base64 class in the org.springframework.security.crypto.codec package that can also be used for encoding and decoding of Base64. Ex.

 public static String base64Encode(String token) {
    byte[] encodedBytes = Base64.encode(token.getBytes());
    return new String(encodedBytes, Charset.forName("UTF-8"));
}


public static String base64Decode(String token) {
    byte[] decodedBytes = Base64.decode(token.getBytes());
    return new String(decodedBytes, Charset.forName("UTF-8"));
}

Error in styles_base.xml file - android app - No resource found that matches the given name 'android:Widget.Material.ActionButton'

Go to your Android SDK installed directory then extras > android > support > v7 > appcompat.

in my case : D:\Software\adt-bundle-windows-x86-20140702\sdk\extras\android\support\v7\appcompat

once you are in appcompat folder ,check for project.properties file then change the value from default 19 to 21 as :

target=android-21.

Save the file and then refresh your project.

Then clean the project: In project tab , select clean option then select your project and clean...

This will resolve the error. If not, make sure your project also targets API 21 or higher (same steps as before, and easily forgotten when upgrading a project which targets an older version). Enjoy coding...

GIT clone repo across local file system in windows

You can specify the remote’s URL by applying the UNC path to the file protocol. This requires you to use four slashes:

git clone file:////<host>/<share>/<path>

For example, if your main machine has the IP 192.168.10.51 and the computer name main, and it has a share named code which itself is a git repository, then both of the following commands should work equally:

git clone file:////main/code
git clone file:////192.168.10.51/code

If the Git repository is in a subdirectory, simply append the path:

git clone file:////main/code/project-repository
git clone file:////192.168.10.51/code/project-repository

How to get the Android Emulator's IP address?

Within the code of my app I can get the running device IP andress easily like beolow:

WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());

How to loop through a JSON object with typescript (Angular2)

Assuming your json object from your GET request looks like the one you posted above simply do:

let list: string[] = [];

json.Results.forEach(element => {
    list.push(element.Id);
});

Or am I missing something that prevents you from doing it this way?

Root element is missing

Make sure you XML looks like this:

<?xml version="1.0" encoding="utf-8"?>
<rootElement>
...
</rootElement>

Also, a blank XML file will return the same Root elements is missing exception. Each XML file must have a root element / node which encloses all the other elements.

Angular : Manual redirect to route

Angular Redirection manually: Import @angular/router, Inject in constructor() then call this.router.navigate().

import {Router} from '@angular/router';
... 
...

constructor(private router: Router) {
  ...
}

onSubmit() {
  ...
  this.router.navigate(['/profile']); 
}

Return char[]/string from a function

you can use a static array in your method, to avoid lose of your array when your function ends :

char * createStr() 
{
    char char1= 'm';
    char char2= 'y';

    static char str[3];  
    str[0] = char1;
    str[1] = char2;
    str[2] = '\0';

    return str;
}

Edit : As Toby Speight mentioned this approach is not thread safe, and also recalling the function leads to data overwrite that is unwanted in some applications. So you have to save the data in a buffer as soon as you return back from the function. (However because it is not thread safe method, concurrent calls could still make problem in some cases, and to prevent this you have to use lock. capture it when entering the function and release it after copy is done, i prefer not to use this approach because its messy and error prone.)

Selecting option by text content with jQuery

I know this question is too old, but still, I think this approach would be cleaner:

cat = $.URLDecode(cat);
$('#cbCategory option:contains("' + cat + '")').prop('selected', true);

In this case you wont need to go over the entire options with each(). Although by that time prop() didn't exist so for older versions of jQuery use attr().


UPDATE

You have to be certain when using contains because you can find multiple options, in case of the string inside cat matches a substring of a different option than the one you intend to match.

Then you should use:

cat = $.URLDecode(cat);
$('#cbCategory option')
    .filter(function(index) { return $(this).text() === cat; })
    .prop('selected', true);

Batch files : How to leave the console window open

You can just put a pause command in the last line of your batch file:

@echo off
echo Hey, I'm just doing some work for you.
pause

Will give you something like this as output:

Hey, I'm just doing some work for you.

Press any key to continue ...

Note: Using the @echo prevents to output the command before the output is printed.

JavaScript, getting value of a td with id name

If by 'td value' you mean text inside of td, then:

document.getElementById('td-id').innerHTML

org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]A child container failed during start

In my case, the servlet-api.jar file in jre/lib/ext in the jdk directory conflicts with the servlet-api.jar file in tomcat, removing the servlet-api.jar in jre/lib/ext in the jdk directory can solve the problem.

Python in Xcode 4+?

You should try PyDev plug in for Eclipse. I tried alot of editors/IDE's to use with python, but the only one i liked the most is the PyDev plugin for Eclipse. It has code completion, debugger and many other nice features. Plus both are free.

Regex to check with starts with http://, https:// or ftp://

I think the regex / string parsing solutions are great, but for this particular context, it seems like it would make sense just to use java's url parser:

https://docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html

Taken from that page:

import java.net.*;
import java.io.*;

public class ParseURL {
    public static void main(String[] args) throws Exception {

        URL aURL = new URL("http://example.com:80/docs/books/tutorial"
                           + "/index.html?name=networking#DOWNLOADING");

        System.out.println("protocol = " + aURL.getProtocol());
        System.out.println("authority = " + aURL.getAuthority());
        System.out.println("host = " + aURL.getHost());
        System.out.println("port = " + aURL.getPort());
        System.out.println("path = " + aURL.getPath());
        System.out.println("query = " + aURL.getQuery());
        System.out.println("filename = " + aURL.getFile());
        System.out.println("ref = " + aURL.getRef());
    }
}

yields the following:

protocol = http
authority = example.com:80
host = example.com
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?name=networking
ref = DOWNLOADING

embedding image in html email

One additional hint to Pavel Perna's post which helped me very much (cannot comment with my reputation, that's why I post this as answer): In some versions of Microsoft Exchange, the inline contents disposition is removed (see this post by Microsoft). The image is simply not part in the mail the user sees in Outlook. As a workaround, use "Content-Disposition: attachement" instead. Outlook 2016 won't show images as attachement that are used in the mail message, although they use the "Content-Disposition: attachement".

Visual Studio Code Search and Replace with Regular Expressions

Make sure Match Case is selected with Use Regular Expression so this matches. [A-Z]* If match case is not selected, this matches all letters.

Matplotlib subplots_adjust hspace so titles and xlabels don't overlap?

The link posted by Jose has been updated and pylab now has a tight_layout() function that does this automatically (in matplotlib version 1.1.0).

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.tight_layout

http://matplotlib.org/users/tight_layout_guide.html#plotting-guide-tight-layout

Docker container not starting (docker start)

You are trying to run bash, an interactive shell that requires a tty in order to operate. It doesn't really make sense to run this in "detached" mode with -d, but you can do this by adding -it to the command line, which ensures that the container has a valid tty associated with it and that stdin remains connected:

docker run -it -d -p 52022:22 basickarl/docker-git-test

You would more commonly run some sort of long-lived non-interactive process (like sshd, or a web server, or a database server, or a process manager like systemd or supervisor) when starting detached containers.

If you are trying to run a service like sshd, you cannot simply run service ssh start. This will -- depending on the distribution you're running inside your container -- do one of two things:

  • It will try to contact a process manager like systemd or upstart to start the service. Because there is no service manager running, this will fail.

  • It will actually start sshd, but it will be started in the background. This means that (a) the service sshd start command exits, which means that (b) Docker considers your container to have failed, so it cleans everything up.

If you want to run just ssh in a container, consider an example like this.

If you want to run sshd and other processes inside the container, you will need to investigate some sort of process supervisor.

Comments in Markdown

The following works very well

<empty line>
[whatever comment text]::

that method takes advantage of syntax to create links via reference
since link reference created with [1]: http://example.org will not be rendered, likewise any of the following will not be rendered as well

<empty line>
[whatever]::
[whatever]:whatever
[whatever]: :
[whatever]: whatever

How do you fadeIn and animate at the same time?

Another way to do simultaneous animations if you want to call them separately (eg. from different code) is to use queue. Again, as with Tinister's answer you would have to use animate for this and not fadeIn:

$('.tooltip').css('opacity', 0);
$('.tooltip').show();
...

$('.tooltip').animate({opacity: 1}, {queue: false, duration: 'slow'});
$('.tooltip').animate({ top: "-10px" }, 'slow');

How to get HttpClient to pass credentials along with the request?

OK, so thanks to all of the contributors above. I am using .NET 4.6 and we also had the same issue. I spent time debugging System.Net.Http, specifically the HttpClientHandler, and found the following:

    if (ExecutionContext.IsFlowSuppressed())
    {
      IWebProxy webProxy = (IWebProxy) null;
      if (this.useProxy)
        webProxy = this.proxy ?? WebRequest.DefaultWebProxy;
      if (this.UseDefaultCredentials || this.Credentials != null || webProxy != null && webProxy.Credentials != null)
        this.SafeCaptureIdenity(state);
    }

So after assessing that the ExecutionContext.IsFlowSuppressed() might have been the culprit, I wrapped our Impersonation code as follows:

using (((WindowsIdentity)ExecutionContext.Current.Identity).Impersonate())
using (System.Threading.ExecutionContext.SuppressFlow())
{
    // HttpClient code goes here!
}

The code inside of SafeCaptureIdenity (not my spelling mistake), grabs WindowsIdentity.Current() which is our impersonated identity. This is being picked up because we are now suppressing flow. Because of the using/dispose this is reset after invocation.

It now seems to work for us, phew!

how to convert string to numerical values in mongodb

Three things need to care for:

  1. parseInt() will store double data type in mongodb. Please use new NumberInt(string).
  2. in Mongo shell command for bulk usage, yield won't work. Please DO NOT add 'yield'.
  3. If you already change string to double by parseInt(). It looks like you have no way to change the type to int directly. The solution is a little bit wired: change double to string first and then change back to int by new NumberInt().

Java: Retrieving an element from a HashSet

First of all convert your set to Array. Then, get item by index of array .

Set uniqueItem = new HashSet() ;
uniqueItem.add("0");
uniqueItem.add("1");
uniqueItem.add("0");

Object[] arrayItem = uniqueItem.toArray(); 
for(int i = 0; i < uniqueItem.size();i++){
    System.out.println("Item "+i+" "+arrayItem[i].toString());
}

SQL Order By Count

Try :

SELECT count(*),group FROM table GROUP BY group ORDER BY group

to order by count descending do

SELECT count(*),group FROM table GROUP BY group ORDER BY count(*) DESC

This will group the results by the group column returning the group and the count and will return the order in group order

delete all record from table in mysql

truncate tableName

That is what you are looking for.

Truncate will delete all records in the table, emptying it.

Specified cast is not valid?

Try this:

public void LoadData()
        {
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Stocks;Integrated Security=True;Pooling=False");
            SqlDataAdapter sda = new SqlDataAdapter("Select * From [Stocks].[dbo].[product]", con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            DataGridView1.Rows.Clear();

        foreach (DataRow item in dt.Rows)
        {
            int n = DataGridView1.Rows.Add();
            DataGridView1.Rows[n].Cells[0].Value = item["ProductCode"].ToString();
            DataGridView1.Rows[n].Cells[1].Value = item["Productname"].ToString();
            DataGridView1.Rows[n].Cells[2].Value = item["qty"].ToString();                
            if ((bool)item["productstatus"])
            {
                DataGridView1.Rows[n].Cells[3].Value = "Active";
            }
            else
            {
                DataGridView1.Rows[n].Cells[3].Value = "Deactive";
            }

Angular - Can't make ng-repeat orderBy work

The orderBy only works with Arrays -- See http://docs.angularjs.org/api/ng.filter:orderBy

Also a great filter to use for Objects instead of Arrays @ Angularjs OrderBy on ng-repeat doesn't work

How to give a pattern for new line in grep?

just found

grep $'\r'

It's using $'\r' for c-style escape in Bash.

in this article

VBA Count cells in column containing specified value

This isn't exactly what you are looking for but here is how I've approached this problem in the past;

You can enter a formula like;

=COUNTIF(A1:A10,"Green")

...into a cell. This will count the Number of cells between A1 and A10 that contain the text "Green". You can then select this cell value in a VBA Macro and assign it to a variable as normal.

How does C#'s random number generator work?

I was just wondering how the random number generator in C# works.

That's implementation-specific, but the wikipedia entry for pseudo-random number generators should give you some ideas.

I was also curious how I could make a program that generates random WHOLE INTEGER numbers from 1-100.

You can use Random.Next(int, int):

Random rng = new Random();
for (int i = 0; i < 10; i++)
{
    Console.WriteLine(rng.Next(1, 101));
}

Note that the upper bound is exclusive - which is why I've used 101 here.

You should also be aware of some of the "gotchas" associated with Random - in particular, you should not create a new instance every time you want to generate a random number, as otherwise if you generate lots of random numbers in a short space of time, you'll see a lot of repeats. See my article on this topic for more details.

How to test the `Mosquitto` server?

To test and see if you can access your MQTT server from outside world (outside of your VM or local machine), you can install one of the MQTT publishing and monitoring tools such as MQTT-Spy on your outside-world machine and then subscribe for '#" (meaning all the topics).

You can follow this by the method @hardillb mentioned in his answer above and test back and forth such as this:

On the machine with Mosquitto Server running, enter image description here

On the outside-word machine with mqtt-spy running, enter image description here

I have mainly mentioned mqtt-spy since it's multi-platform and easy to use. You can go with any other tool really. And also to my knowledge to run the mosquitto_sub and mosquitto_pub you need to have mosquitto-clients installed on your Linux machine running the test (in my case Ubuntu) which can be done easily by,

sudo apt-get install mosquitto-clients

How to get the focused element with jQuery?

If you want to confirm if focus is with an element then

if ($('#inputId').is(':focus')) {
    //your code
}

How to exit an Android app programmatically?

If someone still wonders, for Xamarin.Android (in my case also Monogame running on it) the command FinishAndRemoveTask() on Activity does the job very well!

WPF Databinding: How do I access the "parent" data context?

This also works in Silverlight 5 (perhaps earlier as well but i haven't tested it). I used the relative source like this and it worked fine.

RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=telerik:RadGridView}"

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

First you must test the query list size; here a example:

long count;
if (query.list().size() > 0)
    count=(long) criteria.list().get(0);   
else
    count=0;            
return count;

How do I properly set the permgen size?

So you are doing the right thing concerning "-XX:MaxPermSize=512m": it is indeed the correct syntax. You could try to set these options directly to the Catalyna server files so they are used on server start.

Maybe this post will help you!

How to make sure that Tomcat6 reads CATALINA_OPTS on Windows?

Google Maps Android API v2 - Interactive InfoWindow (like in original android google maps)

It is really simple.

googleMap.setInfoWindowAdapter(new InfoWindowAdapter() {

            // Use default InfoWindow frame
            @Override
            public View getInfoWindow(Marker marker) {              
                return null;
            }           

            // Defines the contents of the InfoWindow
            @Override
            public View getInfoContents(Marker marker) {

                // Getting view from the layout file info_window_layout
                View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);

                // Getting reference to the TextView to set title
                TextView note = (TextView) v.findViewById(R.id.note);

                note.setText(marker.getTitle() );

                // Returning the view containing InfoWindow contents
                return v;

            }

        });

Just add above code in your class where you are using GoogleMap. R.layout.info_window_layout is our custom layout that is showing the view that will come in place of infowindow. I just added the textview here. You can add additonal view here to make it like the sample snap. My info_window_layout was

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:orientation="vertical" 
    >

        <TextView 
        android:id="@+id/note"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

I hope it will help. We can find a working example of custom infowindow at http://wptrafficanalyzer.in/blog/customizing-infowindow-contents-in-google-map-android-api-v2-using-infowindowadapter/#comment-39731

EDITED : This code is shows how we can add custom view on infoWindow. This code did not handle the clicks on Custom View items. So it is close to answer but not exactly the answer that's why It is not accepted as answer.

How to increase IDE memory limit in IntelliJ IDEA on Mac?

OSX 10.9, if you dont bother about signed application you might just change

/Applications/IntelliJ\ IDEA\ 12\ CE.app/bin/idea.vmoptions

JSON to pandas DataFrame

Just a new version of the accepted answer, as python3.x does not support urllib2

from requests import request
import json
from pandas.io.json import json_normalize

path1 = '42.974049,-81.205203|42.974298,-81.195755'
response=request(url='http://maps.googleapis.com/maps/api/elevation/json?locations='+path1+'&sensor=false', method='get')
elevations = response.json()
elevations
data = json.loads(elevations)
json_normalize(data['results'])

How to determine if a number is positive or negative?

You say

we should not use conditional operators

But this is a trick requirement, because == is also a conditional operator. There is also one built into ? :, while, and for loops. So nearly everyone has failed to provide an answer meeting all the requirements.

The only way to build a solution without a conditional operator is to use lookup table vs one of a few other people's solutions that can be boiled down to 0/1 or a character, before a conditional is met.

Here are the answers that I think might work vs a lookup table:

  • Nabb
  • Steven Schlansker
  • Dennis Cheung
  • Gary Rowe

UILabel Align Text to center

Here is a sample code showing how to align text using UILabel:

label = [[UILabel alloc] initWithFrame:CGRectMake(60, 30, 200, 12)];
label.textAlignment = NSTextAlignmentCenter;

You can read more about it here UILabel

Bootstrap - Removing padding or margin when screen size is smaller

The way I get an element to go 100% width of the device is use negative left and right margins on it. The body has a padding of 24px, so that's what you can use negative margins for:

element{
    margin-left:  -24px;
    margin-right: -24px;
    padding-left:  24px;
    padding-right:  24px;
}

How to convert any Object to String?

If the class does not have toString() method, then you can use ToStringBuilder class from org.apache.commons:commons-lang3

pom.xml:

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.10</version>
</dependency>

code:

ToStringBuilder.reflectionToString(yourObject)

Array of strings in groovy

If you really want to create an array rather than a list use either

String[] names = ["lucas", "Fred", "Mary"]

or

def names = ["lucas", "Fred", "Mary"].toArray()

Deploying Java webapp to Tomcat 8 running in Docker container

Tomcat will only extract the war which is copied to webapps directory. Change Dockerfile as below:

FROM tomcat:8.0.20-jre8
COPY /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war /usr/local/tomcat/webapps/myapp.war

You might need to access the url as below unless you have specified the webroot

http://192.168.59.103:8888/myapp/getData

How to open local file on Jupyter?

Install jupyter. Open terminal. Go to folder where you file is (in terminal ie.cd path/to/folder). Run jupyter notebook. And voila: you have something like this:

enter image description here

Notice that to open a notebook in the folder, you can either click on it in the browser or go to address:

http://localhost:8888/notebooks/name_of_your_file.ipynb

Replace non-numeric with empty string

Using the Regex methods in .NET you should be able to match any non-numeric digit using \D, like so:

phoneNumber  = Regex.Replace(phoneNumber, "\\D", String.Empty);

Is there a function in python to split a word into a list?

The easiest way is probably just to use list(), but there is at least one other option as well:

s = "Word to Split"
wordlist = list(s)               # option 1, 
wordlist = [ch for ch in s]      # option 2, list comprehension.

They should both give you what you need:

['W','o','r','d',' ','t','o',' ','S','p','l','i','t']

As stated, the first is likely the most preferable for your example but there are use cases that may make the latter quite handy for more complex stuff, such as if you want to apply some arbitrary function to the items, such as with:

[doSomethingWith(ch) for ch in s]

How to use lodash to find and return an object from Array?

The argument passed to the callback is one of the elements of the array. The elements of your array are objects of the form {description: ..., id: ...}.

var delete_id = _.result(_.find(savedViews, function(obj) {
    return obj.description === view;
}), 'id');

Yet another alternative from the docs you linked to (lodash v3):

_.find(savedViews, 'description', view);

Lodash v4:

_.find(savedViews, ['description', view]);

Convert comma separated string to array in PL/SQL

Another possibility is:

create or replace FUNCTION getNth (
  input varchar2,
  nth number
) RETURN varchar2 AS
  nthVal varchar2(80);
BEGIN
  with candidates (s,e,n) as (
      select 1, instr(input,',',1), 1 from dual
      union all
      select e+1, instr(input,',',e+1), n+1
        from candidates where e > 0)
  select substr(input,s,case when e > 0 then e-s else length(input) end) 
    into nthVal
    from candidates where n=nth;
  return nthVal;
END getNth;

It's a little too expensive to run, as it computes the complete split every time the caller asks for one of the items in there...

Getting the WordPress Post ID of current post

you can use $post->ID for current id.

How to find out if an item is present in a std::vector?

Here's a function that will work for any Container:

template <class Container> 
const bool contains(const Container& container, const typename Container::value_type& element) 
{
    return std::find(container.begin(), container.end(), element) != container.end();
}

Note that you can get away with 1 template parameter because you can extract the value_type from the Container. You need the typename because Container::value_type is a dependent name.

How to save RecyclerView's scroll position using RecyclerView.State?

You can either use adapter.stateRestorationPolicy = StateRestorationPolicy.PREVENT_WHEN_EMPTY which is introduced in recyclerview:1.2.0-alpha02

https://medium.com/androiddevelopers/restore-recyclerview-scroll-position-a8fbdc9a9334

but it has some issues such as not working with inner RecyclerView, and some other issues you can check out in medium post's comment section.

Or you can use ViewModel with SavedStateHandle which works for inner RecyclerViews, screen rotation and process death.

Create a ViewModel with saveStateHandle

val scrollState=
    savedStateHandle.getLiveData<Parcelable?>(KEY_LAYOUT_MANAGER_STATE)

use Parcelable scrollState to save and restore state as answered in other posts or by adding a scroll listener to RecyclerView and

recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {

        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            super.onScrollStateChanged(recyclerView, newState)
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
               scrollState.value = mLayoutManager.onSaveInstanceState()
            }
        }

HttpUtility does not exist in the current context

Adding a reference to Sysem.Web.Dll did it for me.

How to change visibility of layout programmatically

TextView view = (TextView) findViewById(R.id.textView);
view.setText("Add your text here");
view.setVisibility(View.VISIBLE);

How to send list of file in a folder to a txt file in Linux

If only names of regular files immediately contained within a directory (assume it's ~/dirs) are needed, you can do

find ~/docs -type f -maxdepth 1 > filenames.txt

How to convert JTextField to String and String to JTextField?

how to convert JTextField to string and string to JTextField in java

If you mean how to get and set String from jTextField then you can use following methods:

String str = jTextField.getText() // get string from jtextfield

and

jTextField.setText(str)  // set string to jtextfield
//or
new JTextField(str)     // set string to jtextfield

You should check JavaDoc for JTextField

How to remove commits from a pull request

People wouldn't like to see a wrong commit and a revert commit to undo changes of the wrong commit. This pollutes commit history.

Here is a simple way for removing the wrong commit instead of undoing changes with a revert commit.

  1. git checkout my-pull-request-branch

  2. git rebase -i HEAD~n // where n is the number of last commits you want to include in interactive rebase.

  3. Replace pick with drop for commits you want to discard.
  4. Save and exit.
  5. git push --force

how to stop a for loop

Try to simply use break statement.

Also you can use the following code as an example:

a = [[0,1,0], [1,0,0], [1,1,1]]
b = [[0,0,0], [0,0,0], [0,0,0]]

def check_matr(matr, expVal):    
    for row in matr:
        if len(set(row)) > 1 or set(row).pop() != expVal:
            print 'Wrong'
            break# or return
        else:
            print 'ok'
    else:
        print 'empty'
check_matr(a, 0)
check_matr(b, 0)

How to make an AlertDialog in Flutter?

Another easy option to show Dialog is to use stacked_services package

 _dialogService.showDialog(
      title: "Title",
      description: "Dialog message Tex",
         );
     });

Generating CSV file for Excel, how to have a newline inside a value

The way we do it (we use VB.Net) is to enclose the text with new lines in Chr(34) which is the char representing the double quotes and replace all CR-LF characters for LF.

How do I fix the indentation of selected lines in Visual Studio

Selecting the text to fix, and CtrlK, CtrlF shortcut certainly works. However, I generally find that if a particular method (for instance) has it's indentation messed up, simply removing the closing brace of the method, and re-adding, in fact fixes the indentation anyway, thereby doing without the need to select the code before hand, ergo is quicker. ymmv.

How can I add a space in between two outputs?

Like this?

 System.out.println(Name + " " + Income);

HTML5 Pre-resize images before uploading

Yes, use the File API, then you can process the images with the canvas element.

This Mozilla Hacks blog post walks you through most of the process. For reference here's the assembled source code from the blog post:

// from an input element
var filesToUpload = input.files;
var file = filesToUpload[0];

var img = document.createElement("img");
var reader = new FileReader();  
reader.onload = function(e) {img.src = e.target.result}
reader.readAsDataURL(file);

var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);

var MAX_WIDTH = 800;
var MAX_HEIGHT = 600;
var width = img.width;
var height = img.height;

if (width > height) {
  if (width > MAX_WIDTH) {
    height *= MAX_WIDTH / width;
    width = MAX_WIDTH;
  }
} else {
  if (height > MAX_HEIGHT) {
    width *= MAX_HEIGHT / height;
    height = MAX_HEIGHT;
  }
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);

var dataurl = canvas.toDataURL("image/png");

//Post dataurl to the server with AJAX

What are the differences between json and simplejson Python modules?

Some values are serialized differently between simplejson and json.

Notably, instances of collections.namedtuple are serialized as arrays by json but as objects by simplejson. You can override this behaviour by passing namedtuple_as_object=False to simplejson.dump, but by default the behaviours do not match.

>>> import collections, simplejson, json
>>> TupleClass = collections.namedtuple("TupleClass", ("a", "b"))
>>> value = TupleClass(1, 2)
>>> json.dumps(value)
'[1, 2]'
>>> simplejson.dumps(value)
'{"a": 1, "b": 2}'
>>> simplejson.dumps(value, namedtuple_as_object=False)
'[1, 2]'

Can one class extend two classes?

No you cannot make a class extend to two classes.

A possible solution is to make it extend from another class, and make that class extend from another again.

Plotting dates on the x-axis with Python's matplotlib

You can do this more simply using plot() instead of plot_date().

First, convert your strings to instances of Python datetime.date:

import datetime as dt

dates = ['01/02/1991','01/03/1991','01/04/1991']
x = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates]
y = range(len(x)) # many thanks to Kyss Tao for setting me straight here

Then plot:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.plot(x,y)
plt.gcf().autofmt_xdate()

Result:

enter image description here

Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)

Seeing how you draw your canvas with

$("canvas").drawImage();

it seems that you use jQuery Canvas (jCanvas) by Caleb Evans. I actually use that plugin and it has a simple way to retrieve canvas base64 image string with $('canvas').getCanvasImage();

Here's a working Fiddle for you: http://jsfiddle.net/e6nqzxpn/

Exception 'open failed: EACCES (Permission denied)' on Android

I had the same problem (API >= 23).

The solution https://stackoverflow.com/a/13569364/1729501 worked for me, but it was not practical to disconnect app for debugging.

my solution was to install proper adb device driver on Windows. The google USB driver did not work for my device.

STEP 1: Download adb drivers for your device brand.

STEP 2: Go to device manager -> other devices -> look for entries with word "adb" -> select Update driver -> give location in step 1

vbscript output to console

You only need to force cscript instead wscript. I always use this template. The function ForceConsole() will execute your vbs into cscript, also you have nice alias to print and scan text.

 Set oWSH = CreateObject("WScript.Shell")
 vbsInterpreter = "cscript.exe"

 Call ForceConsole()

 Function printf(txt)
    WScript.StdOut.WriteLine txt
 End Function

 Function printl(txt)
    WScript.StdOut.Write txt
 End Function

 Function scanf()
    scanf = LCase(WScript.StdIn.ReadLine)
 End Function

 Function wait(n)
    WScript.Sleep Int(n * 1000)
 End Function

 Function ForceConsole()
    If InStr(LCase(WScript.FullName), vbsInterpreter) = 0 Then
        oWSH.Run vbsInterpreter & " //NoLogo " & Chr(34) & WScript.ScriptFullName & Chr(34)
        WScript.Quit
    End If
 End Function

 Function cls()
    For i = 1 To 50
        printf ""
    Next
 End Function

 printf " _____ _ _           _____         _    _____         _     _   "
 printf "|  _  |_| |_ ___ ___|     |_ _ _ _| |  |   __|___ ___|_|___| |_ "
 printf "|     | | '_| . |   |   --| | | | . |  |__   |  _|  _| | . |  _|"
 printf "|__|__|_|_,_|___|_|_|_____|_____|___|  |_____|___|_| |_|  _|_|  "
 printf "                                                       |_|     v1.0"
 printl " Enter your name:"
 MyVar = scanf
 cls
 printf "Your name is: " & MyVar
 wait(5)

Conversion hex string into ascii in bash command line

Make a script like this:

#!/bin/bash

echo $((0x$1)).$((0x$2)).$((0x$3)).$((0x$4))

Example:

sh converthextoip.sh c0 a8 00 0b

Result:

192.168.0.11

What jsf component can render a div tag?

You can create a DIV component using the <h:panelGroup/>. By default, the <h:panelGroup/> will generate a SPAN in the HTML code.

However, if you specify layout="block", then the component will be a DIV in the generated HTML code.

<h:panelGroup layout="block"/>

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

Got this problem, and fixed it by setting the "launch mode" property of the activity.

Error launching Eclipse 4.4 "Version 1.6.0_65 of the JVM is not suitable for this product."

Your -vm argument seems ok BUT it's position is wrong. According to this Eclipse Wiki entry :

The -vm option must occur before the -vmargs option, since everything after -vmargs is passed directly to the JVM.

So your -vm argument is not taken into account and it fails over to your default java installation, which is probably 1.6.0_65.

Sort a list of lists with a custom compare function

>>> l = [list(range(i, i+4)) for i in range(10,1,-1)]
>>> l
[[10, 11, 12, 13], [9, 10, 11, 12], [8, 9, 10, 11], [7, 8, 9, 10], [6, 7, 8, 9], [5, 6, 7, 8], [4, 5, 6, 7], [3, 4, 5, 6], [2, 3, 4, 5]]
>>> sorted(l, key=sum)
[[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9, 10], [8, 9, 10, 11], [9, 10, 11, 12], [10, 11, 12, 13]]

The above works. Are you doing something different?

Notice that your key function is just sum; there's no need to write it explicitly.

How to remove Left property when position: absolute?

In the future one would use left: unset; for unsetting the value of left.

As of today 4 nov 2014 unset is only supported in Firefox.

Read more about unset in MDN.

My guess is we'll be able to use it around year 2022 when IE 11 is properly phased out.

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

The brute force method of generating every single possible board and scoring it based on the boards it later produces further down the tree doesn't require much memory, especially once you recognize that 90 degree board rotations are redundant, as are flips about the vertical, horizontal, and diagonal axis.

Once you get to that point, there's something like less than 1k of data in a tree graph to describe the outcome, and thus the best move for the computer.

-Adam

Convert string into integer in bash script - "Leading Zero" number error

You could also use bc

hour=8
result=$(echo "$hour + 1" | bc)
echo $result
9

ASP.Net MVC: Calling a method from a view

why You don't use Ajax to

its simple and does not require page refresh and has success and error callbacks

take look at my samlpe

<a id="ResendVerificationCode" >@Resource_en.ResendVerificationCode</a>

and in JQuery

 $("#ResendVerificationCode").on("click", function() {
                getUserbyPhoneIfNotRegisterd($("#phone").val());
 });

and this is my ajax which call my controller and my controller and return object from database

function getUserbyPhoneIfNotRegisterd(userphone) {

              $.ajax({
                    type: "GET",
                    dataType: "Json",
                    url: '@Url.Action("GetUserByPhone", "User")' + '?phone=' + userphone,
                    async: false,
                    success: function(data) {
                        if (data == null || data.data == null) {
                            ErrorMessage("", "@Resource_en.YourPhoneDoesNotExistInOurDatabase");
                        } else {
                            user = data[Object.keys(data)[0]];
                                AddVereCode(user.ID);// anather Ajax call 
                                SuccessMessage("Done", "@Resource_en.VerificationCodeSentSuccessfully", "Done");
                        }
                    },
                    error: function() {
                        ErrorMessage("", '@Resource_en.ErrorOccourd');
                    }
                });
            }

Reactjs - Form input validation

We have plenty of options to validate the react js forms. Maybe the npm packages have some own limitations. Based up on your needs you can choose the right validator packages. I would like to recommend some, those are listed below.

If anybody knows a better solution than this, please put it on the comment section for other people references.

Is it possible to style html5 audio tag?

The appearance of the tag is browser-dependent, but you can hide it, build your own interface and control the playback using Javascript.

Difference between TCP and UDP?

TCP is a connection oriented stream over an IP network. It guarantees that all sent packets will reach the destination in the correct order. This imply the use of acknowledgement packets sent back to the sender, and automatic retransmission, causing additional delays and a general less efficient transmission than UDP.

UDP is a connection-less protocol. Communication is datagram oriented. The integrity is guaranteed only on the single datagram. Datagrams reach destination and can arrive out of order or don't arrive at all. It is more efficient than TCP because it uses non ACK. It's generally used for real time communication, where a little percentage of packet loss rate is preferable to the overhead of a TCP connection.

In certain situations UDP is used because it allows broadcast packet transmission. This is sometimes fundamental in cases like DHCP protocol, because the client machine hasn't still received an IP address (this is the DHCP negotiaton protocol purpose) and there won't be any way to establish a TCP stream without the IP address itself.

How to reference image resources in XAML?

If the image is in your resources folder and its build action is set to Resource. You can reference the image in XAML as follows:

"pack://application:,,,/Resources/Search.png"

Assuming you do not have any folder structure under the Resources folder and it is an application. For example I use:

ImageSource="pack://application:,,,/Resources/RibbonImages/CloseButton.png"

when I have a folder named RibbonImages under Resources folder.

Default settings Raspberry Pi /etc/network/interfaces

These are the default settings I have for /etc/network/interfaces (including WiFi settings) for my Raspberry Pi 1:

auto lo

iface lo inet loopback
iface eth0 inet dhcp

allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp