Programs & Examples On #My.cnf

Configuration file for MySQL programs, particularly for the mysqld server.

MySQL my.cnf performance tuning recommendations

Try starting with the Percona wizard and comparing their recommendations against your current settings one by one. Don't worry there aren't as many applicable settings as you might think.

https://tools.percona.com/wizard

Update circa 2020: Sorry, this tool reached it's end of life: https://www.percona.com/blog/2019/04/22/end-of-life-query-analyzer-and-mysql-configuration-generator/

Everyone points to key_buffer_size first which you have addressed. With 96GB memory I'd be wary of any tiny default value (likely to be only 96M!).

MySQL my.cnf file - Found option without preceding group

Charset encoding

Check the charset encoding of the file. Make sure that it is in ASCII.

Use the od command to see if there is a UTF-8 BOM at the beginning, for example.

Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root

Very weird, but I got this error when I made a typo in the my.cnf file.
So it had nothing to do with the user directive not defined or not running as root-user.

My mistake was:

bind=192.168.1.2

instead of

bind-address=192.168.1.2

How to check if string input is a number?

Here is the simplest solution:

a= input("Choose the option\n")

if(int(a)):
    print (a);
else:
    print("Try Again")

List of enum values in java

It is possible but you should use EnumSet instead

enum MyEnum {
    ONE, TWO;
    public static final EnumSet<MyEnum> all = EnumSet.of(ONE, TWO);
}

Disable password authentication for SSH

I followed these steps (for Mac).

In /etc/ssh/sshd_config change

#ChallengeResponseAuthentication yes
#PasswordAuthentication yes

to

ChallengeResponseAuthentication no
PasswordAuthentication no

Now generate the RSA key:

ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa

(For me an RSA key worked. A DSA key did not work.)

A private key will be generated in ~/.ssh/id_rsa along with ~/.ssh/id_rsa.pub (public key).

Now move to the .ssh folder: cd ~/.ssh

Enter rm -rf authorized_keys (sometimes multiple keys lead to an error).

Enter vi authorized_keys

Enter :wq to save this empty file

Enter cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys

Restart the SSH:

sudo launchctl stop com.openssh.sshd
sudo launchctl start com.openssh.sshd

Concatenating bits in VHDL

You are not allowed to use the concatenation operator with the case statement. One possible solution is to use a variable within the process:

process(b0,b1,b2,b3)
   variable bcat : std_logic_vector(0 to 3);
begin
   bcat := b0 & b1 & b2 & b3;
   case bcat is
      when "0000" => x <= 1;
      when others => x <= 2;
   end case;
end process;

How can I change the color of AlertDialog title and the color of the line under it

Here is another solution (based on suggested answers) that handles the styling of the dialogs in one class without needing to worry about the state of the dialog when you change the style - dialog can be already shown or just initialized.

Usage example:

AlertDialog.Builder builder = new AlertDialog.Builder(context);
AlertDialog dialog = builder.create(); //or builder.show()
DialogViewDecorator.decorate(dialog, android.R.color.holo_red_light); //can also set the defaut color in the class

Implementation:

public class DialogViewDecorator {

private static final
@ColorRes int DEFAULT_TITLE_DIVIDER_COLOR = android.R.color.holo_orange_light;

public static void decorate(Dialog dialog) {
    decorate(dialog, DEFAULT_TITLE_DIVIDER_COLOR);
}

/**
 * Sets the title divider color when the view is shown by setting DialogInterface.OnShowListener on the dialog.
 * <p/>
 * If you want to do other things onShow be sure to extend OnDecoratedDialogShownListener(call super.show(...)!)
 * and call {@link #decorate(Dialog, int, OnDecoratedDialogShownListener)}.
 *
 * @param dialog
 * @param titleDividerColor
 */
public static void decorate(Dialog dialog, final int titleDividerColor) {
    decorate(dialog, titleDividerColor, new OnDecoratedDialogShownListener(titleDividerColor));
}

/**
 * Method for setting a extended implementation of OnDecoratedDialogShownListener. Don't forget to call super
 * or the titleDividerColor wont be applied!
 *
 * @param dialog
 * @param titleDividerColor
 * @param OnShowListener
 * @param <T>
 */
public static <T extends OnDecoratedDialogShownListener> void decorate(Dialog dialog, int titleDividerColor, T OnShowListener) {
    if (dialog == null || titleDividerColor <= 0) { return; }

    if (dialog.isShowing()) {
        setTitleDividerColor(dialog, titleDividerColor);
    } else {
        dialog.setOnShowListener(OnShowListener);
    }
}

private static void setTitleDividerColor(DialogInterface dialogInterface, int titleDividerColor) {
    try {
        Dialog dialog = (Dialog) dialogInterface;
        int dividerId = dialog.getContext().getResources().getIdentifier("android:id/titleDivider", null, null);
        View divider = dialog.findViewById(dividerId);
        if (divider != null) {
            divider.setBackgroundColor(dialog.getContext().getResources().getColor(titleDividerColor));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}


public static class OnDecoratedDialogShownListener implements DialogInterface.OnShowListener {
    private int titleDividerColor;

    public OnDecoratedDialogShownListener() {
        this.titleDividerColor = DEFAULT_TITLE_DIVIDER_COLOR;
    }

    public OnDecoratedDialogShownListener(int titleDividerColor) {
        this.titleDividerColor = titleDividerColor;
    }

    @Override
    public void onShow(DialogInterface dialogInterface) {
        setTitleDividerColor(dialogInterface, titleDividerColor);
    }
}}

In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

Setting readonly on a widget only makes the input in the browser read-only. Adding a clean_sku which returns instance.sku ensures the field value will not change on form level.

def clean_sku(self):
    if self.instance: 
        return self.instance.sku
    else: 
        return self.fields['sku']

This way you can use model's (unmodified save) and avoid getting the field required error.

In PHP, what is a closure and why does it use the "use" identifier?

The function () use () {} is like closure for PHP.

Without use, function cannot access parent scope variable

$s = "hello";
$f = function () {
    echo $s;
};

$f(); // Notice: Undefined variable: s
$s = "hello";
$f = function () use ($s) {
    echo $s;
};

$f(); // hello

The use variable's value is from when the function is defined, not when called

$s = "hello";
$f = function () use ($s) {
    echo $s;
};

$s = "how are you?";
$f(); // hello

use variable by-reference with &

$s = "hello";
$f = function () use (&$s) {
    echo $s;
};

$s = "how are you?";
$f(); // how are you?

installing JDK8 on Windows XP - advapi32.dll error

Oracle has announced fix for Windows XP installation error

Oracle has decided to fix Windows XP installation. As of the JRE 8u25 release in 10/15/2014 the code of the installer has been changes so that installation on Windows XP is again possible.

However, this does not mean that Oracle is continuing to support Windows XP. They make no guarantee about current and future releases of JRE8 being compatible with Windows XP. It looks like it's a run at your own risk kind of thing.

See the Oracle blog post here.

You can get the latest JRE8 right off the Oracle downloads site.

Twitter Bootstrap tabs not working: when I click on them nothing happens

The key elements include:

  1. the class="nav nav-tabs" and data-tabs="tabs" of ul
  2. the data-toggle="tab" and href="#orange" of the a
  3. the class="tab-content" of the div of the content
  4. the class="tab-pane" and id of the div of the items

The complete code is as below:

<ul class="nav nav-tabs" data-tabs="tabs">
    <li class="active"><a data-toggle="tab" href="#red">Red</a></li>
    <li><a data-toggle="tab" href="#orange">Orange</a></li>
    <li><a data-toggle="tab" href="#yellow">Yellow</a></li>
    <li><a data-toggle="tab" href="#green">Green</a></li>
    <li><a data-toggle="tab" href="#blue">Blue</a></li>
</ul>
<div class="tab-content">
    <div class="tab-pane active" id="red">
        <h1>Red</h1>
        <p>red red red red red red</p>
    </div>
    <div class="tab-pane" id="orange">
        <h1>Orange</h1>
        <p>orange orange orange orange orange</p>
    </div>
    <div class="tab-pane" id="yellow">
        <h1>Yellow</h1>
        <p>yellow yellow yellow yellow yellow</p>
    </div>
    <div class="tab-pane" id="green">
        <h1>Green</h1>
        <p>green green green green green</p>
    </div>
    <div class="tab-pane" id="blue">
        <h1>Blue</h1>
        <p>blue blue blue blue blue</p>
    </div>
</div>

Android studio: emulator is running but not showing up in Run App "choose a running device"

Your adb connection is broken.

close eclipse

open cmd-prompt type adb kill-server then adb start-server

reopen eclipse

run the project!

Python Web Crawlers and "getting" html source code

The first thing you need to do is read the HTTP spec which will explain what you can expect to receive over the wire. The data returned inside the content will be the "rendered" web page, not the source. The source could be a JSP, a servlet, a CGI script, in short, just about anything, and you have no access to that. You only get the HTML that the server sent you. In the case of a static HTML page, then yes, you will be seeing the "source". But for anything else you see the generated HTML, not the source.

When you say modify the page and return the modified page what do you mean?

Wrapping long text without white space inside of a div

I have found something strange here about word-wrap only works with width property of CSS properly.

_x000D_
_x000D_
#ONLYwidth {_x000D_
  width: 200px;_x000D_
}_x000D_
_x000D_
#wordwrapWITHOUTWidth {_x000D_
  word-wrap: break-word;_x000D_
}_x000D_
_x000D_
#wordwrapWITHWidth {_x000D_
  width: 200px;_x000D_
  word-wrap: break-word;_x000D_
}
_x000D_
<b>This is the example of word-wrap only using width property</b>_x000D_
<p id="ONLYwidth">827938828ey823876te37257e5t328er6367r5erd663275e65r532r6s3624e5645376er563rdr753624e544341763r567r4e56r326r5632r65sr32dr32udr56r634r57rd63725</p>_x000D_
<br/>_x000D_
<b>This is the example of word-wrap without width property</b>_x000D_
<p id="wordwrapWITHOUTWidth">827938828ey823876te37257e5t328er6367r5erd663275e65r532r6s3624e5645376er563rdr753624e544341763r567r4e56r326r5632r65sr32dr32udr56r634r57rd63725</p>_x000D_
<br/>_x000D_
<b>This is the example of word-wrap with width property</b>_x000D_
<p id="wordwrapWITHWidth">827938828ey823876te37257e5t328er6367r5erd663275e65r532r6s3624e5645376er563rdr753624e544341763r567r4e56r326r5632r65sr32dr32udr56r634r57rd63725</p>
_x000D_
_x000D_
_x000D_

Here is a working demo that I have prepared about it. http://jsfiddle.net/Hss5g/2/

How to get string objects instead of Unicode from JSON?

I've adapted the code from the answer of Mark Amery, particularly in order to get rid of isinstance for the pros of duck-typing.

The encoding is done manually and ensure_ascii is disabled. The python docs for json.dump says that

If ensure_ascii is True (the default), all non-ASCII characters in the output are escaped with \uXXXX sequences

Disclaimer: in the doctest I used the Hungarian language. Some notable Hungarian-related character encodings are: cp852 the IBM/OEM encoding used eg. in DOS (sometimes referred as ascii, incorrectly I think, it is dependent on the codepage setting), cp1250 used eg. in Windows (sometimes referred as ansi, dependent on the locale settings), and iso-8859-2, sometimes used on http servers. The test text Tüskéshátú kígyóbuvölo is attributed to Koltai László (native personal name form) and is from wikipedia.

# coding: utf-8
"""
This file should be encoded correctly with utf-8.
"""
import json

def encode_items(input, encoding='utf-8'):
    u"""original from: https://stackoverflow.com/a/13101776/611007
    adapted by SO/u/611007 (20150623)
    >>> 
    >>> ## run this with `python -m doctest <this file>.py` from command line
    >>> 
    >>> txt = u"Tüskéshátú kígyóbuvölo"
    >>> txt2 = u"T\\u00fcsk\\u00e9sh\\u00e1t\\u00fa k\\u00edgy\\u00f3b\\u0171v\\u00f6l\\u0151"
    >>> txt3 = u"uúuutifu"
    >>> txt4 = b'u\\xfauutifu'
    >>> # txt4 shouldn't be 'u\\xc3\\xbauutifu', string content needs double backslash for doctest:
    >>> assert u'\\u0102' not in b'u\\xfauutifu'.decode('cp1250')
    >>> txt4u = txt4.decode('cp1250')
    >>> assert txt4u == u'u\\xfauutifu', repr(txt4u)
    >>> txt5 = b"u\\xc3\\xbauutifu"
    >>> txt5u = txt5.decode('utf-8')
    >>> txt6 = u"u\\u251c\\u2551uutifu"
    >>> there_and_back_again = lambda t: encode_items(t, encoding='utf-8').decode('utf-8')
    >>> assert txt == there_and_back_again(txt)
    >>> assert txt == there_and_back_again(txt2)
    >>> assert txt3 == there_and_back_again(txt3)
    >>> assert txt3.encode('cp852') == there_and_back_again(txt4u).encode('cp852')
    >>> assert txt3 == txt4u,(txt3,txt4u)
    >>> assert txt3 == there_and_back_again(txt5)
    >>> assert txt3 == there_and_back_again(txt5u)
    >>> assert txt3 == there_and_back_again(txt4u)
    >>> assert txt3.encode('cp1250') == encode_items(txt4, encoding='utf-8')
    >>> assert txt3.encode('utf-8') == encode_items(txt5, encoding='utf-8')
    >>> assert txt2.encode('utf-8') == encode_items(txt, encoding='utf-8')
    >>> assert {'a':txt2.encode('utf-8')} == encode_items({'a':txt}, encoding='utf-8')
    >>> assert [txt2.encode('utf-8')] == encode_items([txt], encoding='utf-8')
    >>> assert [[txt2.encode('utf-8')]] == encode_items([[txt]], encoding='utf-8')
    >>> assert [{'a':txt2.encode('utf-8')}] == encode_items([{'a':txt}], encoding='utf-8')
    >>> assert {'b':{'a':txt2.encode('utf-8')}} == encode_items({'b':{'a':txt}}, encoding='utf-8')
    """
    try:
        input.iteritems
        return {encode_items(k): encode_items(v) for (k,v) in input.iteritems()}
    except AttributeError:
        if isinstance(input, unicode):
            return input.encode(encoding)
        elif isinstance(input, str):
            return input
        try:
            iter(input)
            return [encode_items(e) for e in input]
        except TypeError:
            return input

def alt_dumps(obj, **kwargs):
    """
    >>> alt_dumps({'a': u"T\\u00fcsk\\u00e9sh\\u00e1t\\u00fa k\\u00edgy\\u00f3b\\u0171v\\u00f6l\\u0151"})
    '{"a": "T\\xc3\\xbcsk\\xc3\\xa9sh\\xc3\\xa1t\\xc3\\xba k\\xc3\\xadgy\\xc3\\xb3b\\xc5\\xb1v\\xc3\\xb6l\\xc5\\x91"}'
    """
    if 'ensure_ascii' in kwargs:
        del kwargs['ensure_ascii']
    return json.dumps(encode_items(obj), ensure_ascii=False, **kwargs)

I'd also like to highlight the answer of Jarret Hardie which references the JSON spec, quoting:

A string is a collection of zero or more Unicode characters

In my use-case I had files with json. They are utf-8 encoded files. ensure_ascii results in properly escaped but not very readable json files, that is why I've adapted Mark Amery's answer to fit my needs.

The doctest is not particularly thoughtful but I share the code in the hope that it will useful for someone.

Does Python have a toString() equivalent, and can I convert a db.Model element to String?

In python, the str() method is similar to the toString() method in other languages. It is called passing the object to convert to a string as a parameter. Internally it calls the __str__() method of the parameter object to get its string representation.

In this case, however, you are comparing a UserProperty author from the database, which is of type users.User with the nickname string. You will want to compare the nickname property of the author instead with todo.author.nickname in your template.

How to align this span to the right of the div?

The solution using flexbox without justify-content: space-between.

<div class="title">
  <span>Cumulative performance</span>
  <span>20/02/2011</span>
</div>

.title {
  display: flex;
}

span:first-of-type {
  flex: 1;
}

When we use flex:1 on the first <span>, it takes up the entire remaining space and moves the second <span> to the right. The Fiddle with this solution: https://jsfiddle.net/2k1vryn7/

Here https://jsfiddle.net/7wvx2uLp/3/ you can see the difference between two flexbox approaches: flexbox with justify-content: space-between and flexbox with flex:1 on the first <span>.

Representing null in JSON

I would use null to show that there is no value for that particular key. For example, use null to represent that "number of devices in your household connects to internet" is unknown.

On the other hand, use {} if that particular key is not applicable. For example, you should not show a count, even if null, to the question "number of cars that has active internet connection" is asked to someone who does not own any cars.

I would avoid defaulting any value unless that default makes sense. While you may decide to use null to represent no value, certainly never use "null" to do so.

Find intersection of two nested lists?

# Problem:  Given c1 and c2:
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
# how do you get c3 to be [[13, 32], [7, 13, 28], [1, 6]] ?

Here's one way to set c3 that doesn't involve sets:

c3 = []
for sublist in c2:
    c3.append([val for val in c1 if val in sublist])

But if you prefer to use just one line, you can do this:

c3 = [[val for val in c1 if val in sublist]  for sublist in c2]

It's a list comprehension inside a list comprehension, which is a little unusual, but I think you shouldn't have too much trouble following it.

How to change the Eclipse default workspace?

If you mean to change the directory in which the program execution will occur, go to "Run configurations" in the Run tab.

Then select your project and go to the "Arguments" tab, you can change the directory there. By default it is the root directory of your project.

Is it possible to make input fields read-only through CSS?

Why not hide the input element and replace it with a label element with the same content?

I puzzled over how the React TODOMVC app accomplished this same thing and this is the strategy they came up with.

To see it in action, check out the app below, and watch the CSS properties of the TODO items when you double click them and then click away.

http://todomvc.com/examples/react-backbone/#/

When you render the page you can have either an editable input, or a non-editable label with display:none; depending on your media query.

React router nav bar example

Yes, Daniel is correct, but to expand upon his answer, your primary app component would need to have a navbar component within it. That way, when you render the primary app (any page under the '/' path), it would also display the navbar. I am guessing that you wouldn't want your login page to display the navbar, so that shouldn't be a nested component, and should instead be by itself. So your routes would end up looking something like this:

<Router>
  <Route path="/" component={App}>
    <Route path="page1" component={Page1} />
    <Route path="page2" component={Page2} />
  </Route>
  <Route path="/login" component={Login} />
</Router>

And the other components would look something like this:

var NavBar = React.createClass({
  render() {
    return (
      <div>
        <ul>
          <a onClick={() => history.push('page1') }>Page 1</a>
          <a onClick={() => history.push('page2') }>Page 2</a>
        </ul>
      </div>
    )
  }
});

var App = React.createClass({
  render() {
    return (
      <div>
        <NavBar />
        <div>Other Content</div>
        {this.props.children}
      </div>
    )
  }
});

How do I implement Cross Domain URL Access from an Iframe using Javascript?

You might want to take a look at these questions/answers ; they could give you some informations concerning your problem :

To make things short : accessing iframe from another domain is not possible, for security reasons -- which explains the error message you are getting.


The Same origin policy page on wikipedia brings some informations about that security measure :

In a nutshell, the policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions — but prevents access to most methods and properties across pages on different sites.

A strict separation between content provided by unrelated sites must be maintained on client side to prevent the loss of data confidentiality or integrity.

How do I catch a PHP fatal (`E_ERROR`) error?

I need to handle fatal errors for production to instead show a static styled 503 Service Unavailable HTML output. This is surely a reasonable approach to "catching fatal errors". This is what I've done:

I have a custom error handling function "error_handler" which will display my "503 service unavailable" HTML page on any E_ERROR, E_USER_ERROR, etc. This will now be called on the shutdown function, catching my fatal error,

function fatal_error_handler() {

    if (@is_array($e = @error_get_last())) {
        $code = isset($e['type']) ? $e['type'] : 0;
        $msg = isset($e['message']) ? $e['message'] : '';
        $file = isset($e['file']) ? $e['file'] : '';
        $line = isset($e['line']) ? $e['line'] : '';
        if ($code>0)
            error_handler($code, $msg, $file, $line);
    }
}
set_error_handler("error_handler");
register_shutdown_function('fatal_error_handler');

in my custom error_handler function, if the error is E_ERROR, E_USER_ERROR, etc. I also call @ob_end_clean(); to empty the buffer, thus removing PHP's "fatal error" message.

Take important note of the strict isset() checking and @ silencing functions since we don’t want our error_handler scripts to generate any errors.

In still agreeing with keparo, catching fatal errors does defeat the purpose of "FATAL error" so it's not really intended for you to do further processing. Do not run any mail() functions in this shutdown process as you will certainly back up the mail server or your inbox. Rather log these occurrences to file and schedule a cron job to find these error.log files and mail them to administrators.

Regex for empty string or white space

If you're using jQuery, you have .trim().

if ($("#siren").val().trim() == "") {
  // it's empty
}

Find the day of a week

This should do the trick

df = data.frame(date=c("2012-02-01", "2012-02-01", "2012-02-02")) 
dow <- function(x) format(as.Date(x), "%A")
df$day <- dow(df$date)
df

#Returns:
        date       day
1 2012-02-01 Wednesday
2 2012-02-01 Wednesday
3 2012-02-02  Thursday

Split array into chunks of N length

Maybe this code helps:

_x000D_
_x000D_
var chunk_size = 10;_x000D_
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];_x000D_
var groups = arr.map( function(e,i){ _x000D_
     return i%chunk_size===0 ? arr.slice(i,i+chunk_size) : null; _x000D_
}).filter(function(e){ return e; });_x000D_
console.log({arr, groups})
_x000D_
_x000D_
_x000D_

AngularJS - Attribute directive input value change

Since this must have an input element as a parent, you could just use

<input type="text" ng-model="foo" ng-change="myOnChangeFunction()">

Alternatively, you could use the ngModelController and add a function to $formatters, which executes functions on input change. See http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController

.directive("myDirective", function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attr, ngModel) {
      ngModel.$formatters.push(function(value) {
        // Do stuff here, and return the formatted value.
      });
  };
};

Modify SVG fill color when being served as Background-Image

Now you can achieve this on the client side like this:

var green = '3CB54A';
var red = 'ED1F24';
var svg = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"  width="320px" height="100px" viewBox="0 0 320 100" enable-background="new 0 0 320 100" xml:space="preserve"> <polygon class="mystar" fill="#'+green+'" points="134.973,14.204 143.295,31.066 161.903,33.77 148.438,46.896 151.617,65.43 134.973,56.679 118.329,65.43 121.507,46.896 108.042,33.77 126.65,31.066 "/><circle class="mycircle" fill="#'+red+'" cx="202.028" cy="58.342" r="12.26"/></svg>';      
var encoded = window.btoa(svg);
document.body.style.background = "url(data:image/svg+xml;base64,"+encoded+")";

Fiddle here!

sum two columns in R

Try this for creating a column3 as a sum of column1 + column 2 in a table

tablename$column3=rowSums(cbind(tablename$column1,tablename$column2))

Setting format and value in input type="date"

try this :)

function getDefaultDate(){

    var now = new Date();
    var day = ("0" + now.getDate()).slice(-2);
    var month = ("0" + (now.getMonth() + 1)).slice(-2);
    var today = now.getFullYear()+"-"+(month)+"-"+(day) ;

    return today;
}

$(document).ready(function(){ 
    $("#dateid").val( getDefaultDate()); 
});

SQL Server IIF vs CASE

IIF is the same as CASE WHEN <Condition> THEN <true part> ELSE <false part> END. The query plan will be the same. It is, perhaps, "syntactical sugar" as initially implemented.

CASE is portable across all SQL platforms whereas IIF is SQL SERVER 2012+ specific.

Binding value to input in Angular JS

Use ng-value for set value of input box after clicking on a button:

"input type="email"  class="form-control" id="email2" ng-value="myForm.email2" placeholder="Email"

and

Set Value as:

 $scope.myForm.email2 = $scope.names[0].success;

Eclipse HotKey: how to switch between tabs?

If you want to simply switch between your current and your previous tab selections, using CTRL + F6 will switch you back and forth. To navigate to a tab further back in your history, you need to use the UP / DOWN keys while the Editors window is open. This works with Helios (Eclipse 3.6); not sure if this is true for older versions of Eclipse.

Cookies on localhost with explicit domain

Tried all of the options above. What worked for me was:

  1. Make sure the request to server have withCredentials set to true. XMLHttpRequest from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request.
  2. Do not set Domain
  3. Set Path=/

Resulting Set-Cookie header:

Set-Cookie: session_token=74528588-7c48-4546-a3ae-4326e22449e5; Expires=Sun, 16 Aug 2020 04:40:42 GMT; Path=/

Compare two objects' properties to find differences?

Type.GetProperties will list each of the properties of a given type. Then use PropertyInfo.GetValue to check the values.

Sending websocket ping/pong frame from browser

There is no Javascript API to send ping frames or receive pong frames. This is either supported by your browser, or not. There is also no API to enable, configure or detect whether the browser supports and is using ping/pong frames. There was discussion about creating a Javascript ping/pong API for this. There is a possibility that pings may be configurable/detectable in the future, but it is unlikely that Javascript will be able to directly send and receive ping/pong frames.

However, if you control both the client and server code, then you can easily add ping/pong support at a higher level. You will need some sort of message type header/metadata in your message if you don't have that already, but that's pretty simple. Unless you are planning on sending pings hundreds of times per second or have thousands of simultaneous clients, the overhead is going to be pretty minimal to do it yourself.

Radio Buttons ng-checked with ng-model

I think you should only use ng-model and should work well for you, here is the link to the official documentation of angular https://docs.angularjs.org/api/ng/input/input%5Bradio%5D

The code from the example should not be difficult to adapt to your specific situation:

<script>
   function Ctrl($scope) {
      $scope.color = 'blue';
      $scope.specialValue = {
         "id": "12345",
         "value": "green"
      };
   }
</script>
<form name="myForm" ng-controller="Ctrl">
   <input type="radio" ng-model="color" value="red">  Red <br/>
   <input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
   <input type="radio" ng-model="color" value="blue"> Blue <br/>
   <tt>color = {{color | json}}</tt><br/>
</form>

installing apache: no VCRUNTIME140.dll

Be sure you have C++ Redistributable for Visual Studio 2015 RC. Try to download the last version:

https://www.microsoft.com/en-us/download/details.aspx?id=52685

Obs: Credit to parsecer

How can I declare a two dimensional string array?

string[,] Tablero = new string[3,3];

Received fatal alert: handshake_failure through SSLHandshakeException

This can also happend when the client needs to present a certificate. After the server lists the certificate chain, the following can happen:

3. Certificate Request The server will issue a certificate request from the client. The request will list all of the certificates the server accepts.

*** CertificateRequest
Cert Types: RSA
Cert Authorities:
<CN=blah, OU=blah, O=blah, L=blah, ST=blah, C=blah>
<CN=yadda, DC=yadda, DC=yadda>
<CN=moreblah, OU=moreblah, O=moreblah, C=moreblah>
<CN=moreyada, OU=moreyada, O=moreyada, C=moreyada>
... the rest of the request
*** ServerHelloDone

4. Client Certificate Chain This is the certificate the client is sending to the server.

*** Certificate chain
chain [0] = [
[
  Version: V3
  Subject: EMAILADDRESS=client's email, CN=client, OU=client's ou, O=client's Org, L=client's location, ST=client's state, C=client's Country
  Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5
  ... the rest of the certificate
*** ClientKeyExchange, RSA PreMasterSecret, TLSv1    
... key exchange info 

If there isn't a certificate in the chain and the server requires one, you'll get the handshake error here. A likely cause is the path to your certificate wasn't found.

5. Certificate Verify The client asks the server to verify the certificate

*** CertificateVerify
... payload of verify check

This step will only happen if you are sending a certificate.

6. Finished The server will respond with a verify response

*** Finished
verify_data:  { 345, ... }

Simple example of threading in C++

Well, technically any such object will wind up being built over a C-style thread library because C++ only just specified a stock std::thread model in c++0x, which was just nailed down and hasn't yet been implemented. The problem is somewhat systemic, technically the existing c++ memory model isn't strict enough to allow for well defined semantics for all of the 'happens before' cases. Hans Boehm wrote an paper on the topic a while back and was instrumental in hammering out the c++0x standard on the topic.

http://www.hpl.hp.com/techreports/2004/HPL-2004-209.html

That said there are several cross-platform thread C++ libraries that work just fine in practice. Intel thread building blocks contains a tbb::thread object that closely approximates the c++0x standard and Boost has a boost::thread library that does the same.

http://www.threadingbuildingblocks.org/

http://www.boost.org/doc/libs/1_37_0/doc/html/thread.html

Using boost::thread you'd get something like:

#include <boost/thread.hpp>

void task1() { 
    // do stuff
}

void task2() { 
    // do stuff
}

int main (int argc, char ** argv) {
    using namespace boost; 
    thread thread_1 = thread(task1);
    thread thread_2 = thread(task2);

    // do other stuff
    thread_2.join();
    thread_1.join();
    return 0;
}

Open files always in a new tab

One simple solution is, instead of making changes in settings of vscode, whenever you open a file through a reference,you will see that the file is in preview mode(the name of file is in italic) and in the sidebar you will see that same preview file in focus just double tap it and it will be pinned on the tab,so that it wont get replaced by another file in preview mode.

Importing two classes with same name. How to handle?

If you really want or need to use the same class name from two different packages, you have two options:

1-pick one to use in the import and use the other's fully qualified class name:

import my.own.Date;

class Test{

     public static void main(String[] args){

        // I want to choose my.own.Date here. How?
        //Answer:
        Date ownDate = new Date();

        // I want to choose util.Date here. How ?
        //Answer:
        java.util.Date utilDate = new java.util.Date();

     }
}


2-always use the fully qualified class name:

//no Date import
class Test{

  public static void main(String[] args){

    // I want to choose my.own.Date here. How?
    //Answer:
     my.own.Date ownDate = new my.own.Date();
    // I want to choose util.Date here. How ?
    //Answer:
     java.util.Date utilDate = new java.util.Date();

  }
}

What is the difference between jQuery: text() and html() ?

$('.div').html(val) will set the HTML values of all selected elements, $('.div').text(val) will set the text values of all selected elements.

API docs for jQuery.text()

API docs for jQuery.html()

I would guess that they correspond to Node#textContent and Element#innerHTML, respectively. (Gecko DOM references).

Immediate exit of 'while' loop in C++

while(choice!=99)
{
  cin>>choice;
  if (choice==99)
    exit(0);
  cin>>gNum;
}

Trust me, that will exit the loop. If that doesn't work nothing will. Mind, this may not be what you want...

How to handle authentication popup with Selenium WebDriver using Java

Selenium 4 supports authenticating using Basic and Digest auth . It's using the CDP and currently only supports chromium-derived browsers

Java Example :

Webdriver driver = new ChromeDriver();

((HasAuthentication) driver).register(UsernameAndPassword.of("username", "pass"));

driver.get("http://sitewithauth");

Note : In Alpha-7 there is bug where it send username for both user/password. Need to wait for next release of selenium version as fix is available in trunk https://github.com/SeleniumHQ/selenium/commit/4917444886ba16a033a81a2a9676c9267c472894

Hash function that produces short hashes?

Simply run this in a terminal (on MacOS or Linux):

crc32 <(echo "some string")

8 characters long.

Where do I put my php files to have Xampp parse them?

in XAMPP the default root is "htdocs" inside the XAMPP folder, if you followed the instructions on the xampp homepage it would be "/opt/lampp/htdocs"

How to define multiple CSS attributes in jQuery?

Try this

$(element).css({
    "propertyName1":"propertyValue1",
    "propertyName2":"propertyValue2"
})

In Python, what does dict.pop(a,b) mean?

So many questions here. I see at least two, maybe three:

  • What does pop(a,b) do?/Why are there a second argument?
  • What is *args being used for?

The first question is trivially answered in the Python Standard Library reference:

pop(key[, default])

If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.


The second question is covered in the Python Language Reference:

If the form “*identifier” is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form “**identifier” is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary.

In other words, the pop function takes at least two arguments. The first two get assigned the names self and key; and the rest are stuffed into a tuple called args.

What's happening on the next line when *args is passed along in the call to self.data.pop is the inverse of this - the tuple *args is expanded to of positional parameters which get passed along. This is explained in the Python Language Reference:

If the syntax *expression appears in the function call, expression must evaluate to a sequence. Elements from this sequence are treated as if they were additional positional arguments

In short, a.pop() wants to be flexible and accept any number of positional parameters, so that it can pass this unknown number of positional parameters on to self.data.pop().

This gives you flexibility; data happens to be a dict right now, and so self.data.pop() takes either one or two parameters; but if you changed data to be a type which took 19 parameters for a call to self.data.pop() you wouldn't have to change class a at all. You'd still have to change any code that called a.pop() to pass the required 19 parameters though.

FromBody string parameter is giving null

I know this answer is kinda old and there are some very good answers who already solve the problem. In order to expand the issue I'd like to mention one more thing that has driven me crazy for the last 4 or 5 hours.

It is VERY VERY VERY important that your properties in your model class have the set attribute enabled.

This WILL NOT work (parameter still null):

/* Action code */
[HttpPost]
public Weird NOURLAuthenticate([FromBody] Weird form) {
    return form;
}
/* Model class code */
public class Weird {
    public string UserId {get;}
    public string UserPwd {get;}
}

This WILL work:

/* Action code */
[HttpPost]
public Weird NOURLAuthenticate([FromBody] Weird form) {
    return form;
}
/* Model class code */
public class Weird {
    public string UserId {get; set;}
    public string UserPwd {get; set;}
}

C#: Limit the length of a string?

string shortFoo = foo.Length > 5 ? foo.Substring(0, 5) : foo;

Note that you can't just use foo.Substring(0, 5) by itself because it will throw an error when foo is less than 5 characters.

Iterate over values of object

In case you want to deeply iterate into a complex (nested) object for each key & value, you can do so using Object.keys():

const iterate = (obj) => {
    Object.keys(obj).forEach(key => {

    console.log(`key: ${key}, value: ${obj[key]}`)

    if (typeof obj[key] === 'object') {
            iterate(obj[key])
        }
    })
}

What is the difference between parseInt() and Number()?

Summary:

parseInt():

  • Takes a string as a first argument, the radix (An integer which is the base of a numeral system e.g. decimal 10 or binary 2) as a second argument
  • The function returns a integer number, if the first character cannot be converted to a number NaN will be returned.
  • If the parseInt() function encounters a non numerical value, it will cut off the rest of input string and only parse the part until the non numerical value.
  • If the radix is undefined or 0, JS will assume the following:
    • If the input string begins with "0x" or "0X", the radix is 16 (hexadecimal), the remainder of the string is parsed into a number.
    • If the input value begins with a 0 the radix can be either 8 (octal) or 10 (decimal). Which radix is chosen is depending on JS engine implementation. ES5 specifies that 10 should be used then. However, this is not supported by all browsers, therefore always specify radix if your numbers can begin with a 0.
    • If the input value begins with any number, the radix will be 10

Number():

  • The Number() constructor can convert any argument input into a number. If the Number() constructor cannot convert the input into a number, NaN will be returned.
  • The Number() constructor can also handle hexadecimal number, they have to start with 0x.

Example:

_x000D_
_x000D_
console.log(parseInt('0xF', 16));  // 15_x000D_
_x000D_
// z is no number, it will only evaluate 0xF, therefore 15 is logged_x000D_
console.log(parseInt('0xFz123', 16));_x000D_
_x000D_
// because the radix is 10, A is considered a letter not a number (like in Hexadecimal)_x000D_
// Therefore, A will be cut off the string and 10 is logged_x000D_
console.log(parseInt('10A', 10));  // 10_x000D_
_x000D_
// first character isnot a number, therefore parseInt will return NaN_x000D_
console.log(parseInt('a1213', 10));_x000D_
_x000D_
_x000D_
console.log('\n');_x000D_
_x000D_
_x000D_
// start with 0X, therefore Number will interpret it as a hexadecimal value_x000D_
console.log(Number('0x11'));_x000D_
_x000D_
// Cannot be converted to a number, NaN will be returned, notice that_x000D_
// the number constructor will not cut off a non number part like parseInt does_x000D_
console.log(Number('123A'));_x000D_
_x000D_
// scientific notation is allowed_x000D_
console.log(Number('152e-1'));  // 15.21
_x000D_
_x000D_
_x000D_

Sql error on update : The UPDATE statement conflicted with the FOREIGN KEY constraint

In MySQL

set foreign_key_checks=0;

UPDATE patient INNER JOIN patient_address 
ON patient.id_no=patient_address.id_no 
SET patient.id_no='8008255601088', 
patient_address.id_no=patient.id_no 
WHERE patient.id_no='7008255601088';

Note that foreign_key_checks only temporarily set foreign key checking false. So it need to execute every time before update statement. We set it 0 as if we update parent first then that will not be allowed as child may have already that value. And if we update child first then that will also be not allowed as parent may not have that value from which we are updating. So we need to set foreign key check. Another thing is that if you are using command line tool to use this query then put care to mention spaces in place where i put new line or ENTER in code. As command line take it in one line, so it may happen that two words stick as patient_addressON which create syntax error.

Object Required Error in excel VBA

The Set statement is only used for object variables (like Range, Cell or Worksheet in Excel), while the simple equal sign '=' is used for elementary datatypes like Integer. You can find a good explanation for when to use set here.

The other problem is, that your variable g1val isn't actually declared as Integer, but has the type Variant. This is because the Dim statement doesn't work the way you would expect it, here (see example below). The variable has to be followed by its type right away, otherwise its type will default to Variant. You can only shorten your Dim statement this way:

Dim intColumn As Integer, intRow As Integer  'This creates two integers

For this reason, you will see the "Empty" instead of the expected "0" in the Watches window.

Try this example to understand the difference:

Sub Dimming()

  Dim thisBecomesVariant, thisIsAnInteger As Integer
  Dim integerOne As Integer, integerTwo As Integer

  MsgBox TypeName(thisBecomesVariant)  'Will display "Empty"
  MsgBox TypeName(thisIsAnInteger )  'Will display "Integer"
  MsgBox TypeName(integerOne )  'Will display "Integer"
  MsgBox TypeName(integerTwo )  'Will display "Integer"

  'By assigning an Integer value to a Variant it becomes Integer, too
  thisBecomesVariant = 0
  MsgBox TypeName(thisBecomesVariant)  'Will display "Integer"

End Sub

Two further notices on your code:

First remark: Instead of writing

'If g1val is bigger than the value in the current cell
If g1val > Cells(33, i).Value Then
  g1val = g1val   'Don't change g1val
Else
  g1val = Cells(33, i).Value  'Otherwise set g1val to the cell's value
End If

you could simply write

'If g1val is smaller or equal than the value in the current cell
If g1val <= Cells(33, i).Value Then
  g1val = Cells(33, i).Value  'Set g1val to the cell's value 
End If

Since you don't want to change g1val in the other case.

Second remark: I encourage you to use Option Explicit when programming, to prevent typos in your program. You will then have to declare all variables and the compiler will give you a warning if a variable is unknown.

Send JSON via POST in C# and Receive the JSON returned?

You can also use the PostAsJsonAsync() method available in HttpClient()

_x000D_
_x000D_
   var requestObj= JsonConvert.SerializeObject(obj);_x000D_
   HttpResponseMessage response = await    client.PostAsJsonAsync($"endpoint",requestObj).ConfigureAwait(false);
_x000D_
_x000D_
_x000D_

How to create JNDI context in Spring Boot with Embedded Tomcat Container

I recently had the requirement to use JNDI with an embedded Tomcat in Spring Boot.
Actual answers give some interesting hints to solve my task but it was not enough as probably not updated for Spring Boot 2.

Here is my contribution tested with Spring Boot 2.0.3.RELEASE.

Specifying a datasource available in the classpath at runtime

You have multiple choices :

  • using the DBCP 2 datasource (you don't want to use DBCP 1 that is outdated and less efficient).
  • using the Tomcat JDBC datasource.
  • using any other datasource : for example HikariCP.

If you don't specify anyone of them, with the default configuration the instantiation of the datasource will throw an exception :

Caused by: javax.naming.NamingException: Could not create resource factory instance
        at org.apache.naming.factory.ResourceFactory.getDefaultFactory(ResourceFactory.java:50)
        at org.apache.naming.factory.FactoryBase.getObjectInstance(FactoryBase.java:90)
        at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:321)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:839)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:159)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:827)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:159)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:827)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:159)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:827)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:173)
        at org.apache.naming.SelectorContext.lookup(SelectorContext.java:163)
        at javax.naming.InitialContext.lookup(InitialContext.java:417)
        at org.springframework.jndi.JndiTemplate.lambda$lookup$0(JndiTemplate.java:156)
        at org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:91)
        at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:156)
        at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:178)
        at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:96)
        at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:114)
        at org.springframework.jndi.JndiObjectTargetSource.getTarget(JndiObjectTargetSource.java:140)
        ... 39 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:264)
        at org.apache.naming.factory.ResourceFactory.getDefaultFactory(ResourceFactory.java:47)
        ... 58 common frames omitted

  • To use Apache JDBC datasource, you don't need to add any dependency but you have to change the default factory class to org.apache.tomcat.jdbc.pool.DataSourceFactory.
    You can do it in the resource declaration : resource.setProperty("factory", "org.apache.tomcat.jdbc.pool.DataSourceFactory"); I will explain below where add this line.

  • To use DBCP 2 datasource a dependency is required:

    <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-dbcp</artifactId> <version>8.5.4</version> </dependency>

Of course, adapt the artifact version according to your Spring Boot Tomcat embedded version.

  • To use HikariCP, add the required dependency if not already present in your configuration (it may be if you rely on persistence starters of Spring Boot) such as :

    <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>3.1.0</version> </dependency>

and specify the factory that goes with in the resource declaration:

resource.setProperty("factory", "com.zaxxer.hikari.HikariJNDIFactory");

Datasource configuration/declaration

You have to customize the bean that creates the TomcatServletWebServerFactory instance.
Two things to do :

  • enabling the JNDI naming which is disabled by default

  • creating and add the JNDI resource(s) in the server context

For example with PostgreSQL and a DBCP 2 datasource, do that :

@Bean
public TomcatServletWebServerFactory tomcatFactory() {
    return new TomcatServletWebServerFactory() {
        @Override
        protected TomcatWebServer getTomcatWebServer(org.apache.catalina.startup.Tomcat tomcat) {
            tomcat.enableNaming(); 
            return super.getTomcatWebServer(tomcat);
        }

        @Override 
        protected void postProcessContext(Context context) {

            // context
            ContextResource resource = new ContextResource();
            resource.setName("jdbc/myJndiResource");
            resource.setType(DataSource.class.getName());
            resource.setProperty("driverClassName", "org.postgresql.Driver");

            resource.setProperty("url", "jdbc:postgresql://hostname:port/dbname");
            resource.setProperty("username", "username");
            resource.setProperty("password", "password");
            context.getNamingResources()
                   .addResource(resource);          
        }
    };
}

Here the variants for Tomcat JDBC and HikariCP datasource.

In postProcessContext() set the factory property as explained early for Tomcat JDBC ds :

    @Override 
    protected void postProcessContext(Context context) {
        ContextResource resource = new ContextResource();       
        //...
        resource.setProperty("factory", "org.apache.tomcat.jdbc.pool.DataSourceFactory");
        //...
        context.getNamingResources()
               .addResource(resource);          
    }
};

and for HikariCP :

    @Override 
    protected void postProcessContext(Context context) {
        ContextResource resource = new ContextResource();       
        //...
        resource.setProperty("factory", "com.zaxxer.hikari.HikariDataSource");
        //...
        context.getNamingResources()
               .addResource(resource);          
    }
};

Using/Injecting the datasource

You should now be able to lookup the JNDI ressource anywhere by using a standard InitialContext instance :

InitialContext initialContext = new InitialContext();
DataSource datasource = (DataSource) initialContext.lookup("java:comp/env/jdbc/myJndiResource");

You can also use JndiObjectFactoryBean of Spring to lookup up the resource :

JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName("java:comp/env/jdbc/myJndiResource");
bean.afterPropertiesSet();
DataSource object = (DataSource) bean.getObject();

To take advantage of the DI container you can also make the DataSource a Spring bean :

@Bean(destroyMethod = "")
public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
    JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
    bean.setJndiName("java:comp/env/jdbc/myJndiResource");
    bean.afterPropertiesSet();
    return (DataSource) bean.getObject();
}

And so you can now inject the DataSource in any Spring beans such as :

@Autowired
private DataSource jndiDataSource;

Note that many examples on the internet seem to disable the lookup of the JNDI resource on startup :

bean.setJndiName("java:comp/env/jdbc/myJndiResource");
bean.setProxyInterface(DataSource.class);
bean.setLookupOnStartup(false);
bean.afterPropertiesSet(); 

But I think that it is helpless as it invokes just after afterPropertiesSet() that does the lookup !

Difference between IsNullOrEmpty and IsNullOrWhiteSpace in C#

String.IsNullOrEmpty(string value) returns true if the string is null or empty. For reference an empty string is represented by "" (two double quote characters)

String.IsNullOrWhitespace(string value) returns true if the string is null, empty, or contains only whitespace characters such as a space or tab.

To see what characters count as whitespace consult this link: http://msdn.microsoft.com/en-us/library/t809ektx.aspx

How do I increase modal width in Angular UI Bootstrap?

I found it easier to just take over the template from Bootstrap-ui. I have left the commented HTML still in-place to show what I changed.

Overwrite their default template:

<script type="text/ng-template" id="myDlgTemplateWrapper.html">
    <div tabindex="-1" role="dialog" class="modal fade" ng-class="{in: animate}" 
         ng-style="{'z-index': 1050 + index*10, display: 'block'}" ng-click="close($event)"> 
        <!-- <div class="modal-dialog"
            ng-class="{'modal-sm': size == 'sm', 'modal-lg': size == 'lg'}"
            >
            <div class="modal-content"  modal-transclude></div>
        </div>--> 

        <div modal-transclude>
            <!-- Your content goes here -->
        </div>
    </div>
</script>

Modify your dialog template (note the wrapper DIVs containing "modal-dialog" class and "modal-content" class):

<script type="text/ng-template" id="myModalContent.html">
    <div class="modal-dialog {{extraDlgClass}}"
         style="width: {{width}}; max-width: {{maxWidth}}; min-width: {{minWidth}}; ">
        <div class="modal-content">
            <div class="modal-header bg-primary">
                <h3>I am a more flexible modal!</h3>
            </div>
            <div class="modal-body"
                 style="min-height: {{minHeight}}; height: {{height}}; max-height {{maxHeight}}; ">
                <p>Make me any size you want</p>
            </div>
            <div class="modal-footer">
                <button class="btn btn-primary" ng-click="ok()">OK</button>
                <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
            </div>
        </div>
    </div>
</script>

And then call the modal with whatever CSS class or style parameters you wish to change (assuming you have already defined "app" somewhere else):

<script type="text/javascript">
    app.controller("myTest", ["$scope", "$modal", function ($scope, $modal)
    {
        //  Adjust these with your parameters as needed

        $scope.extraDlgClass = undefined;

        $scope.width = "70%";
        $scope.height = "200px";
        $scope.maxWidth = undefined;
        $scope.maxHeight = undefined;
        $scope.minWidth = undefined;
        $scope.minHeight = undefined;

        $scope.open = function ()
        {
            $scope.modalInstance = $modal.open(
            {
                backdrop: 'static',
                keyboard: false,
                modalFade: true,

                templateUrl: "myModalContent.html",
                windowTemplateUrl: "myDlgTemplateWrapper.html",
                scope: $scope,
                //size: size,   - overwritten by the extraDlgClass below (use 'modal-lg' or 'modal-sm' if desired)

                extraDlgClass: $scope.extraDlgClass,

                width: $scope.width,
                height: $scope.height,
                maxWidth: $scope.maxWidth,
                maxHeight: $scope.maxHeight,
                minWidth: $scope.minWidth,
                minHeight: $scope.minHeight
            });

            $scope.modalInstance.result.then(function ()
            {
                console.log('Modal closed at: ' + new Date());
            },
            function ()
            {
                console.log('Modal dismissed at: ' + new Date());
            });
        };

        $scope.ok = function ($event)
        {
            if ($event)
                $event.preventDefault();
            $scope.modalInstance.close("OK");
        };

        $scope.cancel = function ($event)
        {
            if ($event)
                $event.preventDefault();
            $scope.modalInstance.dismiss('cancel');
        };

        $scope.openFlexModal = function ()
        {
            $scope.open();
        }

    }]);
</script>

Add an "open" button and fire away.

    <button ng-controller="myTest" class="btn btn-default" type="button" ng-click="openFlexModal();">Open Flex Modal!</button>

Now you can add whatever extra class you want, or simply change width/height sizes as necessary.

I further enclosed it within a wrapper directive, which is should be trivial from this point forward.

Cheers.

CardView not showing Shadow in Android L

Card view can't show shadow because of your RelativeLayout is on the card view's shadow. To show the shadow add margins on your Card view. For example:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginTop="4dp"
    android:layout_marginBottom="8dp">

</android.support.v7.widget.CardView>

</RelativeLayout>

"implements Runnable" vs "extends Thread" in Java

Moral of the story:

Inherit only if you want to override some behavior.

Or rather it should be read as:

Inherit less, interface more.

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

_x000D_
_x000D_
//find duplicates:_x000D_
//sort, then reduce - concat values equal previous element, skip others_x000D_
_x000D_
//input_x000D_
var a = [1, 2, 3, 1, 2, 1, 2]_x000D_
_x000D_
//short version:_x000D_
var duplicates = a.sort().reduce((d, v, i, a) => i && v === a[i - 1] ? d.concat(v) : d, [])_x000D_
console.log(duplicates); //[1, 1, 2, 2]_x000D_
_x000D_
//readable version:_x000D_
var duplicates = a.sort().reduce((output, element, index, input) => {_x000D_
  if ((index > 0) && (element === input[index - 1]))_x000D_
    return output.concat(element)_x000D_
  return output_x000D_
}, [])_x000D_
console.log(duplicates); //[1, 1, 2, 2]
_x000D_
_x000D_
_x000D_

Center div on the middle of screen

2018: CSS3

div{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%);
}

This is even shorter. For more information see this: CSS: Centering Things

How to undo the last commit in git

Try simply to reset last commit using --soft flag

git reset --soft HEAD~1

Note :

For Windows, wrap the HEAD parts in quotes like git reset --soft "HEAD~1"

Get distance between two points in canvas

You can do it with pythagoras theorem

If you have two points (x1, y1) and (x2, y2) then you can calculate the difference in x and difference in y, lets call them a and b.

enter image description here

var a = x1 - x2;
var b = y1 - y2;

var c = Math.sqrt( a*a + b*b );

// c is the distance

Confirm password validation in Angular 6

The simplest way imo:

(It can also be used with emails for example)

public static matchValues(
    matchTo: string // name of the control to match to
  ): (AbstractControl) => ValidationErrors | null {
    return (control: AbstractControl): ValidationErrors | null => {
      return !!control.parent &&
        !!control.parent.value &&
        control.value === control.parent.controls[matchTo].value
        ? null
        : { isMatching: false };
    };
}

In your Component:

this.SignUpForm = this.formBuilder.group({

password: [undefined, [Validators.required]],
passwordConfirm: [undefined, 
        [
          Validators.required,
          matchValues('password'),
        ],
      ],
});

Follow up:

As others pointed out in the comments, if you fix the error by fixing the password field the error won't go away, Because the validation triggers on passwordConfirm input. This can be fixed by a number of ways. I think the best is:

this.SignUpForm .controls.password.valueChanges.subscribe(() => {
  this.SignUpForm .controls.confirmPassword.updateValueAndValidity();
});

On password change, revliadte confirmPassword.

How to clear form after submit in Angular 2?

Here is how I do it in Angular 7.3

// you can put this method in a module and reuse it as needed
resetForm(form: FormGroup) {

    form.reset();

    Object.keys(form.controls).forEach(key => {
      form.get(key).setErrors(null) ;
    });
}

There was no need to call form.clearValidators()

Find the unique values in a column and then sort them

Another way is using set data type.

Some characteristic of Sets: Sets are unordered, can include mixed data types, elements in a set cannot be repeated, are mutable.

Solving your question:

df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
sorted(set(df.A))

The answer in List type:

[1, 2, 3, 6, 8]

How to import Swagger APIs into Postman?

I work on PHP and have used Swagger 2.0 to document the APIs. The Swagger Document is created on the fly (at least that is what I use in PHP). The document is generated in the JSON format.

Sample document

{
    "swagger": "2.0",
    "info": {
    "title": "Company Admin Panel",
        "description": "Converting the Magento code into core PHP and RESTful APIs for increasing the performance of the website.",
        "contact": {
        "email": "[email protected]"
        },
        "version": "1.0.0"
    },
    "host": "localhost/cv_admin/api",
    "schemes": [
    "http"
],
    "paths": {
    "/getCustomerByEmail.php": {
        "post": {
            "summary": "List the details of customer by the email.",
                "consumes": [
                "string",
                "application/json",
                "application/x-www-form-urlencoded"
            ],
                "produces": [
                "application/json"
            ],
                "parameters": [
                    {
                        "name": "email",
                        "in": "body",
                        "description": "Customer email to ge the data",
                        "required": true,
                        "schema": {
                        "properties": {
                            "id": {
                                "properties": {
                                    "abc": {
                                        "properties": {
                                            "inner_abc": {
                                                "type": "number",
                                                    "default": 1,
                                                    "example": 123
                                                }
                                            },
                                            "type": "object"
                                        },
                                        "xyz": {
                                        "type": "string",
                                            "default": "xyz default value",
                                            "example": "xyz example value"
                                        }
                                    },
                                    "type": "object"
                                }
                            }
                        }
                    }
                ],
                "responses": {
                "200": {
                    "description": "Details of the customer"
                    },
                    "400": {
                    "description": "Email required"
                    },
                    "404": {
                    "description": "Customer does not exist"
                    },
                    "default": {
                    "description": "an \"unexpected\" error"
                    }
                }
            }
        },
        "/getCustomerById.php": {
        "get": {
            "summary": "List the details of customer by the ID",
                "parameters": [
                    {
                        "name": "id",
                        "in": "query",
                        "description": "Customer ID to get the data",
                        "required": true,
                        "type": "integer"
                    }
                ],
                "responses": {
                "200": {
                    "description": "Details of the customer"
                    },
                    "400": {
                    "description": "ID required"
                    },
                    "404": {
                    "description": "Customer does not exist"
                    },
                    "default": {
                    "description": "an \"unexpected\" error"
                    }
                }
            }
        },
        "/getShipmentById.php": {
        "get": {
            "summary": "List the details of shipment by the ID",
                "parameters": [
                    {
                        "name": "id",
                        "in": "query",
                        "description": "Shipment ID to get the data",
                        "required": true,
                        "type": "integer"
                    }
                ],
                "responses": {
                "200": {
                    "description": "Details of the shipment"
                    },
                    "404": {
                    "description": "Shipment does not exist"
                    },
                    "400": {
                    "description": "ID required"
                    },
                    "default": {
                    "description": "an \"unexpected\" error"
                    }
                }
            }
        }
    },
    "definitions": {

    }
}

This can be imported into Postman as follow.

  1. Click on the 'Import' button in the top left corner of Postman UI.
  2. You will see multiple options to import the API doc. Click on the 'Paste Raw Text'.
  3. Paste the JSON format in the text area and click import.
  4. You will see all your APIs as 'Postman Collection' and can use it from the Postman.

Importing the JSON into Postman

Imported APIs

You can also use 'Import From Link'. Here paste the URL which generates the JSON format of the APIs from the Swagger or any other API Document tool.

This is my Document (JSON) generation file. It's in PHP. I have no idea of JAVA along with Swagger.

<?php
require("vendor/autoload.php");
$swagger = \Swagger\scan('path_of_the_directory_to_scan');
header('Content-Type: application/json');
echo $swagger;

How to catch all exceptions in c# using try and catch?

try
{

..
..
..

}

catch(Exception ex)
{

..
..
..

}

the Exception ex means all the exceptions.

How do I hide the status bar in a Swift iOS app?

A solution that works for me; if you want to hide the status bar on a specific view controller while loading:

import UIKit

class ViewController: UIViewController {

private var hideStatusBar: Bool = false

override var prefersStatusBarHidden: Bool {
    return hideStatusBar
}

override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
    return UIStatusBarAnimation.slide
}

override func viewDidLoad() {
    super.viewDidLoad()

    view.backgroundcolor = .white
    hideStatusBar = true

    UIView.animate(withDuration: 0.3) {
        self.setNeedsStatusBarAppearanceUpdate()
    }
}

Attention: if you set the key "View controller-based status bar appearance" to "NO" in your info.plist the code above doesn't work. You should set the key to "YES" or remove it from info.plist

How to copy a huge table data into another table in SQL Server

Simple Insert/Select sp's work great until the row count exceeds 1 mil. I've watched tempdb file explode trying to insert/select 20 mil + rows. The simplest solution is SSIS setting the batch row size buffer to 5000 and commit size buffer to 1000.

Update just one gem with bundler

The way to do this is to run the following command:

bundle update --source gem-name

What's the best visual merge tool for Git?

If you are just looking for a diff tool beyond compare is pretty nice: http://www.scootersoftware.com/moreinfo.php

How to export specific request to file using postman?

The workaround is to export the collection as explained in other answers or references. This will export all requests in that collection to JSON file.

Then edit the JSON file to remove the requests you do not want using any editor; this is very simple.

Look for "item" collection in file. This contains all your requests; one in each item. Remove the items you do not want to keep.

If you import this edited file in Postman where original collection already exists, Postman will ask you if you want to replace it or create a copy. If you want to avoid this, you may consider changing "_postman_id" and "name" under "info". If original collection will not exist while importing edited collection, then this change is not needed.

Screenshot

Show Hide div if, if statement is true

This does not need jquery, you could set a variable inside the if and use it in html or pass it thru your template system if any

<?php
$showDivFlag=false
$query3 = mysql_query($query3);
$numrows = mysql_num_rows($query3);
if ($numrows > 0){
    $fvisit = mysql_fetch_array($result3);
    $showDivFlag=true;
 }else {

 }

?>

later in html

  <div id="results" <?php if ($showDivFlag===false){?>style="display:none"<?php } ?>>

ImportError: No module named mysql.connector using Python2

use the command below

python -m pip install mysql-connector 

How to enumerate an enum with String type?

This is a pretty old post, from Swift 2.0. There are now some better solutions here that use newer features of swift 3.0: Iterating through an Enum in Swift 3.0

And on this question there is a solution that uses a new feature of (the not-yet-released as I write this edit) Swift 4.2: How do I get the count of a Swift enum?


There are lots of good solutions in this thread and others however some of them are very complicated. I like to simplify as much as possible. Here is a solution which may or may not work for different needs but I think it works well in most cases:

enum Number: String {
    case One
    case Two
    case Three
    case Four
    case EndIndex

    func nextCase () -> Number
    {
        switch self {
        case .One:
            return .Two
        case .Two:
            return .Three
        case .Three:
            return .Four
        case .Four:
            return .EndIndex

        /* 
        Add all additional cases above
        */
        case .EndIndex:
            return .EndIndex
        }
    }

    static var allValues: [String] {
        var array: [String] = Array()
        var number = Number.One

        while number != Number.EndIndex {
            array.append(number.rawValue)
            number = number.nextCase()
        }
        return array
    }
}

To iterate:

for item in Number.allValues {
    print("number is: \(item)")
}

TortoiseSVN icons not showing up under Windows 7

If you want to use Tortoise from within a 32 bit Application on Windows 7 64 bit, you need to install both the 64bit and the 32bit versions of Tortoise. According to Tortoise's makers, this works fine. (source)

How to run code after some delay in Flutter?

Figured it out

class AnimatedFlutterLogo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new _AnimatedFlutterLogoState();
}

class _AnimatedFlutterLogoState extends State<AnimatedFlutterLogo> {
  Timer _timer;
  FlutterLogoStyle _logoStyle = FlutterLogoStyle.markOnly;

  _AnimatedFlutterLogoState() {
    _timer = new Timer(const Duration(milliseconds: 400), () {
      setState(() {
        _logoStyle = FlutterLogoStyle.horizontal;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    _timer.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return new FlutterLogo(
      size: 200.0,
      textColor: Palette.white,
      style: _logoStyle,
    );
  }
}

Javascript ES6 export const vs export let

In ES6, imports are live read-only views on exported-values. As a result, when you do import a from "somemodule";, you cannot assign to a no matter how you declare a in the module.

However, since imported variables are live views, they do change according to the "raw" exported variable in exports. Consider the following code (borrowed from the reference article below):

//------ lib.js ------
export let counter = 3;
export function incCounter() {
    counter++;
}

//------ main1.js ------
import { counter, incCounter } from './lib';

// The imported value `counter` is live
console.log(counter); // 3
incCounter();
console.log(counter); // 4

// The imported value can’t be changed
counter++; // TypeError

As you can see, the difference really lies in lib.js, not main1.js.


To summarize:

  • You cannot assign to import-ed variables, no matter how you declare the corresponding variables in the module.
  • The traditional let-vs-const semantics applies to the declared variable in the module.
    • If the variable is declared const, it cannot be reassigned or rebound in anywhere.
    • If the variable is declared let, it can only be reassigned in the module (but not the user). If it is changed, the import-ed variable changes accordingly.

Reference: http://exploringjs.com/es6/ch_modules.html#leanpub-auto-in-es6-imports-are-live-read-only-views-on-exported-values

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

I could do this with a custom attribute as follows.

[AuthorizeUser(AccessLevel = "Create")]
public ActionResult CreateNewInvoice()
{
    //...
    return View();
}

Custom Attribute class as follows.

public class AuthorizeUserAttribute : AuthorizeAttribute
{
    // Custom property
    public string AccessLevel { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {                
            return false;
        }

        string privilegeLevels = string.Join("", GetUserRights(httpContext.User.Identity.Name.ToString())); // Call another method to get rights of the user from DB

        return privilegeLevels.Contains(this.AccessLevel);           
    }
}

You can redirect an unauthorised user in your custom AuthorisationAttribute by overriding the HandleUnauthorizedRequest method:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary(
                    new
                        { 
                            controller = "Error", 
                            action = "Unauthorised" 
                        })
                );
}

Git will not init/sync/update new submodules

Sort of magically, but today I ran git submodule init followed by git submodule sync followed by git submodule update and it started pulling my submodules... Magic? Perhaps! This is truly one of the most annoying experiences with Git…

Scratch that. I actually got it working by doing git submodule update --init --recursive. Hope this helps.

PS: Make sure you are in the root git directory, not the submodule's.

Raising a number to a power in Java

You should use below method-

Math.pow(double a, double b)

Returns the value of the first argument raised to the power of the second argument.

div inside table

It is allow as TD can contain inline- AND block-elements.

Here you can find it in the reference: http://xhtml.com/en/xhtml/reference/td/#td-contains

MySQL Select Date Equal to Today

Sounds like you need to add the formatting to the WHERE:

SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d') 
FROM users 
WHERE DATE_FORMAT(users.signup_date, '%Y-%m-%d') = CURDATE()

See SQL Fiddle with Demo

Angular 5 ngHide ngShow [hidden] not working

If you add [hidden]="true" to div, the actual thing that happens is adding a class [hidden] to this element conditionally with display: none

Please check the style of the element in the browser to ensure no other style affect the display property of an element like this:

enter image description here

If you found display of [hidden] class is overridden, you need to add this css code to your style:

[hidden] {
    display: none !important;
}

What's the difference between setWebViewClient vs. setWebChromeClient?

From the source code:

// Instance of WebViewClient that is the client callback.
private volatile WebViewClient mWebViewClient;
// Instance of WebChromeClient for handling all chrome functions.
private volatile WebChromeClient mWebChromeClient;

// SOME OTHER SUTFFF.......

/**
 * Set the WebViewClient.
 * @param client An implementation of WebViewClient.
 */
public void setWebViewClient(WebViewClient client) {
    mWebViewClient = client;
}

/**
 * Set the WebChromeClient.
 * @param client An implementation of WebChromeClient.
 */
public void setWebChromeClient(WebChromeClient client) {
    mWebChromeClient = client;
}

Using WebChromeClient allows you to handle Javascript dialogs, favicons, titles, and the progress. Take a look of this example: Adding alert() support to a WebView

At first glance, there are too many differences WebViewClient & WebChromeClient. But, basically: if you are developing a WebView that won't require too many features but rendering HTML, you can just use a WebViewClient. On the other hand, if you want to (for instance) load the favicon of the page you are rendering, you should use a WebChromeClient object and override the onReceivedIcon(WebView view, Bitmap icon).

Most of the times, if you don't want to worry about those things... you can just do this:

webView= (WebView) findViewById(R.id.webview); 
webView.setWebChromeClient(new WebChromeClient()); 
webView.setWebViewClient(new WebViewClient()); 
webView.getSettings().setJavaScriptEnabled(true); 
webView.loadUrl(url); 

And your WebView will (in theory) have all features implemented (as the android native browser).

Python : Trying to POST form using requests

Send a POST request with content type = 'form-data':

import requests
files = {
    'username': (None, 'myusername'),
    'password': (None, 'mypassword'),
}
response = requests.post('https://example.com/abc', files=files)

Java get String CompareTo as a comparator object

Regarding Nambari's answer there was a mistake. If you compare values using double equal sign == program will never reach compare method, unless someone will use new keyword to create String object which is not the best practice. This might be a bit better solution:

public int compare(String o1, String o2) {
        if (o1 == null && o2 == null){return 0;}
        if (o1 == null) { return -1;}
        if (o2 == null) { return 1;}
        return o1.compareTo(o2);
    }

P.S. Thanks for comments ;)

Limit Get-ChildItem recursion depth

I tried to limit Get-ChildItem recursion depth using Resolve-Path

$PATH = "."
$folder = get-item $PATH 
$FolderFullName = $Folder.FullName
$PATHs = Resolve-Path $FolderFullName\*\*\*\
$Folders = $PATHs | get-item | where {$_.PsIsContainer}

But this works fine :

gci "$PATH\*\*\*\*"

Direct download from Google Drive using Google Drive API

https://github.com/google/skicka

I used this command line tool to download files from Google Drive. Just follow the instructions in Getting Started section and you should download files from Google Drive in minutes.

hash keys / values as array

var a = {"apples": 3, "oranges": 4, "bananas": 42};    

var array_keys = new Array();
var array_values = new Array();

for (var key in a) {
    array_keys.push(key);
    array_values.push(a[key]);
}

alert(array_keys);
alert(array_values);

Send Outlook Email Via Python?

This was one I tried using Win32:

import win32com.client as win32
import psutil
import os
import subprocess
import sys

# Drafting and sending email notification to senders. You can add other senders' email in the list
def send_notification():


    outlook = win32.Dispatch('outlook.application')
    olFormatHTML = 2
    olFormatPlain = 1
    olFormatRichText = 3
    olFormatUnspecified = 0
    olMailItem = 0x0

    newMail = outlook.CreateItem(olMailItem)
    newMail.Subject = sys.argv[1]
    #newMail.Subject = "check"
    newMail.BodyFormat = olFormatHTML    #or olFormatRichText or olFormatPlain
    #newMail.HTMLBody = "test"
    newMail.HTMLBody = sys.argv[2]
    newMail.To = "[email protected]"
    attachment1 = sys.argv[3]
    attachment2 = sys.argv[4]
    newMail.Attachments.Add(attachment1)
    newMail.Attachments.Add(attachment2)

    newMail.display()
    # or just use this instead of .display() if you want to send immediately
    newMail.Send()





# Open Outlook.exe. Path may vary according to system config
# Please check the path to .exe file and update below
def open_outlook():
    try:
        subprocess.call(['C:\Program Files\Microsoft Office\Office15\Outlook.exe'])
        os.system("C:\Program Files\Microsoft Office\Office15\Outlook.exe");
    except:
        print("Outlook didn't open successfully")     
#

# Checking if outlook is already opened. If not, open Outlook.exe and send email
for item in psutil.pids():
    p = psutil.Process(item)
    if p.name() == "OUTLOOK.EXE":
        flag = 1
        break
    else:
        flag = 0

if (flag == 1):
    send_notification()
else:
    open_outlook()
    send_notification()

CSS hover vs. JavaScript mouseover

Use CSS, it makes for much easier management of the style itself.

How to force NSLocalizedString to use a specific language

Swift 3 solution:

let languages = ["bs", "zh-Hant", "en", "fi", "ko", "lv", "ms", "pl", "pt-BR", "ru", "sr-Latn", "sk", "es", "tr"]
UserDefaults.standard.set([languages[0]], forKey: "AppleLanguages")

Gave some examples of language codes that can be used. Hope this helps

Write variable to file, including name

The default string representation for a dictionary seems to be just right:

>>> a={3: 'foo', 17: 'bar' }
>>> a
{17: 'bar', 3: 'foo'}
>>> print a
{17: 'bar', 3: 'foo'}
>>> print "a=", a
a= {17: 'bar', 3: 'foo'}

Not sure if you can get at the "variable name", since variables in Python are just labels for values. See this question.

List all environment variables from the command line

To list all environment variables in PowerShell:

Get-ChildItem Env:

Or as suggested by user797717 to avoid output truncation:

Get-ChildItem Env: | Format-Table -Wrap -AutoSize

Source: Creating and Modifying Environment Variables (Windows PowerShell Tip of the Week)

How to do an array of hashmaps?

The Java Language Specification, section 15.10, states:

An array creation expression creates an object that is a new array whose elements are of the type specified by the PrimitiveType or ClassOrInterfaceType. It is a compile-time error if the ClassOrInterfaceType does not denote a reifiable type (§4.7).

and

The rules above imply that the element type in an array creation expression cannot be a parameterized type, other than an unbounded wildcard.

The closest you can do is use an unchecked cast, either from the raw type, as you have done, or from an unbounded wildcard:

 HashMap<String, String>[] responseArray = (Map<String, String>[]) new HashMap<?,?>[games.size()];

Your version is clearly better :-)

Pass array to mvc Action via AJAX

I have had issues in the past when attempting to perform a POST (not sure if that is exactly what you are doing, but I recall when passing an array in, traditional must be set to true.

 var arrayOfValues = new Array();

 //Populate arrayOfValues 
 $.ajax({ 
      type: "POST",
      url: "<%= Url.Action("MyAction","Controller")%>",
      traditional: true,
      data: { 'arrayOfValues': arrayOfValues }              
 });

Close virtual keyboard on button press

This solution works perfect for me:

private void showKeyboard(EditText editText) {
    editText.requestFocus();
    editText.setFocusableInTouchMode(true);
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(editText, InputMethodManager.RESULT_UNCHANGED_SHOWN);
    editText.setSelection(editText.getText().length());
}

private void closeKeyboard() {
    InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN);
}

Swift - Split string over multiple lines

Swift:

@connor is the right answer, but if you want to add lines in a print statement what you are looking for is \n and/or \r, these are called Escape Sequences or Escaped Characters, this is a link to Apple documentation on the topic..

Example:

print("First line\nSecond Line\rThirdLine...")

Change background of LinearLayout in Android

If you want to set through xml using android's default color codes, then you need to do as below:

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

If you have colors specified in your project's colors.xml, then use:

android:background="@color/white"

If you want to do programmatically, then do:

linearlayout.setBackgroundColor(Color.WHITE);

how to get files from <input type='file' .../> (Indirect) with javascript

If you are looking to style a file input element, look at open file dialog box in javascript. If you are looking to grab the files associated with a file input element, you must do something like this:

inputElement.onchange = function(event) {
   var fileList = inputElement.files;
   //TODO do something with fileList.  
}

See this MDN article for more info on the FileList type.

Note that the code above will only work in browsers that support the File API. For IE9 and earlier, for example, you only have access to the file name. The input element has no files property in non-File API browsers.

cURL not working (Error #77) for SSL connections on CentOS for non-root users

Please check the permissions on the the ca certificates installed on server.

Use find command but exclude files in two directories

Here's how you can specify that with find:

find . -type f -name "*_peaks.bed" ! -path "./tmp/*" ! -path "./scripts/*"

Explanation:

  • find . - Start find from current working directory (recursively by default)
  • -type f - Specify to find that you only want files in the results
  • -name "*_peaks.bed" - Look for files with the name ending in _peaks.bed
  • ! -path "./tmp/*" - Exclude all results whose path starts with ./tmp/
  • ! -path "./scripts/*" - Also exclude all results whose path starts with ./scripts/

Testing the Solution:

$ mkdir a b c d e
$ touch a/1 b/2 c/3 d/4 e/5 e/a e/b
$ find . -type f ! -path "./a/*" ! -path "./b/*"

./d/4
./c/3
./e/a
./e/b
./e/5

You were pretty close, the -name option only considers the basename, where as -path considers the entire path =)

Why does checking a variable against multiple values with `OR` only check the first value?

If you want case-insensitive comparison, use lower or upper:

if name.lower() == "jesse":

How to parse XML using shellscript?

I am surprised no one has mentioned xmlsh. The mission statement :

A command line shell for XML Based on the philosophy and design of the Unix Shells

xmlsh provides a familiar scripting environment, but specifically tailored for scripting xml processes.

A list of shell like commands are provided here.

I use the xed command a lot which is equivalent to sed for XML, and allows XPath based search and replaces.

How can I emulate a get request exactly like a web browser?

i'll make an example, first decide what browser you want to emulate, in this case i chose Firefox 60.6.1esr (64-bit), and check what GET request it issues, this can be obtained with a simple netcat server (MacOS bundles netcat, most linux distributions bunles netcat, and Windows users can get netcat from.. Cygwin.org , among other places),

setting up the netcat server to listen on port 9999: nc -l 9999

now hitting http://127.0.0.1:9999 in firefox, i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

now let us compare that with this simple script:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_exec($ch);

i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
Accept: */*

there are several missing headers here, they can all be added with the CURLOPT_HTTPHEADER option of curl_setopt, but the User-Agent specifically should be set with CURLOPT_USERAGENT instead (it will be persistent across multiple calls to curl_exec() and if you use CURLOPT_FOLLOWLOCATION then it will persist across http redirections as well), and the Accept-Encoding header should be set with CURLOPT_ENCODING instead (if they're set with CURLOPT_ENCODING then curl will automatically decompress the response if the server choose to compress it, but if you set it via CURLOPT_HTTPHEADER then you must manually detect and decompress the content yourself, which is a pain in the ass and completely unnecessary, generally speaking) so adding those we get:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

now running that code, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Upgrade-Insecure-Requests: 1

and voila! our php-emulated browser GET request should now be indistinguishable from the real firefox GET request :)

this next part is just nitpicking, but if you look very closely, you'll see that the headers are stacked in the wrong order, firefox put the Accept-Encoding header in line 6, and our emulated GET request puts it in line 3.. to fix this, we can manually put the Accept-Encoding header in the right line,

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Accept-Encoding: gzip, deflate',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

running that, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

problem solved, now the headers is even in the correct order, and the request seems to be COMPLETELY INDISTINGUISHABLE from the real firefox request :) (i don't actually recommend this last step, it's a maintenance burden to keep CURLOPT_ENCODING in sync with the custom Accept-Encoding header, and i've never experienced a situation where the order of the headers are significant)

Paging UICollectionView by cells, not screen

Approach 1: Collection View

flowLayout is UICollectionViewFlowLayout property

override func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

    if let collectionView = collectionView {

        targetContentOffset.memory = scrollView.contentOffset
        let pageWidth = CGRectGetWidth(scrollView.frame) + flowLayout.minimumInteritemSpacing

        var assistanceOffset : CGFloat = pageWidth / 3.0

        if velocity.x < 0 {
            assistanceOffset = -assistanceOffset
        }

        let assistedScrollPosition = (scrollView.contentOffset.x + assistanceOffset) / pageWidth

        var targetIndex = Int(round(assistedScrollPosition))


        if targetIndex < 0 {
            targetIndex = 0
        }
        else if targetIndex >= collectionView.numberOfItemsInSection(0) {
            targetIndex = collectionView.numberOfItemsInSection(0) - 1
        }

        print("targetIndex = \(targetIndex)")

        let indexPath = NSIndexPath(forItem: targetIndex, inSection: 0)

        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
    }
}

Approach 2: Page View Controller

You could use UIPageViewController if it meets your requirements, each page would have a separate view controller.

Collision resolution in Java HashMap

When you insert the pair (10, 17) and then (10, 20), there is technically no collision involved. You are just replacing the old value with the new value for a given key 10 (since in both cases, 10 is equal to 10 and also the hash code for 10 is always 10).

Collision happens when multiple keys hash to the same bucket. In that case, you need to make sure that you can distinguish between those keys. Chaining collision resolution is one of those techniques which is used for this.

As an example, let's suppose that two strings "abra ka dabra" and "wave my wand" yield hash codes 100 and 200 respectively. Assuming the total array size is 10, both of them end up in the same bucket (100 % 10 and 200 % 10). Chaining ensures that whenever you do map.get( "abra ka dabra" );, you end up with the correct value associated with the key. In the case of hash map in Java, this is done by using the equals method.

How do I keep Python print from adding newlines or spaces?

Greg is right-- you can use sys.stdout.write

Perhaps, though, you should consider refactoring your algorithm to accumulate a list of <whatevers> and then

lst = ['h', 'm']
print  "".join(lst)

Fixing Sublime Text 2 line endings?

The simplest way to modify all files of a project at once (batch) is through Line Endings Unify package:

  1. Ctrl+Shift+P type inst + choose Install Package.
  2. Type line end + choose Line Endings Unify.
  3. Once installed, Ctrl+Shift+P + type end + choose Line Endings Unify.
  4. OR (instead of 3.) copy:

    {
     "keys": ["ctrl+alt+l"],
     "command": "line_endings_unify"
    },
    

    to the User array (right pane, after the opening [) in Preferences -> KeyBindings + press Ctrl+Alt+L.

As mentioned in another answer:

  • The Carriage Return (CR) character (0x0D, \r) [...] Early Macintosh operating systems (OS-9 and earlier).

  • The Line Feed (LF) character (0x0A, \n) [...] UNIX based systems (Linux, Mac OSX)

  • The End of Line (EOL) sequence (0x0D 0x0A, \r\n) [...] (non-Unix: Windows, Symbian OS).

If you have node_modules, build or other auto-generated folders, delete them before running the package.

When you run the package:

  1. you are asked at the bottom to choose which file extensions to search through a comma separated list (type the only ones you need to speed up the replacements, e.g. js,jsx).
  2. then you are asked which Input line ending to use, e.g. if you need LF type \n.
  3. press ENTER and wait until you see an alert window with LineEndingsUnify Complete.

Function for C++ struct

Structs can have functions just like classes. The only difference is that they are public by default:

struct A {
    void f() {}
};

Additionally, structs can also have constructors and destructors.

struct A {
    A() : x(5) {}
    ~A() {}

    private: int x;
};

Can I avoid the native fullscreen video player with HTML5 on iPhone or android?

Old answer (applicable till 2016)

Here's an Apple developer link that explicitly says that -

on iPhone and iPod touch, which are small screen devices, "Video is NOT presented within the Web Page"

Safari Device-Specific Considerations

Your options:

  • The webkit-playsinline attribute works for HTML5 videos on iOS but only when you save the webpage to your home screen as a webapp - Not if opened a page in Safari
  • For a native app with a WebView (or a hybrid app with HTML, CSS, JS) the UIWebView allows to play the video inline, but only if you set the allowsInlineMediaPlayback property for the UIWebView class to true

How to include Authorization header in cURL POST HTTP Request in PHP?

use "Content-type: application/x-www-form-urlencoded" instead of "application/json"

Swift extract regex matches

@p4bloch if you want to capture results from a series of capture parentheses, then you need to use the rangeAtIndex(index) method of NSTextCheckingResult, instead of range. Here's @MartinR 's method for Swift2 from above, adapted for capture parentheses. In the array that is returned, the first result [0] is the entire capture, and then individual capture groups begin from [1]. I commented out the map operation (so it's easier to see what I changed) and replaced it with nested loops.

func matches(for regex: String!, in text: String!) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex, options: [])
        let nsString = text as NSString
        let results = regex.matchesInString(text, options: [], range: NSMakeRange(0, nsString.length))
        var match = [String]()
        for result in results {
            for i in 0..<result.numberOfRanges {
                match.append(nsString.substringWithRange( result.rangeAtIndex(i) ))
            }
        }
        return match
        //return results.map { nsString.substringWithRange( $0.range )} //rangeAtIndex(0)
    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

An example use case might be, say you want to split a string of title year eg "Finding Dory 2016" you could do this:

print ( matches(for: "^(.+)\\s(\\d{4})" , in: "Finding Dory 2016"))
// ["Finding Dory 2016", "Finding Dory", "2016"]

How to schedule a stored procedure in MySQL

In order to create a cronjob, follow these steps:

  1. run this command : SET GLOBAL event_scheduler = ON;

  2. If ERROR 1229 (HY000): Variable 'event_scheduler' is a GLOBAL variable and should be set with SET GLOBAL: mportant

It is possible to set the Event Scheduler to DISABLED only at server startup. If event_scheduler is ON or OFF, you cannot set it to DISABLED at runtime. Also, if the Event Scheduler is set to DISABLED at startup, you cannot change the value of event_scheduler at runtime.

To disable the event scheduler, use one of the following two methods:

  1. As a command-line option when starting the server:

    --event-scheduler=DISABLED
    
  2. In the server configuration file (my.cnf, or my.ini on Windows systems): include the line where it will be read by the server (for example, in a [mysqld] section):

    event_scheduler=DISABLED
    

    Read MySQL documentation for more information.

     DROP EVENT IF EXISTS EVENT_NAME;
      CREATE EVENT EVENT_NAME
     ON SCHEDULE EVERY 10 SECOND/minute/hour
     DO
     CALL PROCEDURE_NAME();
    

Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener

It happen if there are two more ContextLoaderListener exist in your project.

For ex: in my case 2 ContextLoaderListener was exist using

  1. java configuration
  2. web.xml

So, remove any one ContextLoaderListener from your project and run your application.

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

Please find the actual css from Bootstrap

.container-fluid {
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
}
.row {
  margin-right: -15px;
  margin-left: -15px;
}

When you add a .container-fluid class, it adds a horizontal padding of 15px, and the same will be removed when you add a .row class as a child element by the negative margin set on row.

Find files and tar them (with spaces)

Would add a comment to @Steve Kehlet post but need 50 rep (RIP).

For anyone that has found this post through numerous googling, I found a way to not only find specific files given a time range, but also NOT include the relative paths OR whitespaces that would cause tarring errors. (THANK YOU SO MUCH STEVE.)

find . -name "*.pdf" -type f -mtime 0 -printf "%f\0" | tar -czvf /dir/zip.tar.gz --null -T -
  1. . relative directory

  2. -name "*.pdf" look for pdfs (or any file type)

  3. -type f type to look for is a file

  4. -mtime 0 look for files created in last 24 hours

  5. -printf "%f\0" Regular -print0 OR -printf "%f" did NOT work for me. From man pages:

This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use '\0' as a terminator than to use newline, as file names can contain white space and newline characters.

  1. -czvf create archive, filter the archive through gzip , verbosely list files processed, archive name

Edit 2019-08-14: I would like to add, that I was also able to use essentially use the same command in my comment, just using tar itself:

tar -czvf /archiveDir/test.tar.gz --newer-mtime=0 --ignore-failed-read *.pdf

Needed --ignore-failed-read in-case there were no new PDFs for today.

Filtering array of objects with lodash based on property value

**Filter by name, age ** also, you can use the map function

difference between map and filter

1. map - The map() method creates a new array with the results of calling a function for every array element. The map method allows items in an array to be manipulated to the user’s preference, returning the conclusion of the chosen manipulation in an entirely new array. For example, consider the following array:

2. filter - The filter() method creates an array filled with all array elements that pass a test implemented by the provided function. The filter method is well suited for particular instances where the user must identify certain items in an array that share a common characteristic. For example, consider the following array:

const users = [
    { name: "john", age: 23 },
    { name: "john", age:43 },
    { name: "jim", age: 101 },
    { name: "bob", age: 67 }
];

const user = _.filter(users, {name: 'jim', age: 101});
console.log(user);

html select option SELECTED

foreach($array as $value=>$name)
{
    if($value == $_GET['sel'])
    {
         echo "<option selected='selected' value='".$value."'>".$name."</option>";
    }
    else
    {
         echo "<option value='".$value."'>".$name."</option>";
    }
}

jQuery Set Select Index

you can set selectoption variable value dynamically as well as option will be selected.You can try following code

code:

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>

      $(function(){
            $('#allcheck').click(function(){
             // $('#select_option').val([1,2,5]);also can use multi selectbox
              // $('#select_option').val(1);
               var selectoption=3;
           $("#selectBox>option[value="+selectoption+"]").attr('selected', 'selected');
    });

});

HTML CODE:

   <select id="selectBox">
       <option value="0">Number 0</option>
       <option value="1">Number 1</option>
       <option value="2">Number 2</option>
       <option value="3">Number 3</option>
       <option value="4">Number 4</option>
       <option value="5">Number 5</option>
       <option value="6">Number 6</option>
       <option value="7">Number 7</option>
 </select> <br>
<strong>Select&nbsp;&nbsp; <a style="cursor:pointer;" id="allcheck">click for select option</a></strong>

$apply already in progress error

In my case i use $apply with angular calendar UI to link some event:

$scope.eventClick = function(event){           
    $scope.$apply( function() {
        $location.path('/event/' + event.id);
    });
};

After reading the doc of the problem: https://docs.angularjs.org/error/$rootScope/inprog

The part Inconsistent API (Sync/Async) is very interesting:

For example, imagine a 3rd party library that has a method which will retrieve data for us. Since it may be making an asynchronous call to a server, it accepts a callback function, which will be called when the data arrives.

Since, the MyController constructor is always instantiated from within an $apply call, our handler is trying to enter a new $apply block from within one.

I change the code to :

$scope.eventClick = function(event){           
    $timeout(function() {
        $location.path('/event/' + event.id);
    }, 0);
};

Works like a charm !

Here we have used $timeout to schedule the changes to the scope in a future call stack. By providing a timeout period of 0ms, this will occur as soon as possible and $timeout will ensure that the code will be called in a single $apply block.

Add new column in Pandas DataFrame Python

The easiest way that I found for adding a column to a DataFrame was to use the "add" function. Here's a snippet of code, also with the output to a CSV file. Note that including the "columns" argument allows you to set the name of the column (which happens to be the same as the name of the np.array that I used as the source of the data).

#  now to create a PANDAS data frame
df = pd.DataFrame(data = FF_maxRSSBasal, columns=['FF_maxRSSBasal'])
# from here on, we use the trick of creating a new dataframe and then "add"ing it
df2 = pd.DataFrame(data = FF_maxRSSPrism, columns=['FF_maxRSSPrism'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = FF_maxRSSPyramidal, columns=['FF_maxRSSPyramidal'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_strainE22, columns=['deltaFF_strainE22'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = scaled, columns=['scaled'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_orientation, columns=['deltaFF_orientation'])
df = df.add( df2, fill_value=0 )
#print(df)
df.to_csv('FF_data_frame.csv')

How to get a cross-origin resource sharing (CORS) post request working

This is a little late to the party, but I have been struggling with this for a couple of days. It is possible and none of the answers I found here have worked. It's deceptively simple. Here's the .ajax call:

_x000D_
_x000D_
    <!DOCTYPE HTML>_x000D_
    <html>_x000D_
    <head>_x000D_
    <body>_x000D_
     <title>Javascript Test</title>_x000D_
     <script src="http://code.jquery.com/jquery-latest.min.js"></script>_x000D_
     <script type="text/javascript">_x000D_
     $(document).domain = 'XXX.com';_x000D_
     $(document).ready(function () {_x000D_
     $.ajax({_x000D_
        xhrFields: {cors: false},_x000D_
        type: "GET",_x000D_
        url: "http://XXXX.com/test.php?email='[email protected]'",_x000D_
        success: function (data) {_x000D_
           alert(data);_x000D_
        },_x000D_
        error: function (x, y, z) {_x000D_
           alert(x.responseText + " :EEE: " + x.status);_x000D_
        }_x000D_
    });_x000D_
    });_x000D_
    </script> _x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Here's the php on the server side:

_x000D_
_x000D_
    <html>_x000D_
    <head>_x000D_
     <title>PHP Test</title>_x000D_
     </head>_x000D_
    <body>_x000D_
      <?php_x000D_
      header('Origin: xxx.com');_x000D_
      header('Access-Control-Allow-Origin:*');_x000D_
      $servername = "sqlxxx";_x000D_
      $username = "xxxx";_x000D_
      $password = "sss";_x000D_
      $conn = new mysqli($servername, $username, $password);_x000D_
      if ($conn->connect_error) {_x000D_
        die( "Connection failed: " . $conn->connect_error);_x000D_
      }_x000D_
      $sql = "SELECT email, status, userdata  FROM msi.usersLive";_x000D_
      $result = $conn->query($sql);_x000D_
      if ($result->num_rows > 0) {_x000D_
      while($row = $result->fetch_assoc()) {_x000D_
        echo $row["email"] . ":" . $row["status"] . ":" . $row["userdata"] .  "<br>";_x000D_
      }_x000D_
    } else {_x000D_
      echo "{ }";_x000D_
    }_x000D_
    $conn->close();_x000D_
    ?>_x000D_
    </body>
_x000D_
_x000D_
_x000D_

How do I pass a datetime value as a URI parameter in asp.net mvc?

You should first add a new route in global.asax:


routes.MapRoute(
                "MyNewRoute",
                "{controller}/{action}/{date}",
                new { controller="YourControllerName", action="YourActionName", date = "" }
            );

The on your Controller:



        public ActionResult MyActionName(DateTime date)
        {

        }

Remember to keep your default route at the bottom of the RegisterRoutes method. Be advised that the engine will try to cast whatever value you send in {date} as a DateTime example, so if it can't be casted then an exception will be thrown. If your date string contains spaces or : you could HTML.Encode them so the URL could be parsed correctly. If no, then you could have another DateTime representation.

Sending JSON object to Web API

Change:

 data: JSON.stringify({ model: source })

To:

 data: {model: JSON.stringify(source)}

And in your controller you do this:

public void PartSourceAPI(string model)
{
       System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

   var result = js.Deserialize<PartSourceModel>(model);
}

If the url you use in jquery is /api/PartSourceAPI then the controller name must be api and the action(method) should be PartSourceAPI

MySQL: Enable LOAD DATA LOCAL INFILE

I am using xampp v3.2.4 and mysql server 8.0.20.

I added local-infile=1 to [mysql] and [mysqld] in the file "my.ini". The file is located at "C:\xampp\mysql\bin\my.ini".

Then I inserted the data from csv file using the following code LOAD DATA INFILE .... It is important to move LOCAL. Otherwise it won't work.

Thanks for all suggestions above. A combination finally worked out for me.

How to export SQL Server 2005 query to CSV

You can use following Node.js module to do it with a breeze:

https://www.npmjs.com/package/mssql-to-csv

A select query selecting a select statement

Not sure if Access supports it, but in most engines (including SQL Server) this is called a correlated subquery and works fine:

SELECT  TypesAndBread.Type, TypesAndBread.TBName,
        (
        SELECT  Count(Sandwiches.[SandwichID]) As SandwichCount
        FROM    Sandwiches
        WHERE   (Type = 'Sandwich Type' AND Sandwiches.Type = TypesAndBread.TBName)
                OR (Type = 'Bread' AND Sandwiches.Bread = TypesAndBread.TBName)
        ) As SandwichCount
FROM    TypesAndBread

This can be made more efficient by indexing Type and Bread and distributing the subqueries over the UNION:

SELECT  [Sandwiches Types].[Sandwich Type] As TBName, "Sandwich Type" As Type,
        (
        SELECT  COUNT(*) As SandwichCount
        FROM    Sandwiches
        WHERE   Sandwiches.Type = [Sandwiches Types].[Sandwich Type]
        )
FROM    [Sandwiches Types]
UNION ALL
SELECT  [Breads].[Bread] As TBName, "Bread" As Type,
        (
        SELECT  COUNT(*) As SandwichCount
        FROM    Sandwiches
        WHERE   Sandwiches.Bread = [Breads].[Bread]
        )
FROM    [Breads]

How does DISTINCT work when using JPA and Hibernate

I would use JPA's constructor expression feature. See also following answer:

JPQL Constructor Expression - org.hibernate.hql.ast.QuerySyntaxException:Table is not mapped

Following the example in the question, it would be something like this.

SELECT DISTINCT new com.mypackage.MyNameType(c.name) from Customer c

How to call codeigniter controller function from view

Codeigniter is an MVC (Model - View - Controller) framework. It's really not a good idea to call a function from the view. The view should be used just for presentation, and all your logic should be happening before you get to the view in the controllers and models.

A good start for clarifying the best practice is to follow this tutorial:

https://codeigniter.com/user_guide/tutorial/index.html

It's simple, but it really lays out an excellent how-to.

I hope this helps!

How do I programmatically set device orientation in iOS 7?

NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft]; [[UIDevice currentDevice] setValue:value forKey:@"orientation"];

does work but you have to return shouldAutorotate with YES in your view controller

- (BOOL)shouldAutorotate
{
    return self.shouldAutoRotate;
}

But if you do that, your VC will autorotate if the user rotates the device... so I changed it to:

@property (nonatomic, assign) BOOL shouldAutoRotate;

- (BOOL)shouldAutorotate
{
    return self.shouldAutoRotate;
}

and I call

- (void)swithInterfaceOrientation:(UIInterfaceOrientation)orientation
{
    self.rootVC.shouldAutoRotate = YES;

    NSNumber *value = [NSNumber numberWithInt: orientation];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
}

to force a new orientation with a button-click. To set back shouldAutoRotate to NO, I added to my rootVC

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    self.shouldAutoRotate = NO;
}

PS: This workaround does work in all simulators too.

How do you check if a certain index exists in a table?

For SQL 2008 and newer, a more concise method, coding-wise, to detect index existence is by using the INDEXPROPERTY built-in function:

INDEXPROPERTY ( object_ID , index_or_statistics_name , property )  

The simplest usage is with the IndexID property:

If IndexProperty(Object_Id('MyTable'), 'MyIndex', 'IndexID') Is Null

If the index exists, the above will return its ID; if it doesn't, it will return NULL.

Virtual network interface in Mac OS X

What do you mean by

"but it will not act as a real fully functional interface (if the original interface is inactive, then the derived one is also inactive"

?

I can make a new interface, base it on an already existing one, then disable the existing one and the new one still works. Making a second interface does however not create a real interface (when you check with ifconfig), it will just assign a second IP to the already existing one (however, this one can be DHCP while the first one is hard coded for example).

So did I understand you right, that you want to create an interface, not bound to any real interface? How would this interface then be used? E.g. if you disconnect all WLAN and pull all network cables, where would this interface send traffic to, if you send traffic to it? Maybe your question is a bit unclear, it might help a lot if rephrase it, so it's clear what you are actually trying to do with this "virtual interface" once you have it.

As you mentioned "alias IP" in your question, this would mean an alias interface. But an alias interface is always bound to a real interface. The difference is in Linux such an interface really IS an interface (e.g. an alias interface for eth0 could be eth1), while on Mac, no real interface is created, instead a virtual interface is created, that can configured and used independently, but it is still the same interface physically and thus no new named interface is generated (you just have two interfaces, that are both in fact en0, but both can be enabled/disabled and configured independently).

How do I scroll a row of a table into view (element.scrollintoView) using jQuery?

Same from above with little modification

_x000D_
_x000D_
function focusMe() {_x000D_
       var rowpos = $('#FocusME').position();_x000D_
        rowpos.top = rowpos.top - 30;_x000D_
        $('#container').scrollTop(rowpos.top);_x000D_
    }
_x000D_
<html>_x000D_
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>_x000D_
<body>_x000D_
    <input type="button" onclick="focusMe()" value="focus">_x000D_
    <div id="container" style="max-height:200px;overflow:scroll;">_x000D_
        <table>_x000D_
            <tr>_x000D_
                <td>1</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>2</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>3</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>4</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>5</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>6</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>7</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>8</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>9</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr id="FocusME">_x000D_
                <td>10</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>11</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>12</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>13</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>14</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>15</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>16</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>17</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>18</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>19</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>20</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
        </table>_x000D_
    </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Find if variable is divisible by 2

Use Modulus, but.. The above accepted answer is slightly inaccurate. I believe because x is a Number type in JavaScript that the operator should be a double assignment instead of a triple assignment, like so:

x % 2 == 0

Remember to declare your variables too, so obviously that line couldn't be written standalone. :-) Usually used as an if statement. Hope this helps.

How can I make window.showmodaldialog work in chrome 37?

The window.showModalDialog is deprecated (Intent to Remove: window.showModalDialog(), Removing showModalDialog from the Web platform). [...]The latest plan is to land the showModalDialog removal in Chromium 37. This means the feature will be gone in Opera 24 and Chrome 37, both of which should be released in September.[...]

How do I represent a time only value in .NET?

As others have said, you can use a DateTime and ignore the date, or use a TimeSpan. Personally I'm not keen on either of these solutions, as neither type really reflects the concept you're trying to represent - I regard the date/time types in .NET as somewhat on the sparse side which is one of the reasons I started Noda Time. In Noda Time, you can use the LocalTime type to represent a time of day.

One thing to consider: the time of day is not necessarily the length of time since midnight on the same day...

(As another aside, if you're also wanting to represent a closing time of a shop, you may find that you want to represent 24:00, i.e. the time at the end of the day. Most date/time APIs - including Noda Time - don't allow that to be represented as a time-of-day value.)

What is the maximum value for an int32?

With Groovy on the path:

groovy -e " println Integer.MAX_VALUE "

(Groovy is extremely useful for quick reference, within a Java context.)

Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java

the difference of the numbers put in system.exit() is explained in other answers. but the REAL DIFFERENCE is that System.exit() is a code that gets returned to the invoking process. If the program is being invoked by the Operating system then the return code will tell the OS that if system.exit() returned 0 than everything was ok but if not something went wrong, then there could be some handlers for that in the parent process

Remove element of a regular array

First step
You need to convert the array into a list, you could write an extension method like this

// Convert An array of string  to a list of string
public static List<string> ConnvertArrayToList(this string [] array) {

    // DECLARE a list of string and add all element of the array into it

    List<string> myList = new List<string>();
    foreach( string s in array){
        myList.Add(s);
    }
    return myList;
} 

Second step
Write an extension method to convert back the list into an array

// convert a list of string to an array 
public static string[] ConvertListToArray(this List<string> list) {

    string[] array = new string[list.Capacity];
    array = list.Select(i => i.ToString()).ToArray();
    return array;
}

Last steps
Write your final method, but remember to remove the element at index before converting back to an array like the code show

public static string[] removeAt(string[] array, int index) {

    List<string> myList = array.ConnvertArrayToList();
    myList.RemoveAt(index);
    return myList.ConvertListToArray();
} 

examples codes could be find on my blog, keep tracking.

Syntax error "syntax error, unexpected end-of-input, expecting keyword_end (SyntaxError)"

Just posting in case it help someone else. The cause of this error for me was a missing do after creating a form with form_with. Hope that may help someone else

calling parent class method from child class object in java

NOTE calling parent method via super will only work on parent class, If your parent is interface, and wants to call the default methods then need to add interfaceName before super like IfscName.super.method();

interface Vehicle {
    //Non abstract method
    public default void printVehicleTypeName() { //default keyword can be used only in interface.
        System.out.println("Vehicle");
    }
}


class FordFigo extends FordImpl implements Vehicle, Ford {
    @Override
    public void printVehicleTypeName() { 
        System.out.println("Figo");
        Vehicle.super.printVehicleTypeName();
    }
}

Interface name is needed because same default methods can be available in multiple interface name that this class extends. So explicit call to a method is required.

relative path in BAT script

I have found that %CD% gives the path the script was called from and not the path of the script, however, %~dp0 will give the path of the script itself.

How do I prompt a user for confirmation in bash script?

Try the read shell builtin:

read -p "Continue (y/n)?" CONT
if [ "$CONT" = "y" ]; then
  echo "yaaa";
else
  echo "booo";
fi

How can I remove an element from a list?

if you'd like to avoid numeric indices, you can use

a <- setdiff(names(a),c("name1", ..., "namen"))

to delete names namea...namen from a. this works for lists

> l <- list(a=1,b=2)
> l[setdiff(names(l),"a")]
$b
[1] 2

as well as for vectors

> v <- c(a=1,b=2)
> v[setdiff(names(v),"a")]
b 
2

Java code To convert byte to Hexadecimal

The fastest way i've yet found to do this is the following:

private static final String    HEXES    = "0123456789ABCDEF";

static String getHex(byte[] raw) {
    final StringBuilder hex = new StringBuilder(2 * raw.length);
    for (final byte b : raw) {
        hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F)));
    }
    return hex.toString();
}

It's ~ 50x faster than String.format. if you want to test it:

public class MyTest{
    private static final String    HEXES        = "0123456789ABCDEF";

    @Test
    public void test_get_hex() {
        byte[] raw = {
            (byte) 0xd0, (byte) 0x0b, (byte) 0x01, (byte) 0x2a, (byte) 0x63,
            (byte) 0x78, (byte) 0x01, (byte) 0x2e, (byte) 0xe3, (byte) 0x6c,
            (byte) 0xd2, (byte) 0xb0, (byte) 0x78, (byte) 0x51, (byte) 0x73,
            (byte) 0x34, (byte) 0xaf, (byte) 0xbb, (byte) 0xa0, (byte) 0x9f,
            (byte) 0xc3, (byte) 0xa9, (byte) 0x00, (byte) 0x1e, (byte) 0xd5,
            (byte) 0x4b, (byte) 0x89, (byte) 0xa3, (byte) 0x45, (byte) 0x35,
            (byte) 0xd6, (byte) 0x10,
        };

        int N = 77777;
        long t;

        {
            t = System.currentTimeMillis();
            for (int i = 0; i < N; i++) {
                final StringBuilder hex = new StringBuilder(2 * raw.length);
                for (final byte b : raw) {
                    hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F)));
                }
                hex.toString();
            }
            System.out.println(System.currentTimeMillis() - t); // 50
        }

        {
            t = System.currentTimeMillis();
            for (int i = 0; i < N; i++) {
                StringBuilder hex = new StringBuilder(2 * raw.length);
                for (byte b : raw) {
                    hex.append(String.format("%02X", b));
                }
                hex.toString();
            }
            System.out.println(System.currentTimeMillis() - t); // 2535
        }

    }
}

Edit: Just found something just a lil faster and that holds on one line but is not compatible with JRE 9. Use at your own risks

import javax.xml.bind.DatatypeConverter;

DatatypeConverter.printHexBinary(raw);

How to get the full URL of a Drupal page?

drupal_get_destination() has some internal code that points at the correct place to getthe current internal path. To translate that path into an absolute URL, the url() function should do the trick. If the 'absolute' option is passed in it will generate the full URL, not just the internal path. It will also swap in any path aliases for the current path as well.

$path = isset($_GET['q']) ? $_GET['q'] : '<front>';
$link = url($path, array('absolute' => TRUE));

What is "android:allowBackup"?

Here is what backup in this sense really means:

Android's backup service allows you to copy your persistent application data to remote "cloud" storage, in order to provide a restore point for the application data and settings. If a user performs a factory reset or converts to a new Android-powered device, the system automatically restores your backup data when the application is re-installed. This way, your users don't need to reproduce their previous data or application settings.

~Taken from http://developer.android.com/guide/topics/data/backup.html

You can register for this backup service as a developer here: https://developer.android.com/google/backup/signup.html

The type of data that can be backed up are files, databases, sharedPreferences, cache, and lib. These are generally stored in your device's /data/data/[com.myapp] directory, which is read-protected and cannot be accessed unless you have root privileges.

UPDATE: You can see this flag listed on BackupManager's api doc: BackupManager

How to save public key from a certificate in .pem format

There are a couple ways to do this.

First, instead of going into openssl command prompt mode, just enter everything on one command line from the Windows prompt:

E:\> openssl x509 -pubkey -noout -in cert.pem  > pubkey.pem

If for some reason, you have to use the openssl command prompt, just enter everything up to the ">". Then OpenSSL will print out the public key info to the screen. You can then copy this and paste it into a file called pubkey.pem.

openssl> x509 -pubkey -noout -in cert.pem

Output will look something like this:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAryQICCl6NZ5gDKrnSztO
3Hy8PEUcuyvg/ikC+VcIo2SFFSf18a3IMYldIugqqqZCs4/4uVW3sbdLs/6PfgdX
7O9D22ZiFWHPYA2k2N744MNiCD1UE+tJyllUhSblK48bn+v1oZHCM0nYQ2NqUkvS
j+hwUU3RiWl7x3D2s9wSdNt7XUtW05a/FXehsPSiJfKvHJJnGOX0BgTvkLnkAOTd
OrUZ/wK69Dzu4IvrN4vs9Nes8vbwPa/ddZEzGR0cQMt0JBkhk9kU/qwqUseP1QRJ
5I1jR4g8aYPL/ke9K35PxZWuDp3U0UPAZ3PjFAh+5T+fc7gzCs9dPzSHloruU+gl
FQIDAQAB
-----END PUBLIC KEY-----

How do I use a 32-bit ODBC driver on 64-bit Server 2008 when the installer doesn't create a standard DSN?

Open IIS manager, select Application Pools, select the application pool you are using, click on Advanced Settings in the right-hand menu. Under General, set "Enable 32-Bit Applications" to "True".

How to get the previous page URL using JavaScript?

You can use the following to get the previous URL.

var oldURL = document.referrer;
alert(oldURL);

Errno 13 Permission denied Python

For future searchers, if none of the above worked, for me, python was trying to open a folder as a file.

How to Ignore "Duplicate Key" error in T-SQL (SQL Server)

If by "Ignore Duplicate Error statments", to abort the current statement and continue to the next statement without aborting the trnsaction then just put BEGIN TRY.. END TRY around each statement:

BEGIN TRY
    INSERT ...
END TRY
BEGIN CATCH /*required, but you dont have to do anything */ END CATCH
...

Jquery Setting Value of Input Field

$('.formData').attr('value','YOUR_VALUE')

Is it possible to write to the console in colour in .NET?

Yes, it's easy and possible. Define first default colors.

Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.White;
Console.Clear();

Console.Clear() it's important in order to set new console colors. If you don't make this step you can see combined colors when ask for values with Console.ReadLine().

Then you can change the colors on each print:

Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Red text over black.");

When finish your program, remember reset console colors on finish:

Console.ResetColor();
Console.Clear();

Now with netcore we have another problem if you want to "preserve" the User experience because terminal have different colors on each Operative System.

I'm making a library that solves this problem with Text Format: colors, alignment and lot more. Feel free to use and contribute.

https://github.com/deinsoftware/colorify/ and also available as NuGet package

Colors for Windows/Linux (Dark):
enter image description here

Colors for MacOS (Light):
enter image description here

SELECT INTO a table variable in T-SQL

Try something like this:

DECLARE @userData TABLE(
    name varchar(30) NOT NULL,
    oldlocation varchar(30) NOT NULL
);

INSERT INTO @userData (name, oldlocation)
SELECT name, location FROM myTable
INNER JOIN otherTable ON ...
WHERE age > 30;

How to write hello world in assembler under Windows?

If you want to use NASM and Visual Studio's linker (link.exe) with anderstornvig's Hello World example you will have to manually link with the C Runtime Libary that contains the printf() function.

nasm -fwin32 helloworld.asm
link.exe helloworld.obj libcmt.lib

Hope this helps someone.

How do I compare two files using Eclipse? Is there any option provided by Eclipse?

To compare two files in Eclipse, first select them in the Project Explorer / Package Explorer / Navigator with control-click. Now right-click on one of the files, and the following context menu will appear. Select Compare With / Each Other.

enter image description here

How to check if an int is a null

In Java there isn't Null values for primitive Data types. If you need to check Null use Integer Class instead of primitive type. You don't need to worry about data type difference. Java converts int primitive type data to Integer. When concerning about the memory Integer takes more memory than int. But the difference of memory allocation, nothing to be considered.

In this case you must use Inter instead of int

Try below snippet and see example for more info,

Integer id;
String name;

//Refer this example
    Integer val = 0;

`

if (val != null){
System.out.println("value is not null");
}

`

Also you can assign Null as below,

val = null;

How to copy folders to docker image from Dockerfile?

Suppose you want to copy the contents from a folder where you have docker file into your container. Use ADD:

RUN mkdir /temp
ADD folder /temp/Newfolder  

it will add to your container with temp/newfolder

folder is the folder/directory where you have the dockerfile, more concretely, where you put your content and want to copy that.

Now can you check your copied/added folder by runining container and see the content using ls

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

Note: You shouldn't use async: false due to this warning messages:

Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.

Chrome even warns about this in the console:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

This could break your page if you are doing something like this since it could stop working any day.

If you want to do it a way that still feels like if it's synchronous but still don't block then you should use async/await and probably also some ajax that is based on promises like the new Fetch API

async function foo() {
  var res = await fetch(url)
  console.log(res.ok)
  var json = await res.json()
  console.log(json)
}

Edit chrome is working on Disallowing sync XHR in page dismissal when the page is being navigated away or closed by the user. This involves beforeunload, unload, pagehide and visibilitychange.

if this is your use case then you might want to have a look at navigator.sendBeacon instead

It is also possible for the page to disable sync req with either http headers or iframe's allow attribute

Bootstrap 3 Glyphicons CDN

With the recent release of bootstrap 3, and the glyphicons being merged back to the main Bootstrap repo, Bootstrap CDN is now serving the complete Bootstrap 3.0 css including Glyphicons. The Bootstrap css reference is all you need to include: Glyphicons and its dependencies are on relative paths on the CDN site and are referenced in bootstrap.min.css.

In html:

<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">

In css:

 @import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css");

Here is a working demo.

Note that you have to use .glyphicon classes instead of .icon:

Example:

<span class="glyphicon glyphicon-heart"></span>

Also note that you would still need to include bootstrap.min.js for usage of Bootstrap JavaScript components, see Bootstrap CDN for url.


If you want to use the Glyphicons separately, you can do that by directly referencing the Glyphicons css on Bootstrap CDN.

In html:

<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">

In css:

@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css");

Since the css file already includes all the needed Glyphicons dependencies (which are in a relative path on the Bootstrap CDN site), adding the css file is all there is to do to start using Glyphicons.

Here is a working demo of the Glyphicons without Bootstrap.

jQuery get content between <div> tags

This is probably what you need:

$('div').html();

demo

This says get the div and return all the contents inside it. See more here: http://api.jquery.com/html/

If you had many divs on the page and needed to target just one, you could set an id on the div and call it like so

$('#whatever').html();

where whatever is the id

EDIT

Now that you have clarified your question re this being a string, here is a way to do it with vanilla js:

var l = x.length;
var y = x.indexOf('<div>');
var s = x.slice(y,l);
alert(s);

Demo Here

  1. get the length of the string.
  2. find out where the first div occurs
  3. slice the content there.

Excel CSV. file with more than 1,048,576 rows of data

I was able to edit a large 17GB csv file in Sublime Text without issue (line numbering makes it a lot easier to keep track of manual splitting), and then dump it into Excel in chunks smaller than 1,048,576 lines. Simple and quite quick - less faffy than researching into, installing and learning bespoke solutions. Quick and dirty, but it works.

How do I measure time elapsed in Java?

Which types to use in order to accomplish this in Java?

Answer: long

public class Stream {
    public long startTime;
    public long endTime;

    public long getDuration() {
        return endTime - startTime;
    }
    // I  would add
    public void start() {
        startTime = System.currentTimeMillis();
    }
    public void stop() {
         endTime = System.currentTimeMillis();
     }
}

Usage:

  Stream s = .... 

  s.start();

  // do something for a while 

  s.stop();

  s.getDuration(); // gives the elapsed time in milliseconds. 

That's my direct answer for your first question.

For the last "note" I would suggest you to use Joda Time. It contains an interval class suitable for what you need.

Linux find file names with given string recursively

This is a very simple solution using the tree command in the directory you want to search for. -f shows the full file path and | is used to pipe the output of tree to grep to find the file containing the string filename in the name.

tree -f | grep filename

How to add a TextView to a LinearLayout dynamically in Android?

LayoutParams lparams = new LayoutParams(
   LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tv=new TextView(this);
tv.setLayoutParams(lparams);
tv.setText("test");
this.m_vwJokeLayout.addView(tv);

You can change lparams according to your needs

Char array declaration and initialization in C

Yes, this is a kind of inconsistency in the language.

The "=" in myarray = "abc"; is assignment (which won't work as the array is basically a kind of constant pointer), whereas in char myarray[4] = "abc"; it's an initialization of the array. There's no way for "late initialization".

You should just remember this rule.

HTTP POST with URL query parameters -- good idea or not?

You want reasons? Here's one:

A web form can't be used to send a request to a page that uses a mix of GET and POST. If you set the form's method to GET, all the parameters are in the query string. If you set the form's method to POST, all the parameters are in the request body.

Source: HTML 4.01 standard, section 17.13 Form Submission

Angular ngClass and click event for toggling class

Angular6 using the renderer2 without any variables and a clean template:

template:

<div (click)="toggleClass($event,'testClass')"></div>

in ts:

toggleClass(event: any, class: string) {
  const hasClass = event.target.classList.contains(class);

  if(hasClass) {
    this.renderer.removeClass(event.target, class);
  } else {
    this.renderer.addClass(event.target, class);
  }
}

One could put this in a directive too ;)

Create a string with n characters

I think this is the less code it's possible, it uses Guava Joiner class:

Joiner.on("").join(Collections.nCopies(10, " "));

How to find the installed pandas version

Simplest Solution

Code:

import pandas as pd
pd.__version__

**Its double underscore before and after the word "version".

Output:

'0.14.1'

Concatenating string and integer in python

Modern string formatting:

"{} and {}".format("string", 1)

Why use the params keyword?

params also allows you to call the method with a single argument.

private static int Foo(params int[] args) {
    int retVal = 0;
    Array.ForEach(args, (i) => retVal += i);
    return retVal;
}

i.e. Foo(1); instead of Foo(new int[] { 1 });. Can be useful for shorthand in scenarios where you might need to pass in a single value rather than an entire array. It still is handled the same way in the method, but gives some candy for calling this way.

How to execute a raw update sql with dynamic binding in rails

ActiveRecord::Base.connection has a quote method that takes a string value (and optionally the column object). So you can say this:

ActiveRecord::Base.connection.execute(<<-EOQ)
  UPDATE  foo
  SET     bar = #{ActiveRecord::Base.connection.quote(baz)}
EOQ

Note if you're in a Rails migration or an ActiveRecord object you can shorten that to:

connection.execute(<<-EOQ)
  UPDATE  foo
  SET     bar = #{connection.quote(baz)}
EOQ

UPDATE: As @kolen points out, you should use exec_update instead. This will handle the quoting for you and also avoid leaking memory. The signature works a bit differently though:

connection.exec_update(<<-EOQ, "SQL", [[nil, baz]])
  UPDATE  foo
  SET     bar = $1
EOQ

Here the last param is a array of tuples representing bind parameters. In each tuple, the first entry is the column type and the second is the value. You can give nil for the column type and Rails will usually do the right thing though.

There are also exec_query, exec_insert, and exec_delete, depending on what you need.

Log4net rolling daily filename with date in the file name

I moved configuration to code to enable easy modification from CI using system variable. I used this code for file name and result is 'Log_03-23-2020.log'

            log4net.Repository.ILoggerRepository repository = LogManager.GetRepository(Assembly.GetEntryAssembly());
            Hierarchy hierarchy = (Hierarchy)repository;
            PatternLayout patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = "%date %level - %message%newline%exception";
            patternLayout.ActivateOptions();

            RollingFileAppender roller = new RollingFileAppender();
            roller.AppendToFile = true;
            roller.File = "Log_";
            roller.DatePattern = "MM-dd-yyyy'.log'";
            roller.Layout = patternLayout;
            roller.MaxFileSize = 1024*1024*10;
            roller.MaxSizeRollBackups = 10;
            roller.StaticLogFileName = false;
            roller.RollingStyle = RollingFileAppender.RollingMode.Composite;
            roller.ActivateOptions();
            hierarchy.Root.AddAppender(roller);

When to use Spring Security`s antMatcher()?

You need antMatcher for multiple HttpSecurity, see Spring Security Reference:

5.7 Multiple HttpSecurity

We can configure multiple HttpSecurity instances just as we can have multiple <http> blocks. The key is to extend the WebSecurityConfigurationAdapter multiple times. For example, the following is an example of having a different configuration for URL’s that start with /api/.

@EnableWebSecurity
public class MultiHttpSecurityConfig {
  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) { 1
      auth
          .inMemoryAuthentication()
              .withUser("user").password("password").roles("USER").and()
              .withUser("admin").password("password").roles("USER", "ADMIN");
  }

  @Configuration
  @Order(1)                                                        2
  public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
      protected void configure(HttpSecurity http) throws Exception {
          http
              .antMatcher("/api/**")                               3
              .authorizeRequests()
                  .anyRequest().hasRole("ADMIN")
                  .and()
              .httpBasic();
      }
  }    

  @Configuration                                                   4
  public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http
              .authorizeRequests()
                  .anyRequest().authenticated()
                  .and()
              .formLogin();
      }
  }
}

1 Configure Authentication as normal

2 Create an instance of WebSecurityConfigurerAdapter that contains @Order to specify which WebSecurityConfigurerAdapter should be considered first.

3 The http.antMatcher states that this HttpSecurity will only be applicable to URLs that start with /api/

4 Create another instance of WebSecurityConfigurerAdapter. If the URL does not start with /api/ this configuration will be used. This configuration is considered after ApiWebSecurityConfigurationAdapter since it has an @Order value after 1 (no @Order defaults to last).

In your case you need no antMatcher, because you have only one configuration. Your modified code:

http
    .authorizeRequests()
        .antMatchers("/high_level_url_A/sub_level_1").hasRole('USER')
        .antMatchers("/high_level_url_A/sub_level_2").hasRole('USER2')
        .somethingElse() // for /high_level_url_A/**
        .antMatchers("/high_level_url_A/**").authenticated()
        .antMatchers("/high_level_url_B/sub_level_1").permitAll()
        .antMatchers("/high_level_url_B/sub_level_2").hasRole('USER3')
        .somethingElse() // for /high_level_url_B/**
        .antMatchers("/high_level_url_B/**").authenticated()
        .anyRequest().permitAll()

Replace string in text file using PHP

This works like a charm, fast and accurate:

function replace_string_in_file($filename, $string_to_replace, $replace_with){
    $content=file_get_contents($filename);
    $content_chunks=explode($string_to_replace, $content);
    $content=implode($replace_with, $content_chunks);
    file_put_contents($filename, $content);
}

Usage:

$filename="users/data/letter.txt";
$string_to_replace="US$";
$replace_with="Yuan";
replace_string_in_file($filename, $string_to_replace, $replace_with);

// never forget about EXPLODE when it comes about string parsing // it's a powerful and fast tool

Using OR operator in a jquery if statement

Think about what

if ((state != 10) || (state != 15) || (state != 19) || (state != 22) || (state != 33) || (state != 39) || (state != 47) || (state != 48) || (state != 49) || (state != 51))

means. || means "or." The negation of this is (by DeMorgan's Laws):

state == 10 && state == 15 && state == 19...

In other words, the only way that this could be false if if a state equals 10, 15, and 19 (and the rest of the numbers in your or statement) at the same time, which is impossible.

Thus, this statement will always be true. State 15 will never equal state 10, for example, so it's always true that state will either not equal 10 or not equal 15.

Change || to &&.

Also, in most languages, the following:

if (x) {
  return true;
}
else {
  return false;
}

is not necessary. In this case, the method returns true exactly when x is true and false exactly when x is false. You can just do:

return x;

How can I set the request header for curl?

Sometimes changing the header is not enough, some sites check the referer as well:

curl -v \
     -H 'Host: restapi.some-site.com' \
     -H 'Connection: keep-alive' \
     -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
     -H 'Accept-Language: en-GB,en-US;q=0.8,en;q=0.6' \
     -e localhost \
     -A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.65 Safari/537.36' \
     'http://restapi.some-site.com/getsomething?argument=value&argument2=value'

In this example the referer (-e or --referer in curl) is 'localhost'.

Replace Div Content onclick

Working from your jsFiddle example:

The jsFiddle was fine, but you were missing semi-colons at the end of the event.preventDefault() statements.

This works: Revised jsFiddle

jQuery(document).ready(function() {
    jQuery(".rec1").click(function(event) {
        event.preventDefault();
        jQuery('#rec-box').html(jQuery(this).next().html()); 
    });
    jQuery(".rec2").click(function(event) {
        event.preventDefault();
        jQuery('#rec-box2').html(jQuery(this).next().html()); 
    });
});

Could not load file or assembly 'System.Net.Http.Formatting' or one of its dependencies. The system cannot find the path specified

Whenever I have a NuGet error such as these I usually take these steps:

  1. Go to the packages folder in the Windows Explorer and delete it.
  2. Open Visual Studio and Go to Tools > Library Package Manager > Package Manager Settings and under the Package Manager item on the left hand side there is a "Clear Package Cache" button. Click this button and make sure that the check box for "Allow NuGet to download missing packages during build" is checked.
  3. Clean the solution
  4. Then right click the solution in the Solution Explorer and enable NuGet Package Restore
  5. Build the solution
  6. Restart Visual Studio

Taking all of these steps almost always restores all the packages and dll's I need for my MVC program.


EDIT >>>

For Visual Studio 2013 and above, step 2) should read:

  1. Open Visual Studio and go to Tools > Options > NuGet Package Manager and on the right hand side there is a "Clear Package Cache button". Click this button and make sure that the check boxes for "Allow NuGet to download missing packages" and "Automatically check for missing packages during build in Visual Studio" are checked.

Regular expression for excluding special characters

Its usually better to whitelist characters you allow, rather than to blacklist characters you don't allow. both from a security standpoint, and from an ease of implementation standpoint.

If you do go down the blacklist route, here is an example, but be warned, the syntax is not simple.

http://groups.google.com/group/regex/browse_thread/thread/0795c1b958561a07

If you want to whitelist all the accent characters, perhaps using unicode ranges would help? Check out this link.

http://www.regular-expressions.info/unicode.html

How to convert Moment.js date to users local timezone?

You do not need to use moment-timezone for this. The main moment.js library has full functionality for working with UTC and the local time zone.

var testDateUtc = moment.utc("2015-01-30 10:00:00");
var localDate = moment(testDateUtc).local();

From there you can use any of the functions you might expect:

var s = localDate.format("YYYY-MM-DD HH:mm:ss");
var d = localDate.toDate();
// etc...

Note that by passing testDateUtc, which is a moment object, back into the moment() constructor, it creates a clone. Otherwise, when you called .local(), it would also change the testDateUtc value, instead of just the localDate value. Moments are mutable.

Also note that if your original input contains a time zone offset such as +00:00 or Z, then you can just parse it directly with moment. You don't need to use .utc or .local. For example:

var localDate = moment("2015-01-30T10:00:00Z");

How can I get the current date and time in UTC or GMT in Java?

public static void main(String args[]){
    LocalDate date=LocalDate.now();  
    System.out.println("Current date = "+date);
}

Sorting list based on values from another list

This is an old question but some of the answers I see posted don't actually work because zip is not scriptable. Other answers didn't bother to import operator and provide more info about this module and its benefits here.

There are at least two good idioms for this problem. Starting with the example input you provided:

X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0,   1,   1,   0,   1,   2,   2,   0,   1 ]

Using the "Decorate-Sort-Undecorate" idiom

This is also known as the Schwartzian_transform after R. Schwartz who popularized this pattern in Perl in the 90s:

# Zip (decorate), sort and unzip (undecorate).
# Converting to list to script the output and extract X
list(zip(*(sorted(zip(Y,X)))))[1]                                                                                                                       
# Results in: ('a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g')

Note that in this case Y and X are sorted and compared lexicographically. That is, the first items (from Y) are compared; and if they are the same then the second items (from X) are compared, and so on. This can create unstable outputs unless you include the original list indices for the lexicographic ordering to keep duplicates in their original order.

Using the operator module

This gives you more direct control over how to sort the input, so you can get sorting stability by simply stating the specific key to sort by. See more examples here.

import operator    

# Sort by Y (1) and extract X [0]
list(zip(*sorted(zip(X,Y), key=operator.itemgetter(1))))[0]                                                                                                 
# Results in: ('a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g')

Turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server

If you want to do this by code, you can add the behavior like this:

serviceHost.Description.Behaviors.Remove(
    typeof(ServiceDebugBehavior));
serviceHost.Description.Behaviors.Add(
    new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true });

Multiprocessing a for loop?

You can use multiprocessing.Pool:

from multiprocessing import Pool
class Engine(object):
    def __init__(self, parameters):
        self.parameters = parameters
    def __call__(self, filename):
        sci = fits.open(filename + '.fits')
        manipulated = manipulate_image(sci, self.parameters)
        return manipulated

try:
    pool = Pool(8) # on 8 processors
    engine = Engine(my_parameters)
    data_outputs = pool.map(engine, data_inputs)
finally: # To make sure processes are closed in the end, even if errors happen
    pool.close()
    pool.join()

How do I get the result of a command in a variable in windows?

The humble for command has accumulated some interesting capabilities over the years:

D:\> FOR /F "delims=" %i IN ('date /t') DO set today=%i
D:\> echo %today%
Sat 20/09/2008

Note that "delims=" overwrites the default space and tab delimiters so that the output of the date command gets gobbled all at once.

To capture multi-line output, it can still essentially be a one-liner (using the variable lf as the delimiter in the resulting variable):

REM NB:in a batch file, need to use %%i not %i
setlocal EnableDelayedExpansion
SET lf=-
FOR /F "delims=" %%i IN ('dir \ /b') DO if ("!out!"=="") (set out=%%i) else (set out=!out!%lf%%%i)
ECHO %out%

To capture a piped expression, use ^|:

FOR /F "delims=" %%i IN ('svn info . ^| findstr "Root:"') DO set "URL=%%i"