Programs & Examples On #Unsigned char

How to write a comment in a Razor view?

This comment syntax should work for you:

@* enter comments here *@

Nth word in a string variable

An alternative

N=3
STRING="one two three four"

arr=($STRING)
echo ${arr[N-1]}

Python `if x is not None` or `if not x is None`?

Both Google and Python's style guide is the best practice:

if x is not None:
    # Do something about x

Using not x can cause unwanted results.

See below:

>>> x = 1
>>> not x
False
>>> x = [1]
>>> not x
False
>>> x = 0
>>> not x
True
>>> x = [0]         # You don't want to fall in this one.
>>> not x
False

You may be interested to see what literals are evaluated to True or False in Python:


Edit for comment below:

I just did some more testing. not x is None doesn't negate x first and then compared to None. In fact, it seems the is operator has a higher precedence when used that way:

>>> x
[0]
>>> not x is None
True
>>> not (x is None)
True
>>> (not x) is None
False

Therefore, not x is None is just, in my honest opinion, best avoided.


More edit:

I just did more testing and can confirm that bukzor's comment is correct. (At least, I wasn't able to prove it otherwise.)

This means if x is not None has the exact result as if not x is None. I stand corrected. Thanks bukzor.

However, my answer still stands: Use the conventional if x is not None. :]

what is the difference between const_iterator and iterator?

if you have a list a and then following statements

list<int>::iterator it; // declare an iterator
    list<int>::const_iterator cit; // declare an const iterator 
    it=a.begin();
    cit=a.begin();

you can change the contents of the element in the list using “it” but not “cit”, that is you can use “cit” for reading the contents not for updating the elements.

*it=*it+1;//returns no error
    *cit=*cit+1;//this will return error

How to resolve "Error: bad index – Fatal: index file corrupt" when using Git

This sounds like a bad clone. You could try the following to get (possibly?) more information:

git fsck --full

How do you develop Java Servlets using Eclipse?

I use Eclipse Java EE edition

Create a "Dynamic Web Project"

Install a local server in the server view, for the version of Tomcat I'm using. Then debug, and run on that server for testing.

When I deploy I export the project to a war file.

CSS text-align not working

Change the rule on your <a> element from:

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
}?

to

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
    width:100%;
    text-align:center;
}?

Just add two new rules (width:100%; and text-align:center;). You need to make the anchor expand to take up the full width of the list item and then text-align center it.

jsFiddle example

add title attribute from css

As Quentin and other suggested this cannot totally be done with css(partially done with content attribute of css). Instead you should use javascript/jQuery to achieve this,

JS:

document.getElementsByClassName("mandatory")[0].title = "mandatory";

or using jQuery:

$('.mandatory').attr('title','mandatory');

_x000D_
_x000D_
document.getElementsByClassName('mandatory')[0].setAttribute('title', 'mandatory');_x000D_
_x000D_
$('.jmandatory').attr('title', 'jmandatory');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
Place the Mouse Over the following elements to see the title,_x000D_
<br/><br/>_x000D_
<b><label class="mandatory">->Javascript Mandatory</label></b>_x000D_
<br/><br/>_x000D_
<b><label class="jmandatory">->jQuery Mandatory</label></b>
_x000D_
_x000D_
_x000D_

Identify duplicates in a List

I took John Strickler's solution and remade it to use the streams API introduced in JDK8:

private <T> Set<T> findDuplicates(Collection<T> collection) {
    Set<T> uniques = new HashSet<>();
    return collection.stream()
        .filter(e -> !uniques.add(e))
        .collect(Collectors.toSet());
}

Reset auto increment counter in postgres

To reset the auto increment you have to get your sequence name by using following query.

Syntax:

SELECT pg_get_serial_sequence(‘tablename’, ‘ columnname‘);

Example:

SELECT pg_get_serial_sequence('demo', 'autoid');

The query will return the sequence name of autoid as "Demo_autoid_seq" Then use the following query to reset the autoid

Syntax:

ALTER SEQUENCE sequenceName RESTART WITH value;

Example:

ALTER SEQUENCE "Demo_autoid_seq" RESTART WITH 1453;

Is there a way to use max-width and height for a background image?

Unfortunately there's no min (or max)-background-size in CSS you can only use background-size. However if you are seeking a responsive background image you can use Vmin and Vmaxunits for the background-size property to achieve something similar.

example:

#one {
    background:url('../img/blahblah.jpg') no-repeat;
    background-size:10vmin 100%;
}

that will set the height to 10% of the whichever smaller viewport you have whether vertical or horizontal, and will set the width to 100%.

Read more about css units here: https://www.w3schools.com/cssref/css_units.asp

How to set python variables to true or false?

match_var = a==b

that should more than suffice

you cant use a - in a variable name as it thinks that is match (minus) var

match=1
var=2

print match-var  #prints -1

Getting last month's date in php

You can use strtotime, which is great in this kind of situations :

$timestamp = strtotime('-1 month');
var_dump(date('Y-m', $timestamp));

Will get you :

string '2009-11' (length=7)

Checking Value of Radio Button Group via JavaScript?

Try:


var selectedVal;

for( i = 0; i < document.form_name.gender.length; i++ )
{
  if(document.form_name.gender[i].checked)
    selectedVal = document.form_name.gender[i].value; //male or female
    break;
  }
}

How to check cordova android version of a cordova/phonegap project?

After upgrading the Application. I observed different Cordova versions.

  1. Apache Cordova Cli version which is 6.0.0.
  2. Cordova Android version which is 5.1.0.
  3. Cordova IOS version which is 4.1.1.
  4. Docs version is which is 6.0.0, shown on the Cordova Docs website.

Now i am confused, On which version basis, Google Dev Console is giving warning?

Please migrate your app(s) to Apache Cordova v.4.1.1 or higher as soon as possible and increment the version number of the upgraded APK. Beginning May 9, 2016, Google Play will block publishing of any new apps or updates that use pre-4.1.1 versions of Apache Cordova.

The vulnerabilities were addressed in Apache Cordova 4.1.1. If you’re using a 3rd party library that bundles Apache Cordova, you’ll need to upgrade it to a version that bundles Apache Cordova 4.1.1 or later.

And before upgrading. Our Application versions were these.

  1. Apache Cordova Cli version which is 5.4.1.
  2. Cordova Android version which is 4.1.1.
  3. Cordova IOS version which is 3.9.1.
  4. Docs version is which is 5.4.1, shown on the Cordova Docs website.

CSS @font-face not working in ie

1) Try putting an absolute link not relative link to your eot font - somehow old IE just don't know in which folder the css file is 2) make 2 extra @font-face declarations so it should look like this:

@font-face { /* for modern browsers and modern IE */
    font-family: "Futura";
    src: url("../fonts/Futura_Medium_BT.eot"); 
    src: url("../fonts/Futura_Medium_BT.eot?#iefix") format("embedded-opentype"), 
    url( "../fonts/Futura_Medium_BT.ttf" ) format("truetype"); 
}
@font-face{ /* for old IE */
  font-family: "Futura_IE"; 
  src: url(/wp-content/themes/my-theme/fonts/Futura_Medium_BT.eot);
}

@font-face{ /* for old IE */
  font-family: "Futura_IE2"; 
  src:url(/wp-content/themes/my-theme/fonts/Futura_Medium_BT.eot?#iefix) 
  format("embedded-opentype");
}

.p{ font-family: "Futura", "Futura_IE", "Futura_IE2", Arial, sans-serif;

This is an example for wordpress template - absolute link should point from where your start index file is.

Inline for loop

your list comphresnion will, work but will return list of None because append return None:

demo:

>>> a=[]
>>> [ a.append(x) for x in range(10) ]
[None, None, None, None, None, None, None, None, None, None]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

better way to use it like this:

>>> a= [ x for x in range(10) ]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

java.lang.ClassCastException

According to the documentation:

Thrown to indicate that the code has attempted to cast an Object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException:

Object x = new Integer(0);
System.out.println((String)x); 

How to retry after exception?

Here's my idea on how to fix this:

j = 19
def calc(y):
    global j
    try:
        j = j + 8 - y
        x = int(y/j)   # this will eventually raise DIV/0 when j=0
        print("i = ", str(y), " j = ", str(j), " x = ", str(x))
    except:
        j = j + 1   # when the exception happens, increment "j" and retry
        calc(y)
for i in range(50):
    calc(i)

How to do left join in Doctrine?

If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin('a.user', 'u')
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

Since you are applying a condition on the joined result here, using a LEFT JOIN or simply JOIN is the same.

If no association is available, then the query looks like following

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin(
            'User\Entity\User',
            'u',
            \Doctrine\ORM\Query\Expr\Join::WITH,
            'a.user = u.id'
        )
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

This will produce a resultset that looks like following:

array(
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    // ...
)

Select element by exact match of its content

So Amandu's answer mostly works. Using it in the wild, however, I ran into some issues, where things that I would have expected to get found were not getting found. This was because sometimes there is random white space surrounding the element's text. It is my belief that if you're searching for "Hello World", you would still want it to match " Hello World ", or even "Hello World \n". Thus, I just added the "trim()" method to the function, which removes surrounding whitespace, and it started to work better.

Specifically...

$.expr[':'].textEquals = function(el, i, m) {
    var searchText = m[3];
    var match = $(el).text().trim().match("^" + searchText + "$")
    return match && match.length > 0;
}

Also, note, this answer is extremely similar to Select link by text (exact match)

And secondary note... trim only removes whitespace before and after the searched text. It does not remove whitespace in the middle of the words. I believe this is desirable behavior, but you could change that if you wanted.

Git: which is the default configured remote for branch?

Track the remote branch

You can specify the default remote repository for pushing and pulling using git-branch’s track option. You’d normally do this by specifying the --track option when creating your local master branch, but as it already exists we’ll just update the config manually like so:

Edit your .git/config

[branch "master"]
  remote = origin
  merge = refs/heads/master

Now you can simply git push and git pull.

[source]

How to use jQuery to show/hide divs based on radio button selection?

An interesting solution is to make this declarative: you just give every div that should be shown an attribute automaticallyVisibleIfIdChecked with the id of the checkbox or radio button on which it depends. That is, your form looks like this:

<form name="form1" id="my_form" method="post" action="">
    <div><label><input type="radio" name="group1" id="rdio1" value="opt1">opt1</label></div>  
    <div><label><input type="radio" name="group1" id="rdio2" value="opt2">opt2</label></div>  
</form>
....
<div id="opt1" automaticallyVisibleIfIdChecked="rdio1">lorem ipsum dolor</div>
<div id="opt2" automaticallyVisibleIfIdChecked="rdio2">consectetur adipisicing</div>

and have some page independent JavaScript that nicely uses functional programming:

function executeAutomaticVisibility(name) {
    $("[name="+name+"]:checked").each(function() {
        $("[automaticallyVisibleIfIdChecked=" + this.id+"]").show();
    });
    $("[name="+name+"]:not(:checked)").each(function() {
        $("[automaticallyVisibleIfIdChecked=" + this.id+"]").hide();
    });
}

$(document).ready( function() {
    triggers = $("[automaticallyVisibleIfIdChecked]")
        .map(function(){ return $("#" + $(this).attr("automaticallyVisibleIfIdChecked")).get() })
    $.unique(triggers);
    triggers.each( function() {
        executeAutomaticVisibility(this.name);
        $(this).change( function(){ executeAutomaticVisibility(this.name); } );
    });
});

Similarily you could automatically enable / disable form fields with an attribute automaticallyEnabledIfChecked.

I think this method is nice since it avoids having to create specific JavaScript for your page - you just insert some attributes that say what should be done.

Increase distance between text and title on the y-axis

From ggplot2 2.0.0 you can use the margin = argument of element_text() to change the distance between the axis title and the numbers. Set the values of the margin on top, right, bottom, and left side of the element.

ggplot(mpg, aes(cty, hwy)) + geom_point()+
  theme(axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)))

margin can also be used for other element_text elements (see ?theme), such as axis.text.x, axis.text.y and title.

addition

in order to set the margin for axis titles when the axis has a different position (e.g., with scale_x_...(position = "top"), you'll need a different theme setting - e.g. axis.title.x.top. See https://github.com/tidyverse/ggplot2/issues/4343.

How to combine two vectors into a data frame

Here's a simple function. It generates a data frame and automatically uses the names of the vectors as values for the first column.

myfunc <- function(a, b, names = NULL) {
  setNames(data.frame(c(rep(deparse(substitute(a)), length(a)), 
                        rep(deparse(substitute(b)), length(b))), c(a, b)), names)
}

An example:

x <-c(1,2,3)
y <-c(100,200,300)
x_name <- "cond"
y_name <- "rating"

myfunc(x, y, c(x_name, y_name))

  cond rating
1    x      1
2    x      2
3    x      3
4    y    100
5    y    200
6    y    300

Simple linked list in C++

The addNode function needs to be able to change head. As it's written now simply changes the local variable head (a parameter).

Changing the code to

void addNode(struct Node *& head, int n){
    ...
}

would solve this problem because now the head parameter is passed by reference and the called function can mutate it.

Set port for php artisan.php serve

when we use the

php artisan serve 

it will start with the default HTTP-server port mostly it will be 8000 when we want to run the more site in the localhost we have to change the port. Just add the --port argument:

php artisan serve --port=8081

enter image description here

How to disable text selection highlighting

I like the hybrid CSS + jQuery solution.

To make all elements inside <div class="draggable"></div> unselectable, use this CSS:

.draggable {
    -webkit-user-select: none;
     -khtml-user-select: none;
       -moz-user-select: none;
        -ms-user-select: none;
         -o-user-select: none;
            user-select: none;
}

.draggable input {
    -webkit-user-select: text;
     -khtml-user-select: text;
       -moz-user-select: text;
         -o-user-select: text;
            user-select: text;
 }

And then, if you're using jQuery, add this inside a $(document).ready() block:

if (($.browser.msie && $.browser.version < 10) || $.browser.opera) $('.draggable').find(':not(input)').attr('unselectable', 'on');

I figure you still want any input elements to be interactable, hence the :not() pseudo-selector. You could use '*' instead if you don't care.

Caveat: Internet Explorer 9 may not need this extra jQuery piece, so you may want to add a version check in there.

no sqljdbc_auth in java.library.path

Here are the steps if you want to do this from Eclipse :

1) Create a folder 'sqlauth' in your C: drive, and copy the dll file sqljdbc_auth.dll to the folder

1) Go to Run> Run Configurations

2) Choose the 'Arguments' tab for your class

3) Add the below code in VM arguments:

-Djava.library.path="C:\\sqlauth"

4) Hit 'Apply' and click 'Run'

Feel free to try other methods .

ie8 var w= window.open() - "Message: Invalid argument."

This is an old posting but maybe still useful for someone.

I had the same error message. In the end the problem was an invalid name for the second argument, i.e., I had a line like:

   window.open('/somefile.html', 'a window title', 'width=300');

The problem was 'a window title' as it is not valid. It worked fine with the following line:

   window.open('/somefile.html', '', 'width=300');

In fact, reading carefully I realized that Microsoft does not support a name as second argument. When you look at the official documentation page, you see that Microsoft only allows the following arguments, If using that argument at all:

  • _blank
  • _media
  • _parent
  • _search
  • _self
  • _top

How to pass ArrayList of Objects from one to another activity using Intent in android?

Implements Parcelable and send arraylist as putParcelableArrayListExtra and get it from next activity getParcelableArrayListExtra

example:

Implement parcelable on your custom class -(Alt +enter) Implement its methods

public class Model implements Parcelable {

private String Id;

public Model() {

}

protected Model(Parcel in) {
    Id= in.readString();       
}

public static final Creator<Model> CREATOR = new Creator<Model>() {
    @Override
    public ModelcreateFromParcel(Parcel in) {
        return new Model(in);
    }

    @Override
    public Model[] newArray(int size) {
        return new Model[size];
    }
};

public String getId() {
    return Id;
}

public void setId(String Id) {
    this.Id = Id;
}


@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(Id);
}
}

Pass class object from activity 1

 Intent intent = new Intent(Activity1.this, Activity2.class);
            intent.putParcelableArrayListExtra("model", modelArrayList);
            startActivity(intent);

Get extra from Activity2

if (getIntent().hasExtra("model")) {
        Intent intent = getIntent();
        cartArrayList = intent.getParcelableArrayListExtra("model");

    } 

D3 transform scale and translate

I realize this question is fairly old, but wanted to share a quick demo of group transforms, paths/shapes, and relative positioning, for anyone else who found their way here looking for more info:

http://bl.ocks.org/dustinlarimer/6050773

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

going to the website: gives me following information from developer tool and looking at headers. (right click --> inspect. then open network tab and check headers)

  • Request URL: http://www.msft.com/
  • Request Method: GET
  • Status Code:200 OK
  • Remote Address: 205.178.189.130:80
  • Referrer Policy:no-referrer-when-downgrade

So we see we need to perform a request to HTTP, not HTTPS.

import requests


def Earlybird():
    url = 'http://msft.com/'
    response = requests.get(url)
    print(response.text)

if __name__ == '__main__':
    Earlybird()

How do I import a .bak file into Microsoft SQL Server 2012?

.bak is a backup file generated in SQL Server.

Backup files importing means restoring a database, you can restore on a database created in SQL Server 2012 but the backup file should be from SQL Server 2005, 2008, 2008 R2, 2012 database.

You restore database by using following command...

RESTORE DATABASE YourDB FROM DISK = 'D:BackUpYourBaackUpFile.bak' WITH Recovery

You want to learn about how to restore .bak file follow the below link:

http://msdn.microsoft.com/en-us/library/ms186858(v=sql.90).aspx

Change Project Namespace in Visual Studio

Right click properties, Application tab, then see the assembly name and default namespace

nginx - read custom header from upstream server

Use $http_MY_CUSTOM_HEADER

You can write some-thing like

set my_header $http_MY_CUSTOM_HEADER;
if($my_header != 'some-value') {
#do some thing;
}

How to iterate object in JavaScript?

Using for and foreach loop

var dictionary = {
     data: [{ id: "0", name: "ABC" }, { id: "1", name: "DEF" }],
     images: [{ id: "0", name: "PQR" }, { id: "1", name: "xyz" }]
};
dictionary.data.forEach(item => {
     console.log(item.id + " " + item.name);
});

for (var i = 0; i < dictionary.data.length; i++) {
     console.log(dictionary.data[i].id + " " + dictionary.data[i].name);
}

Android Layout Right Align

If you want to use LinearLayout, you can do alignment with layout_weight with Space element.

E.g. following layout places textView and textView2 next to each other and textView3 will be right-aligned

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/textView" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/textView2" />

    <Space
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="20dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/textView3" />
</LinearLayout>

you can achieve the same effect without Space if you would set layout_weight to textView2. It's just that I like things more separated, plus to demonstrate Space element.

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/textView2" />

Note that you should (not must though) set layout_width explicitly as it will be recalculated according to it's weight anyway (same way you should set height in elements of vertical LinearLayout). For other layout performance tips see Android Layout Tricks series.

How to print a number with commas as thousands separators in JavaScript

This is a variation of @mikez302's answer, but modified to support numbers with decimals (per @neu-rah's feedback that numberWithCommas(12345.6789) -> "12,345.6,789" instead of "12,345.6789"

function numberWithCommas(n) {
    var parts=n.toString().split(".");
    return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}

Polling the keyboard (detect a keypress) in python


import sys
import select

def heardEnter():
    i,o,e = select.select([sys.stdin],[],[],0.0001)
    for s in i:
        if s == sys.stdin:
            input = sys.stdin.readline()
            return True
    return False

How to specify HTTP error code?

A simple one liner;

res.status(404).send("Oh uh, something went wrong");

What is the use of WPFFontCache Service in WPF? WPFFontCache_v0400.exe taking 100 % CPU all the time this exe is running, why?

After installing Free BitDefender AntiVirus the services related to the AntiVirus used about 80 MB of my computer's Memory. I also noticed that after installing BitDefender the service related to windows Presentation Font Cache was also installed: "WPFFontCache_v0300.exe". I disabled the service from stating automatically and now BitDefender Free AntiVirus use only 15-20 MB (!!!) of my computer's Memory! As far as I concern, this service affected negatively the memory usage of my PC inother services. I recommend you to disable it.

Mongoose delete array element in document and save

The checked answer does work but officially in MongooseJS latest, you should use pull.

doc.subdocs.push({ _id: 4815162342 }) // added
doc.subdocs.pull({ _id: 4815162342 }) // removed

https://mongoosejs.com/docs/api.html#mongoosearray_MongooseArray-pull

I was just looking that up too.

See Daniel's answer for the correct answer. Much better.

Why do I get a warning icon when I add a reference to an MEF plugin project?

Make sure you have the projects targeting the same framework version. Most of the times the reason would be that current project ( where you are adding reference of another project ) points to a different .net framework version than the rest ones.

CSS Auto hide elements after 5 seconds

Of course you can, just use setTimeout to change a class or something to trigger the transition.

HTML:

<p id="aap">OHAI!</p>

CSS:

p {
    opacity:1;
    transition:opacity 500ms;
}
p.waa {
    opacity:0;
}

JS to run on load or DOMContentReady:

setTimeout(function(){
    document.getElementById('aap').className = 'waa';
}, 5000);

Example fiddle here.

Spring Data JPA find by embedded object property

This method name should do the trick:

Page<QueuedBook> findByBookIdRegion(Region region, Pageable pageable);

More info on that in the section about query derivation of the reference docs.

Shell script "for" loop syntax

Here it worked on Mac OS X.

It includes the example of a BSD date, how to increment and decrement the date also:

for ((i=28; i>=6 ; i--));
do
    dat=`date -v-${i}d -j "+%Y%m%d"` 
    echo $dat
done

Cannot run the macro... the macro may not be available in this workbook

In my case this error came up when the Sub name was identical to the Module name.

update to python 3.7 using anaconda

Python 3.7 is now available to be installed, but many packages have not been updated yet. As noted by another answer here, there is a GitHub issue tracking the progress of Anaconda building all the updated packages.


Until someone creates a conda package for Python 3.7, you can't install it. Unfortunately, something like 3500 packages show up in a search for "python" on Anaconda.org (https://anaconda.org/search?q=%22python%22) so I couldn't see if anyone has done that yet.

You might be able to build your own package, depending on what OS you want it for. You can start with the recipe that conda-forge uses to build Python: https://github.com/conda-forge/python-feedstock/

In the past, I think Continuum have generally waited until a stable release to push out packages for new Pythons, but I don't work there, so I don't know what their actual policy is.

Running multiple async tasks and waiting for them all to complete

You could create many tasks like:

List<Task> TaskList = new List<Task>();
foreach(...)
{
   var LastTask = new Task(SomeFunction);
   LastTask.Start();
   TaskList.Add(LastTask);
}

Task.WaitAll(TaskList.ToArray());

How to dynamically remove items from ListView on a button click?

<ImageView
    android:id="@+id/btnDelete"
    android:layout_width="35dp"
    android:layout_height="match_parent"
    android:layout_alignBottom="@+id/editTipo"
    android:layout_alignParentRight="true"
    android:background="@drawable/abc_ic_clear"
    android:onClick="item_delete_handler"/>

And create Event item_delete_handler,

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

Server.Mappath in C# classlibrary

Architecturally, System.web should not be referred in Business Logic Layer (BLL). Employ BLL into the solution structure to follow the separate of concern principle so refer System.Web is a bad practice. BLL should not load/run in Asp.net context. Because of the reason you should consider using of System.AppDomain.CurrentDomain.BaseDirectory instead of System.Web.HttpContext.Current.Server.MapPath

TypeError: method() takes 1 positional argument but 2 were given

You should actually create a class:

class accum:
    def __init__(self):
        self.acc = 0
    def accumulator(self, var2add, end):
        if not end:
            self.acc+=var2add
    return self.acc

Accessing Session Using ASP.NET Web API

You can access session state using a custom RouteHandler.

// In global.asax
public class MvcApp : System.Web.HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        var route = routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        route.RouteHandler = new MyHttpControllerRouteHandler();
    }
}

// Create two new classes
public class MyHttpControllerHandler
    : HttpControllerHandler, IRequiresSessionState
{
    public MyHttpControllerHandler(RouteData routeData) : base(routeData)
    { }
}
public class MyHttpControllerRouteHandler : HttpControllerRouteHandler
{
    protected override IHttpHandler GetHttpHandler(
        RequestContext requestContext)
    {
        return new MyHttpControllerHandler(requestContext.RouteData);
    }
}

// Now Session is visible in your Web API
public class ValuesController : ApiController
{
    public string Get(string input)
    {
        var session = HttpContext.Current.Session;
        if (session != null)
        {
            if (session["Time"] == null)
                session["Time"] = DateTime.Now;
            return "Session Time: " + session["Time"] + input;
        }
        return "Session is not availabe" + input;
    }
}

Found here: http://techhasnoboundary.blogspot.com/2012/03/mvc-4-web-api-access-session.html

Invalid http_host header

In your project settings.py file,set ALLOWED_HOSTS like this :

ALLOWED_HOSTS = ['62.63.141.41', 'namjoosadr.com']

and then restart your apache. in ubuntu:

/etc/init.d/apache2 restart

React JS Error: is not defined react/jsx-no-undef

Strangely enough, the reason for my failure was about the CamelCase that I was applying to the component name. MyComponent was giving me this error but then I renamed it to Mycomponent and voila, it worked!!!

Java Reflection Performance

Yes - absolutely. Looking up a class via reflection is, by magnitude, more expensive.

Quoting Java's documentation on reflection:

Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.

Here's a simple test I hacked up in 5 minutes on my machine, running Sun JRE 6u10:

public class Main {

    public static void main(String[] args) throws Exception
    {
        doRegular();
        doReflection();
    }

    public static void doRegular() throws Exception
    {
        long start = System.currentTimeMillis();
        for (int i=0; i<1000000; i++)
        {
            A a = new A();
            a.doSomeThing();
        }
        System.out.println(System.currentTimeMillis() - start);
    }

    public static void doReflection() throws Exception
    {
        long start = System.currentTimeMillis();
        for (int i=0; i<1000000; i++)
        {
            A a = (A) Class.forName("misc.A").newInstance();
            a.doSomeThing();
        }
        System.out.println(System.currentTimeMillis() - start);
    }
}

With these results:

35 // no reflection
465 // using reflection

Bear in mind the lookup and the instantiation are done together, and in some cases the lookup can be refactored away, but this is just a basic example.

Even if you just instantiate, you still get a performance hit:

30 // no reflection
47 // reflection using one lookup, only instantiating

Again, YMMV.

Make index.html default, but allow index.php to be visited if typed in

If you're using WordPress, there is now a filter hook to resolve this:

remove_filter('template_redirect', 'redirect_canonical'); 

(Put this in your theme's functions.php)

This tells WordPress to not redirect index.php back to the root page, but to sit where it is. That way, index.html can be assigned to be the default page in .htaccess and can work alongside index.php.

Check if a folder exist in a directory and create them using C#

    String path = Server.MapPath("~/MP_Upload/");
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    }

How do I escape a percentage sign in T-SQL?

WHERE column_name LIKE '%save 50[%] off!%'

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

Most answers suggest to just add ServerName localhost to /etc/apache2/apache2.conf.

But quoting Apache documentation :

The presence of this error message also indicates that Apache httpd was unable to obtain a fully-qualified hostname by doing a reverse lookup on your server's IP address. While the above instructions will get rid of the warning in any case, it is also a good idea to fix your name resolution so that this reverse mapping works.

Therefore adding such a line to /etc/hosts is probably a more robust solution :

192.0.2.0  foobar.example.com  foobar

where 192.0.2.0 is the static IP address of the server named foobar within the example.com domain.

One can check the FQDN e.g. with

hostname -A

(shortcut for hostname --all-fqdn).

How to create a QR code reader in a HTML5 website?

The jsqrcode library by Lazarsoft is now working perfectly using just HTML5, i.e. getUserMedia (WebRTC). You can find it on GitHub.

I also found a great fork which is much simplified. Just one file (plus jQuery) and one call of a method: see html5-qrcode on GitHub.

Procedure or function !!! has too many arguments specified

Use the following command before defining them:

cmd.Parameters.Clear()

No plot window in matplotlib

If you are user of Anaconda and Spyder then best solution for you is that :

Tools --> Preferences --> Ipython console --> Graphic Section

Then in the Support for graphics (Matplotlib) section:

select two avaliable options

and in the Graphics Backend:

select Automatic

How to Lazy Load div background images

I know it's not related to the image load but here what I did in one of the job interview test.

HTML

<div id="news-feed">Scroll to see News (Newest First)</div>

CSS

article {
   margin-top: 500px;
   opacity: 0;
   border: 2px solid #864488;
   padding: 5px 10px 10px 5px;
   background-image: -webkit-gradient(
   linear,
   left top,
   left bottom,
   color-stop(0, #DCD3E8),
   color-stop(1, #BCA3CC)
   );
   background-image: -o-linear-gradient(bottom, #DCD3E8 0%, #BCA3CC 100%);
   background-image: -moz-linear-gradient(bottom, #DCD3E8 0%, #BCA3CC 100%);
   background-image: -webkit-linear-gradient(bottom, #DCD3E8 0%, #BCA3CC 100%);
   background-image: -ms-linear-gradient(bottom, #DCD3E8 0%, #BCA3CC 100%);
   background-image: linear-gradient(to bottom, #DCD3E8 0%, #BCA3CC 100%);
   color: gray;
   font-family: arial;    
}

article h4 {
   font-family: "Times New Roman";
   margin: 5px 1px;
}

.main-news {
   border: 5px double gray;
   padding: 15px;
}

JavaScript

var newsData,
    SortData = '',
    i = 1;

$.getJSON("http://www.stellarbiotechnologies.com/media/press-releases/json", function(data) {

   newsData = data.news;

   function SortByDate(x,y) {
     return ((x.published == y.published) ? 0 : ((x.published < y.published) ? 1 : -1 ));
   }

   var sortedNewsData = newsData.sort(SortByDate);

   $.each( sortedNewsData, function( key, val ) {
     SortData += '<article id="article' + i + '"><h4>Published on: ' + val.published + '</h4><div  class="main-news">' + val.title + '</div></article>';
     i++;    
   });

   $('#news-feed').append(SortData);
});

$(window).scroll(function() {

   var $window = $(window),
       wH = $window.height(),
       wS = $window.scrollTop() + 1

   for (var j=0; j<$('article').length;j++) {
      var eT = $('#article' + j ).offset().top,
          eH = $('#article' + j ).outerHeight();

          if (wS > ((eT + eH) - (wH))) {
             $('#article' + j ).animate({'opacity': '1'}, 500);
          }
    }

});

I am sorting the data by Date and then doing lazy load on window scroll function.

I hope it helps :)

Demo

Why my $.ajax showing "preflight is invalid redirect error"?

Please set http content type in header and also make sure the server is authenticating CORS. This is how to do it in PHP:

//NOT A TESTED CODE
header('Content-Type: application/json;charset=UTF-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: DELETE, HEAD, GET, OPTIONS, POST, PUT');
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');
header('Access-Control-Max-Age: 1728000');

Please refer to:

http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0

How does Access-Control-Allow-Origin header work?

How to convert array to SimpleXML

You can do this through DOM also. Please see below code.

<?php

$el = array();
$command = array();

$dom = new DOMDocument('1.0', 'utf-8');
$dom->formatOutput = true;

$xml_array = [
    'root'=>[
    'Good guy' => [
        'name' => [
            '_cdata' => 'Luke Skywalker'
        ],
        'weapon' => 'Lightsaber'
    ],
    'Bad guy' => [
        'name' => 'Sauron',
        'weapon' => 'Evil Eye'
    ]
        ]
];

convert_xml($xml_array);

if(!empty($el))
{
    $dom->appendChild(end($el));
}

echo $dom->saveXML();

?>

<?php

 function convert_xml($Xml)
{
    global $el, $dom;

        foreach($Xml as $id=>$val)
        {
            if(is_numeric($id))
            {
                $id = "Item".($id);
            }

            $id = str_replace(' ', '-', strtolower($id));

            if(is_array($val))
            {
                $ele = $dom->createElement($id);
                array_push($el, $ele);
                convert_xml($val);
            }
            else
            {
                $ele = $dom->createElement($id, $val);

                if(!empty($el))
                {
                    $com = end($el)->appendChild($ele);
                }
                else
                {
                    $dom->appendChild($ele);
                }

            }
        }

        if(sizeof($el) > 1)
        {
            $child = end($el);
            $com = prev($el)->appendChild($child);
            array_pop($el);
        }
}

?>

Get current application physical path within Application_Start

System.AppDomain.CurrentDomain.BaseDirectory

This will give you the running directory of your application. This even works for web applications. Afterwards, you can reach your file.

How to open the default webbrowser using java

Its very simple just write below code:

String s = "http://www.google.com";
Desktop desktop = Desktop.getDesktop();
desktop.browse(URI.create(s));

or if you don't want to load URL then just write your browser name into string values like,

String s = "chrome";
Desktop desktop = Desktop.getDesktop();
desktop.browse(URI.create(s));

it will open browser automatically with empty URL after executing a program

How to get host name with port from a http or https request

If your server is running behind a proxy server, make sure your proxy header is set:

proxy_set_header X-Forwarded-Proto  $scheme;

Then to get the right scheme & url you can use springframework's classes:

public String getUrl(HttpServletRequest request) {
    HttpRequest httpRequest = new ServletServerHttpRequest(request);
    UriComponents uriComponents = UriComponentsBuilder.fromHttpRequest(httpRequest).build();

    String scheme = uriComponents.getScheme();             // http / https
    String serverName = request.getServerName();     // hostname.com
    int serverPort = request.getServerPort();        // 80
    String contextPath = request.getContextPath();   // /app

    // Reconstruct original requesting URL
    StringBuilder url = new StringBuilder();
    url.append(scheme).append("://");
    url.append(serverName);

    if (serverPort != 80 && serverPort != 443) {
        url.append(":").append(serverPort);
    }
    url.append(contextPath);
    return url.toString();
}

Like Operator in Entity Framework?

For EfCore here is a sample to build LIKE expression

protected override Expression<Func<YourEntiry, bool>> BuildLikeExpression(string searchText)
    {
        var likeSearch = $"%{searchText}%";

        return t => EF.Functions.Like(t.Code, likeSearch)
                    || EF.Functions.Like(t.FirstName, likeSearch)
                    || EF.Functions.Like(t.LastName, likeSearch);
    }

//Calling method

var query = dbContext.Set<YourEntity>().Where(BuildLikeExpression("Text"));

How does the Java 'for each' loop work?

Also note that using the "foreach" method in the original question does have some limitations, such as not being able to remove items from the list during the iteration.

The new for-loop is easier to read and removes the need for a separate iterator, but is only really usable in read-only iteration passes.

Getting the textarea value of a ckeditor textarea with javascript

At least as of CKEDITOR 4.4.5, you can set up a listener for every change to the editor's contents, rather than running a timer:

CKEDITOR.on("instanceCreated", function(event) {
    event.editor.on("change", function () {
        $("#trackingDiv").html(event.editor.getData());
    });
});

I realize this may be too late for the OP, and doesn't show as the correct answer or have any votes (yet), but I thought I'd update the post for future readers.

How do I set a variable to the output of a command in Bash?

You can use backticks (also known as accent graves) or $().

Like:

OUTPUT=$(x+2);
OUTPUT=`x+2`;

Both have the same effect. But OUTPUT=$(x+2) is more readable and the latest one.

How does one set up the Visual Studio Code compiler/debugger to GCC?

Caution

A friendly reminder: The following tutorial is for Linux user instead of Windows

Tutorial

If you want to debug your c++ code with GDB

You can read this ( Debugging your code ) article from Visual Studio Code official website.

Step 1: Compilation

You need to set up task.json for compilation of your cpp file

or simply type in the following command in the command window

g++ -g file.cpp -o file.exe

to generate a debuggable .exe file

Step 2: Set up the launch.json file

To enable debugging, you will need to generate a launch.json file

follow the launch.json example or google others

Step 3: Press (Ctrl+F5) to start compiling

this launch.json file will launch the configuration when you press the shortcut (Ctrl+F5)

Enjoy it!

ps. For those who want to set up tasks.json, you can read this from vscode official (-> TypeScript Hello World)

How do I install command line MySQL client on mac?

install MySQLWorkbench, then

export PATH=$PATH:/Applications/MySQLWorkbench.app/Contents/MacOS

PHP - warning - Undefined property: stdClass - fix?

Depending on whether you're looking for a member or method, you can use either of these two functions to see if a member/method exists in a particular object:

http://php.net/manual/en/function.method-exists.php

http://php.net/manual/en/function.property-exists.php

More generally if you want all of them:

http://php.net/manual/en/function.get-object-vars.php

Checking if a key exists in a JS object

Use the in operator:

testArray = 'key1' in obj;

Sidenote: What you got there, is actually no jQuery object, but just a plain JavaScript Object.

Remove Backslashes from Json Data in JavaScript

In React Native , This worked for me

name = "hi \n\ruser"
name.replace( /[\r\n]+/gm, ""); // hi user

Check whether a variable is a string in Ruby

In addition to the other answers, Class defines the method === to test whether an object is an instance of that class.

  • o.class class of o.
  • o.instance_of? c determines whether o.class == c
  • o.is_a? c Is o an instance of c or any of it's subclasses?
  • o.kind_of? c synonym for *is_a?*
  • c === o for a class or module, determine if *o.is_a? c* (String === "s" returns true)

Create a rounded button / button with border-radius in Flutter

You can always use material button if you are using Material App as your main Widget.

Padding(
  padding: EdgeInsets.symmetric(vertical: 16.0),
  child: Material(
    borderRadius: BorderRadius.circular(30.0),//Set this up for rounding corners.
    shadowColor: Colors.lightBlueAccent.shade100,
    child: MaterialButton(
      minWidth: 200.0,
      height: 42.0,
      onPressed: (){//Actions here//},
      color: Colors.lightBlueAccent,
      child: Text('Log in', style: TextStyle(color: Colors.white),),
    ),
  ),
)

JavaScript getElementByID() not working

At the point you are calling your function, the rest of the page has not rendered and so the element is not in existence at that point. Try calling your function on window.onload maybe. Something like this:

<html>
<head>
    <title></title>
    <script type="text/javascript">
        window.onload = function(){
           var refButton = document.getElementById("btnButton");

            refButton.onclick = function() {
                alert('I am clicked!');
            }
        };
    </script>
</head>
<body>
    <form id="form1">
    <div>
        <input id="btnButton" type="button" value="Click me"/>
    </div>
    </form>
</body>
</html>

PHP : send mail in localhost

I spent hours on this. I used to not get errors but mails were never sent. Finally I found a solution and I would like to share it.

<?php
include 'nav.php';
/*
    Download PhpMailer from the following link:
    https://github.com/Synchro/PHPMailer (CLick on Download zip on the right side)
    Extract the PHPMailer-master folder into your xampp->htdocs folder
    Make changes in the following code and its done :-)

    You will receive the mail with the name Root User.
    To change the name, go to class.phpmailer.php file in your PHPMailer-master folder,
    And change the name here: 
    public $FromName = 'Root User';
*/
require("PHPMailer-master/PHPMailerAutoload.php"); //or select the proper destination for this file if your page is in some   //other folder
ini_set("SMTP","ssl://smtp.gmail.com"); 
ini_set("smtp_port","465"); //No further need to edit your configuration files.
$mail = new PHPMailer();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->SMTPSecure = "ssl";
$mail->Username = "[email protected]"; //account with which you want to send mail. Or use this account. i dont care :-P
$mail->Password = "trials.php.php"; //this account's password.
$mail->Port = "465";
$mail->isSMTP();  // telling the class to use SMTP
$rec1="[email protected]"; //receiver. email addresses to which u want to send the mail.
$mail->AddAddress($rec1);
$mail->Subject  = "Eventbook";
$mail->Body     = "Hello hi, testing";
$mail->WordWrap = 200;
if(!$mail->Send()) {
echo 'Message was not sent!.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo  //Fill in the document.location thing
'<script type="text/javascript">
                        if(confirm("Your mail has been sent"))
                        document.location = "/";
        </script>';
}
?>

How can I format the output of a bash command in neat columns

While awk's printf can be used, you may want to look into pr or (on BSDish systems) rs for formatting.

how to call a variable in code behind to aspx page

The HelloFromCsharp.aspx look like this

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="HelloFromCsharp.aspx.cs" Inherits="Test.HelloFromCsharp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <p>
       <%= clients%>
    </p>
    </form>
</body>
</html>

And the HelloFromCsharp.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Test
{
    public partial class HelloFromCsharp : System.Web.UI.Page
    {
        public string clients;
        protected void Page_Load(object sender, EventArgs e)
        {
            clients = "Hello From C#";
        }
    }
}

How to resolve 'npm should be run outside of the node repl, in your normal shell'

Do not run the application using node.js icon.

Go to All Programmes->Node.js->Node.js command prompt.

Below is example screen shot.

enter image description here

enter image description here

How to compare only date components from DateTime in EF?

//Note for Linq Users/Coders

This should give you the exact comparison for checking if a date falls within range when working with input from a user - date picker for example:

((DateTime)ri.RequestX.DateSatisfied).Date >= startdate.Date &&
        ((DateTime)ri.RequestX.DateSatisfied).Date <= enddate.Date

where startdate and enddate are values from a date picker.

ssl_error_rx_record_too_long and Apache SSL

I had a messed up virtual host config. Remember you need one virtual host without SSL for port 80, and another one with SSL for port 443. You cannot have both in one virtual host, as the webmin-generated config tried to do.

Remove Server Response Header IIS7

Try setting the HKLM\SYSTEM\CurrentControlSet\Services\HTTP\Parameters\DisableServerHeader registry entry to a REG_DWORD of 1.

413 Request Entity Too Large - File Upload Issue

sudo nano /etc/nginx/nginx.conf

Then add a line in the http section

http {
    client_max_body_size 100M;
}

don't use MB only M.

systemctl restart nginx

then for php location

sudo gedit /etc/php5/fpm/php.ini

for nowdays maximum use php 7.0 or higher

sudo nano /etc/php/7.2/fpm/php.ini     //7.3,7.2 or 7.1 which php you use

check those increasing by your desire .

memory_limit = 128M 
post_max_size = 20M  
upload_max_filesize = 10M

restart php-fpm

service php-fpm restart 

Remove item from list based on condition

Using linq:

prods.Remove( prods.Single( s => s.ID == 1 ) );

Maybe you even want to use SingleOrDefault() and check if the element exists at all ...

EDIT:
Since stuff is a struct, SingleOrDefault() will not return null. But it will return default( stuff ), which will have an ID of 0. When you don't have an ID of 0 for your normal stuff-objects you can query for this ID:

var stuffToRemove = prods.SingleOrDefault( s => s.ID == 1 )
if( stuffToRemove.ID != 0 )
{
    prods.Remove( stuffToRemove );
}

What is the difference between char s[] and char *s?

As an addition, consider that, as for read-only purposes the use of both is identical, you can access a char by indexing either with [] or *(<var> + <index>) format:

printf("%c", x[1]);     //Prints r

And:

printf("%c", *(x + 1)); //Prints r

Obviously, if you attempt to do

*(x + 1) = 'a';

You will probably get a Segmentation Fault, as you are trying to access read-only memory.

How to get all values from python enum class?

This is basically available in a 'protected' attribute of the Enum class:

list(Color._value2member_map_.keys())

Attaching click event to a JQuery object not yet added to the DOM

I am really surprised that no one has posted this yet

$(document).on('click','#my-butt', function(){
   console.log('document is always there');
}) 

If you are unsure about what elements are going to be on that page at that time just attach it to document.

Note: this is sub-optimal from performance perspective - to get maximum speed one should try to attach to the nearest parent of element that is going to be inserted.

How do you do exponentiation in C?

The non-recursive version of the function is not too hard - here it is for integers:

long powi(long x, unsigned n)
{
    long p = x;
    long r = 1;

    while (n > 0)
    {
        if (n % 2 == 1)
            r *= p;
        p *= p;
        n /= 2;
    }

    return(r);
}

(Hacked out of code for raising a double value to an integer power - had to remove the code to deal with reciprocals, for example.)

MySQL "ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)"

Note: I had the same problem, and it was because the referenced field was in a different collation in the 2 different tables (they had exact same type).

Make sure all your referenced fields have the same type AND the same collation!

Need to make a clickable <div> button

Just use an <a> by itself, set it to display: block; and set width and height. Get rid of the <span> and <div>. This is the semantic way to do it. There is no need to wrap things in <divs> (or any element) for layout. That is what CSS is for.

Demo: http://jsfiddle.net/ThinkingStiff/89Enq/

HTML:

<a id="music" href="Music.html">Music I Like</a>

CSS:

#music {
    background-color: black;
    color: white;
    display: block;
    height: 40px;
    line-height: 40px;
    text-decoration: none;
    width: 100px;
    text-align: center;
}

Output:

enter image description here

Bootstrap 3 truncate long text inside rows of a table in a responsive way

This is what I achieved, but had to set width, and it cannot be percentual.

_x000D_
_x000D_
.trunc{_x000D_
  width:250px; _x000D_
  white-space: nowrap; _x000D_
  overflow: hidden; _x000D_
  text-overflow: ellipsis;_x000D_
}_x000D_
table tr td {_x000D_
padding: 5px_x000D_
}_x000D_
table tr td {_x000D_
background: salmon_x000D_
}_x000D_
table tr td:first-child {_x000D_
background: lightsalmon_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<table>_x000D_
      _x000D_
      <tr>_x000D_
        <td>Quisque dignissim ante in tincidunt gravida. Maecenas lectus turpis</td>_x000D_
      <td>_x000D_
         <div class="trunc">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
         </div>_x000D_
    </td>_x000D_
        </tr>_x000D_
      </table>
_x000D_
_x000D_
_x000D_

or this: http://collaboradev.com/2015/03/28/responsive-css-truncate-and-ellipsis/

iFrame onload JavaScript event

Update

As of jQuery 3.0, the new syntax is just .on:

see this answer here and the code:

$('iframe').on('load', function() {
    // do stuff 
});

How to uncheck checkbox using jQuery Uniform library

Looking at their docs, they have a $.uniform.update feature to refresh a "uniformed" element.

Example: http://jsfiddle.net/r87NH/4/

$("input:checkbox").uniform();

$("body").on("click", "#check1", function () {
    var two = $("#check2").attr("checked", this.checked);
    $.uniform.update(two);
});

How can I create a simple index.html file which lists all files/directories?

If you have a staging server that has directory listing enabled, then you can copy the index.html to the production server.

For example:

wget https://staging/dir/index.html

# do any additional processing on index.html

scp index.html prod/dir

Detecting the onload event of a window opened with window.open

This did the trick for me; full example:

HTML:

<a href="/my-popup.php" class="import">Click for my popup on same domain</a>

Javascript:

(function(){
    var doc = document;

    jQuery('.import').click(function(e){
        e.preventDefault();
        window.popup = window.open(jQuery(this).attr('href'), 'importwindow', 'width=500, height=200, top=100, left=200, toolbar=1');

        window.popup.onload = function() {
            window.popup.onbeforeunload = function(){
                doc.location.reload(true); //will refresh page after popup close
            }
        }
    });
})();

How to find if div with specific id exists in jQuery?

put the id you want to check in jquery is method.

var idcheck = $("selector").is("#id"); 

if(idcheck){ // if the selector contains particular id

// your code if particular Id is there

}
else{
// your code if particular Id is NOT there
}

java.lang.ClassNotFoundException:com.mysql.jdbc.Driver

You can download the latest mysql driver jar from below path, and copy to your classpath or if you are using web server then copy to tomcat/lib or war/web-inf/lib folder.

http://dev.mysql.com/downloads/connector/j/ or

http://mirrors.ibiblio.org/pub/mirrors/maven2/mysql/mysql-connector-java/5.1.10/mysql-connector-java-5.1.10.jar

SELECT where row value contains string MySQL

Use the % wildcard, which matches any number of characters.

SELECT * FROM Accounts WHERE Username LIKE '%query%'

Change Background color (css property) using Jquery

Change Background Color using on click button jquery

Below is the code of jquery, which you can put in your head tag.

jQuery Code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
    $(document).ready(function(){
      $("button").click(function(){
        $("div").addClass("myclass");
      });
    });
</script>

CSS Code:

<style>
    .myclass {
        background-color: red;
        padding: 100px;
        color: #fff;
    }
</style>

HTML Code:

<body>
    <div>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>
    <button>Click Here</button>
</body>

What should my Objective-C singleton look like?

Edit: This implementation obsoleted with ARC. Please have a look at How do I implement an Objective-C singleton that is compatible with ARC? for correct implementation.

All the implementations of initialize I've read in other answers share a common error.

+ (void) initialize {
  _instance = [[MySingletonClass alloc] init] // <----- Wrong!
}

+ (void) initialize {
  if (self == [MySingletonClass class]){ // <----- Correct!
      _instance = [[MySingletonClass alloc] init] 
  }
}

The Apple documentation recommend you check the class type in your initialize block. Because subclasses call the initialize by default. There exists a non-obvious case where subclasses may be created indirectly through KVO. For if you add the following line in another class:

[[MySingletonClass getInstance] addObserver:self forKeyPath:@"foo" options:0 context:nil]

Objective-C will implicitly create a subclass of MySingletonClass resulting in a second triggering of +initialize.

You may think that you should implicitly check for duplicate initialization in your init block as such:

- (id) init { <----- Wrong!
   if (_instance != nil) {
      // Some hack
   }
   else {
      // Do stuff
   }
  return self;
}

But you will shoot yourself in the foot; or worse give another developer the opportunity to shoot themselves in the foot.

- (id) init { <----- Correct!
   NSAssert(_instance == nil, @"Duplication initialization of singleton");
   self = [super init];
   if (self){
      // Do stuff
   }
   return self;
}

TL;DR, here's my implementation

@implementation MySingletonClass
static MySingletonClass * _instance;
+ (void) initialize {
   if (self == [MySingletonClass class]){
      _instance = [[MySingletonClass alloc] init];
   }
}

- (id) init {
   ZAssert (_instance == nil, @"Duplication initialization of singleton");
   self = [super init];
   if (self) {
      // Initialization
   }
   return self;
}

+ (id) getInstance {
   return _instance;
}
@end

(Replace ZAssert with our own assertion macro; or just NSAssert.)

Apache won't start in wamp

I was having the same problem, the mysql service was starting but not the apache service, the main problem about that is one of your virtual hosts isn't config. correctly, all i did was deleted the virtual host that i created "D:\wamp\bin\apache\apache2.4.23\conf\extra\httpd-vhosts, restarted all services apache service started working correctly and so i just went to localhost and added a virtual host automatically and so it worked!!

jQuery: how to change title of document during .ready()?

Like this:

$(document).ready(function ()
{
    document.title = "Hello World!";
});

Be sure to set a default-title if you want your site to be properly indexed by search-engines.

A little tip:

$(function ()
{
    // this is a shorthand for the whole document-ready thing
    // In my opinion, it's more readable 
});

How to check if a table contains an element in Lua?

I can't think of another way to compare values, but if you use the element of the set as the key, you can set the value to anything other than nil. Then you get fast lookups without having to search the entire table.

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

I think from the author's point of view, the main reason is to reduce the overhead for string concatenation.I just read the logger's documentation, you could find following words:

/**
* <p>This form avoids superfluous string concatenation when the logger
* is disabled for the DEBUG level. However, this variant incurs the hidden
* (and relatively small) cost of creating an <code>Object[]</code> before 
  invoking the method,
* even if this logger is disabled for DEBUG. The variants taking
* {@link #debug(String, Object) one} and {@link #debug(String, Object, Object) two}
* arguments exist solely in order to avoid this hidden cost.</p>
*/
*
 * @param format    the format string
 * @param arguments a list of 3 or more arguments
 */
public void debug(String format, Object... arguments);

How to use string.substr() function?

substr(i,j) means that you start from the index i (assuming the first index to be 0) and take next j chars. It does not mean going up to the index j.

Service Temporarily Unavailable Magento?

In Magento 2 You have to remove file located in /var/.maintenance.flag - just realized that after some searching, so i shall share.

Python - IOError: [Errno 13] Permission denied:

For me nothing from above worked. So I solved my problem with this workaround. Just check that you have added SYSTEM in directory folder. I hope it will help somoene.

import os
# create file
@staticmethod
def create_file(path):
    if not os.path.exists(path):
        os.system('echo # > {}'.format(path))

# append lines to the file
split_text = text_file.split('\n')
    for st in split_text:
        os.system('echo {} >> {}'.format(st,path))

Showing all errors and warnings

You can see a detailed description here.

ini_set('display_errors', 1);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

Changelog

  • 5.4.0 E_STRICT became part of E_ALL

  • 5.3.0 E_DEPRECATED and E_USER_DEPRECATED introduced.

  • 5.2.0 E_RECOVERABLE_ERROR introduced.

  • 5.0.0 E_STRICT introduced (not part of E_ALL).

How can I tell gcc not to inline a function?

GCC has a switch called

-fno-inline-small-functions

So use that when invoking gcc. But the side effect is that all other small functions are also non-inlined.

Get the selected value in a dropdown using jQuery.

The above solutions didn't work for me. Here is what I finally came up with:

$( "#ddl" ).find( "option:selected" ).text();           // Text
$( "#ddl" ).find( "option:selected" ).prop("value");    // Value

Rails Root directory path?

For super correctness, you should use:

Rails.root.join('foo','bar')

which will allow your app to work on platforms where / is not the directory separator, should anyone try and run it on one.

Difference between framework vs Library vs IDE vs API vs SDK vs Toolkits?

In other words...

IDE Even your notepad is an IDE. Every software you write/compile code with is an IDE.

Library A bunch of code which simplifies functions/methods for quick use.

API A programming interface for functions/configuration which you work with, its usage is often documented.

SDK Extras and/or for development/testing purposes.

ToolKit Tiny apps for quick use, often GUIs.

GUI Apps with a graphical interface, requires no knowledge of programming unlike APIs.

Framework Bunch of APIs/huge Library/Snippets wrapped in a namespace/or encapsulated from outer scope for compact handling without conflicts with other code.

MVC A design pattern separated in Models, Views and Controllers for huge applications. They are not dependent on each other and can be changed/improved/replaced without to take care of other code.

Example:

Car (Model)
The object that is being presented.
Example in IT: A HTML form.


Camera (View)
Something that is able to see the object(car).
Example in IT: Browser that renders a website with the form.


Driver (Controller)
Someone who drives that car.
Example in IT: Functions which handle form data that's being submitted.

Snippets Small codes of only a few lines, may not be even complete but worth for a quick share.

Plug-ins Exclusive functions for specified frameworks/APIs/libraries only.

Add-ons Additional modules or services for specific GUIs.

Logging POST data from $request_body

The solution below was the best format I found.

log_format postdata escape=json '$remote_addr - $remote_user [$time_local] '
                       '"$request" $status $bytes_sent '
                       '"$http_referer" "$http_user_agent" "$request_body"';
server {
        listen 80;

        server_name api.some.com;

        location / {
         access_log  /var/log/nginx/postdata.log  postdata;
         proxy_pass      http://127.0.0.1:8080;
        }

}

For this input

curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://api.deprod.com/postEndpoint

Generate that great result

201.23.89.149 -  [22/Aug/2019:15:58:40 +0000] "POST /postEndpoint HTTP/1.1" 200 265 "" "curl/7.64.0" "{\"key1\":\"value1\", \"key2\":\"value2\"}"

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

I think you are looking for the IGNORE_DUP_KEY option on your index. Have a look at IGNORE_DUP_KEY ON option documented at http://msdn.microsoft.com/en-us/library/ms186869.aspx which causes duplicate insertion attempts to produce a warning instead of an error.

How can I disable editing cells in a WPF Datagrid?

I see users in comments wondering how to disable cell editing while allowing row deletion : I managed to do this by setting all columns individually to read only, instead of the DataGrid itself.

<DataGrid IsReadOnly="False">
    <DataGrid.Columns>
        <DataGridTextColumn IsReadOnly="True"/>
        <DataGridTextColumn IsReadOnly="True"/>
    </DataGrid.Columns>
</DataGrid>

Make text wrap in a cell with FPDF?

Text Wrap:

The MultiCell is used for print text with multiple lines. It has the same atributes of Cell except for ln and link.

$pdf->MultiCell( 200, 40, $reportSubtitle, 1);

Line Height:

What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).

MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])

You can read the full documentation here.

Multi-Column Join in Hibernate/JPA Annotations

This worked for me . In my case 2 tables foo and boo have to be joined based on 3 different columns.Please note in my case ,in boo the 3 common columns are not primary key

i.e., one to one mapping based on 3 different columns

@Entity
@Table(name = "foo")
public class foo implements Serializable
{
    @Column(name="foocol1")
    private String foocol1;
    //add getter setter
    @Column(name="foocol2")
    private String foocol2;
    //add getter setter
    @Column(name="foocol3")
    private String foocol3;
    //add getter setter
    private Boo boo;
    private int id;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "brsitem_id", updatable = false)
    public int getId()
    {
        return this.id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    @OneToOne
    @JoinColumns(
    {
        @JoinColumn(updatable=false,insertable=false, name="foocol1", referencedColumnName="boocol1"),
        @JoinColumn(updatable=false,insertable=false, name="foocol2", referencedColumnName="boocol2"),
        @JoinColumn(updatable=false,insertable=false, name="foocol3", referencedColumnName="boocol3")
    }
    )
    public Boo getBoo()
    {
        return boo;
    }
    public void setBoo(Boo boo)
    {
        this.boo = boo;
    }
}





@Entity
@Table(name = "boo")
public class Boo implements Serializable
{
    private int id;
    @Column(name="boocol1")
    private String boocol1;
    //add getter setter
    @Column(name="boocol2")
    private String boocol2;
    //add getter setter
    @Column(name="boocol3")
    private String boocol3;
    //add getter setter
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "item_id", updatable = false)
    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
}

How can I stage and commit all files, including newly added files, using a single command?

I use this function:

gcaa() { git add --all && git commit -m "$*" }

In my zsh config file, so i can just do:

> gcaa This is the commit message

To automatically stage and commit all files.

pandas DataFrame: replace nan values with average of columns

Pandas: How to replace NaN (nan) values with the average (mean), median or other statistics of one column

Say your DataFrame is df and you have one column called nr_items. This is: df['nr_items']

If you want to replace the NaN values of your column df['nr_items'] with the mean of the column:

Use method .fillna():

mean_value=df['nr_items'].mean()
df['nr_item_ave']=df['nr_items'].fillna(mean_value)

I have created a new df column called nr_item_ave to store the new column with the NaN values replaced by the mean value of the column.

You should be careful when using the mean. If you have outliers is more recommendable to use the median

Returning JSON from a PHP Script

According to the manual on json_encode the method can return a non-string (false):

Returns a JSON encoded string on success or FALSE on failure.

When this happens echo json_encode($data) will output the empty string, which is invalid JSON.

json_encode will for instance fail (and return false) if its argument contains a non UTF-8 string.

This error condition should be captured in PHP, for example like this:

<?php
header("Content-Type: application/json");

// Collect what you need in the $data variable.

$json = json_encode($data);
if ($json === false) {
    // Avoid echo of empty string (which is invalid JSON), and
    // JSONify the error message instead:
    $json = json_encode(["jsonError" => json_last_error_msg()]);
    if ($json === false) {
        // This should not happen, but we go all the way now:
        $json = '{"jsonError":"unknown"}';
    }
    // Set HTTP response status code to: 500 - Internal Server Error
    http_response_code(500);
}
echo $json;
?>

Then the receiving end should of course be aware that the presence of the jsonError property indicates an error condition, which it should treat accordingly.

In production mode it might be better to send only a generic error status to the client and log the more specific error messages for later investigation.

Read more about dealing with JSON errors in PHP's Documentation.

Undefined symbols for architecture armv7

If you have the flag -ObjC under your Target > Build Settings > Other Linker Flags and you're getting this issue, consider removing it. If you intentionally added it because you need to load some Obj-C code from a static library that wouldn't normally be loaded otherwise, IE, an Obj-C category, then you should use -force_load <path> instead of -ObjC.

<path> should be relative to your Xcode project directory. IE, if your directory structure looks like this:

iOSProject
  + iOSAPI.framework
      + iOSAPI
  + iOSAPI.xcodeproj

Then you should have this flag set for Other Linker Flags:

-force_load iOSAPI.framework/iOSAPI

If you want to include multiple libraries like that, then you should include a separate -force_load line for each of them.

-force_load iOSAPI.framework/iOSAPI
-force_load another.framework/another

SQL how to check that two tables has exactly the same data?

dietbuddha has a nice answer. In cases where you don't have a MINUS or EXCEPT, one option is to do a union all between the tables, group by with all the columns and make sure there is two of everything:

SELECT col1, col2, col3
FROM
(SELECT * FROM tableA
UNION ALL  
SELECT * FROM tableB) data
GROUP BY col1, col2, col3
HAVING count(*)!=2

Assign output to variable in Bash

Same with something more complex...getting the ec2 instance region from within the instance.

INSTANCE_REGION=$(curl -s 'http://169.254.169.254/latest/dynamic/instance-identity/document' | python -c "import sys, json; print json.load(sys.stdin)['region']")

echo $INSTANCE_REGION

Efficient way to rotate a list in python

For a list X = ['a', 'b', 'c', 'd', 'e', 'f'] and a desired shift value of shift less than list length, we can define the function list_shift() as below

def list_shift(my_list, shift):
    assert shift < len(my_list)
    return my_list[shift:] + my_list[:shift]

Examples,

list_shift(X,1) returns ['b', 'c', 'd', 'e', 'f', 'a'] list_shift(X,3) returns ['d', 'e', 'f', 'a', 'b', 'c']

Select single item from a list

Just to complete the answer, If you are using the LINQ syntax, you can just wrap it since it returns an IEnumerable:

(from int x in intList
 where x > 5
 select x * 2).FirstOrDefault()

change cursor from block or rectangle to line?

please Press fn +ins key together

Showing an image from an array of images - Javascript

This is a simple example and try to combine it with yours using some modifications. I prefer you set all the images in one array in order to make your code easier to read and shorter:

var myImage = document.getElementById("mainImage");

var imageArray = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg",
  "_images/image4.jpg","_images/image5.jpg","_images/image6.jpg"];

var imageIndex = 0; 

function changeImage() {
  myImage.setAttribute("src",imageArray[imageIndex]);
  imageIndex = (imageIndex + 1) % imageArray.length;
}

setInterval(changeImage, 5000);

Fit Image in ImageButton in Android

Refer below link and try to find what you really want:

ImageView.ScaleType CENTER Center the image in the view, but perform no scaling.

ImageView.ScaleType CENTER_CROP Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding).

ImageView.ScaleType CENTER_INSIDE Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding).

ImageView.ScaleType FIT_CENTER Scale the image using CENTER.

ImageView.ScaleType FIT_END Scale the image using END.

ImageView.ScaleType FIT_START Scale the image using START.

ImageView.ScaleType FIT_XY Scale the image using FILL.

ImageView.ScaleType MATRIX Scale using the image matrix when drawing.

https://developer.android.com/reference/android/widget/ImageView.ScaleType.html

SVG fill color transparency / alpha?

As a not yet fully standardized solution (though in alignment with the color syntax in CSS3) you can use e.g fill="rgba(124,240,10,0.5)". Works fine in Firefox, Opera, Chrome.

Here's an example.

Bash if statement with multiple conditions throws an error

Use -a (for and) and -o (for or) operations.

tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

Update

Actually you could still use && and || with the -eq operation. So your script would be like this:

my_error_flag=1
my_error_flag_o=1
if [ $my_error_flag -eq 1 ] ||  [ $my_error_flag_o -eq 2 ] || ([ $my_error_flag -eq 1 ] && [ $my_error_flag_o -eq 2 ]); then
      echo "$my_error_flag"
else
    echo "no flag"
fi

Although in your case you can discard the last two expressions and just stick with one or operation like this:

my_error_flag=1
my_error_flag_o=1
if [ $my_error_flag -eq 1 ] ||  [ $my_error_flag_o -eq 2 ]; then
      echo "$my_error_flag"
else
    echo "no flag"
fi

Hash and salt passwords in C#

In answer to this part of the original question "Is there any other C# method for hashing passwords" You can achieve this using ASP.NET Identity v3.0 https://www.nuget.org/packages/Microsoft.AspNet.Identity.EntityFramework/3.0.0-rc1-final

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using System.Security.Principal;

namespace HashTest{


    class Program
    {
        static void Main(string[] args)
        {

            WindowsIdentity wi = WindowsIdentity.GetCurrent();

            var ph = new PasswordHasher<WindowsIdentity>();

            Console.WriteLine(ph.HashPassword(wi,"test"));

            Console.WriteLine(ph.VerifyHashedPassword(wi,"AQAAAAEAACcQAAAAEA5S5X7dmbx/NzTk6ixCX+bi8zbKqBUjBhID3Dg1teh+TRZMkAy3CZC5yIfbLqwk2A==","test"));

        }
    }


}

Windows Forms ProgressBar: Easiest way to start/stop marquee?

To start/stop the animation, you should do this:

To start:

progressBar1.Style = ProgressBarStyle.Marquee;
progressBar1.MarqueeAnimationSpeed = 30;

To stop:

progressBar1.Style = ProgressBarStyle.Continuous;
progressBar1.MarqueeAnimationSpeed = 0;

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

Getting this error, I changed the

c/C++ > Code Generation > Runtime Library to Multi-threaded library (DLL) /MD

for both code project and associated Google Test project. This solved the issue.

Note: all components of the project must have the same definition in c/C++ > Code Generation > Runtime Library. Either DLL or not DLL, but identical.

Unable to load Private Key. (PEM routines:PEM_read_bio:no start line:pem_lib.c:648:Expecting: ANY PRIVATE KEY)

I changed the header and footer of the PEM file to

-----BEGIN RSA PRIVATE KEY-----

and

-----END RSA PRIVATE KEY-----

Finally, it works!

100% width in React Native Flexbox

Here you go:

Just change the line1 style as per below:

line1: {
    backgroundColor: '#FDD7E4',
    width:'100%',
    alignSelf:'center'
}

How to get the difference (only additions) between two files in linux

All of the below is copied directly from @TomOnTime's serverfault answer here:

Show lines that only exist in file a: (i.e. what was deleted from a)

comm -23 a b

Show lines that only exist in file b: (i.e. what was added to b)

comm -13 a b

Show lines that only exist in one file or the other: (but not both)

comm -3 a b | sed 's/^\t//'

(Warning: If file a has lines that start with TAB, it (the first TAB) will be removed from the output.)

NOTE: Both files need to be sorted for "comm" to work properly. If they aren't already sorted, you should sort them:

sort <a >a.sorted
sort <b >b.sorted
comm -12 a.sorted b.sorted

If the files are extremely long, this may be quite a burden as it requires an extra copy and therefore twice as much disk space.

Edit: note that the command can be written more concisely using process substitution (thanks to @phk for the comment):

comm -12 <(sort < a) <(sort < b)

How to replace all spaces in a string

takes care of multiple white spaces and replaces it for a single character

myString.replace(/\s+/g, "-")

http://jsfiddle.net/aC5ZW/340/

std::string to float or double

My Problem:

  1. Locale independent string to double (decimal separator always '.')
  2. Error detection if string conversion fails

My solution (uses the Windows function _wcstod_l):

// string to convert. Note: decimal seperator is ',' here
std::wstring str = L"1,101";

// Use this for error detection
wchar_t* stopString;

// Create a locale for "C". Thus a '.' is expected as decimal separator
double dbl = _wcstod_l(str.c_str(), &stopString, _create_locale(LC_ALL, "C")); 

if (wcslen(stopString) != 0)
{
    // ... error handling ... we'll run into this because of the separator
}

HTH ... took me pretty long to get to this solution. And I still have the feeling that I don't know enough about string localization and stuff...

Get values from an object in JavaScript

I am sorry that your concluding question is not that clear but you are wrong from the very first line. The variable data is an Object not an Array

To access the attributes of an object is pretty easy:

alert(data.second);

But, if this does not completely answer your question, please clarify it and post back.

Thanks !

CSS text-decoration underline color

(for fellow googlers, copied from duplicate question) This answer is outdated since text-decoration-color is now supported by most modern browsers.

You can do this via the following CSS rule as an example:

text-decoration-color:green


If this rule isn't supported by an older browser, you can use the following solution:

Setting your word with a border-bottom:

a:link {
  color: red;
  text-decoration: none;
  border-bottom: 1px solid blue;
}
a:hover {
 border-bottom-color: green;
}

Best way to check if column returns a null value (from database to .net application)

Use DBNull.Value.Equals on the object without converting it to a string.

Here's an example:

   if (! DBNull.Value.Equals(row[fieldName])) 
   {
      //not null
   }
   else
   {
      //null
   }

How to undo local changes to a specific file

You don't want git revert. That undoes a previous commit. You want git checkout to get git's version of the file from master.

git checkout -- filename.txt

In general, when you want to perform a git operation on a single file, use -- filename.



2020 Update

Git introduced a new command git restore in version 2.23.0. Therefore, if you have git version 2.23.0+, you can simply git restore filename.txt - which does the same thing as git checkout -- filename.txt. The docs for this command do note that it is currently experimental.

Double vs. BigDecimal?

If you are dealing with calculation, there are laws on how you should calculate and what precision you should use. If you fail that you will be doing something illegal. The only real reason is that the bit representation of decimal cases are not precise. As Basil simply put, an example is the best explanation. Just to complement his example, here's what happens:

static void theDoubleProblem1() {
    double d1 = 0.3;
    double d2 = 0.2;
    System.out.println("Double:\t 0,3 - 0,2 = " + (d1 - d2));

    float f1 = 0.3f;
    float f2 = 0.2f;
    System.out.println("Float:\t 0,3 - 0,2 = " + (f1 - f2));

    BigDecimal bd1 = new BigDecimal("0.3");
    BigDecimal bd2 = new BigDecimal("0.2");
    System.out.println("BigDec:\t 0,3 - 0,2 = " + (bd1.subtract(bd2)));
}

Output:

Double:  0,3 - 0,2 = 0.09999999999999998
Float:   0,3 - 0,2 = 0.10000001
BigDec:  0,3 - 0,2 = 0.1

Also we have that:

static void theDoubleProblem2() {
    double d1 = 10;
    double d2 = 3;
    System.out.println("Double:\t 10 / 3 = " + (d1 / d2));

    float f1 = 10f;
    float f2 = 3f;
    System.out.println("Float:\t 10 / 3 = " + (f1 / f2));

    // Exception! 
    BigDecimal bd3 = new BigDecimal("10");
    BigDecimal bd4 = new BigDecimal("3");
    System.out.println("BigDec:\t 10 / 3 = " + (bd3.divide(bd4)));
}

Gives us the output:

Double:  10 / 3 = 3.3333333333333335
Float:   10 / 3 = 3.3333333
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion

But:

static void theDoubleProblem2() {
    BigDecimal bd3 = new BigDecimal("10");
    BigDecimal bd4 = new BigDecimal("3");
    System.out.println("BigDec:\t 10 / 3 = " + (bd3.divide(bd4, 4, BigDecimal.ROUND_HALF_UP)));
}

Has the output:

BigDec:  10 / 3 = 3.3333 

Drag and drop elements from list into separate blocks

_x000D_
_x000D_
 function dragStart(event) {_x000D_
            event.dataTransfer.setData("Text", event.target.id);_x000D_
        }_x000D_
_x000D_
        function allowDrop(event) {_x000D_
            event.preventDefault();_x000D_
        }_x000D_
_x000D_
        function drop(event) {_x000D_
            $("#maincontainer").append("<br/><table style='border:1px solid black; font-size:20px;'><tr><th>Name</th><th>Country</th><th>Experience</th><th>Technologies</th></tr><tr><td>  Bhanu Pratap   </td><td> India </td><td>  3 years   </td><td>  Javascript,Jquery,AngularJS,ASP.NET C#, XML,HTML,CSS,Telerik,XSLT,AJAX,etc...</td></tr></table>");_x000D_
        }
_x000D_
 .droptarget {_x000D_
            float: left;_x000D_
            min-height: 100px;_x000D_
            min-width: 200px;_x000D_
            border: 1px solid black;_x000D_
            margin: 15px;_x000D_
            padding: 10px;_x000D_
            border: 1px solid #aaaaaa;_x000D_
        }_x000D_
_x000D_
        [contentEditable=true]:empty:not(:focus):before {_x000D_
            content: attr(data-text);_x000D_
        }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>_x000D_
<div class="droptarget" ondrop="drop(event)" ondragover="allowDrop(event)">_x000D_
        <p ondragstart="dragStart(event)" draggable="true" id="dragtarget">Drag Table</p>_x000D_
    </div>_x000D_
_x000D_
    <div id="maincontainer" contenteditable=true data-text="Drop here..." class="droptarget" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
_x000D_
_x000D_
_x000D_

  1. this is just simple here i'm appending html table into a div at the end
  2. we can achieve this or any thing with a simple concept of calling a JavaScript function when we want (here on drop.)
  3. In this example you can drag & drop any number of tables, new table will be added below the last table exists in the div other wise it will be the first table in the div.
  4. here we can add text between tables or we can say the section where we drop tables is editable we can type text between tables. enter image description here

Thanks... :)

Where is Java's Array indexOf?

int findIndex(int myElement, int[] someArray){
 int index = 0;
 for(int n: someArray){
   if(myElement == n) return index;
   else index++;
 }
}

Note: you can use this method for arrays of type int, you can also use this algorithm for other types with minor changes

How to write a test which expects an Error to be thrown in Jasmine?

For coffeescript lovers

expect( => someMethodCall(arg1, arg2)).toThrow()

Create a custom callback in JavaScript

It is good practice to make sure the callback is an actual function before attempting to execute it:

if (callback && typeof(callback) === "function") {

  callback();
}

How to center the text in a JLabel?

myLabel.setHorizontalAlignment(SwingConstants.CENTER);
myLabel.setVerticalAlignment(SwingConstants.CENTER);

If you cannot reconstruct the label for some reason, this is how you edit these properties of a pre-existent JLabel.

Valid characters of a hostname?

It depends on whether you process IDNs before or after the IDN toASCII algorithm (that is, do you see the domain name pa??de??µa.d???µ? in Greek or as xn--hxajbheg2az3al.xn--jxalpdlp?).

In the latter case—where you are handling IDNs through the punycode—the old RFC 1123 rules apply:

U+0041 through U+005A (A-Z), U+0061 through U+007A (a-z) case folded as each other, U+0030 through U+0039 (0-9) and U+002D (-).

and U+002E (.) of course; the rules for labels allow the others, with dots between labels.

If you are seeing it in IDN form, the allowed characters are much varied, see http://unicode.org/reports/tr36/idn-chars.html for a handy chart of all valid characters.

Chances are your network code will deal with the punycode, but your display code (or even just passing strings to and from other layers) with the more human-readable form as nobody running a server on the ????????. domain wants to see their server listed as being on .xn--mgberp4a5d4ar.

What is the 'override' keyword in C++ used for?

override is a C++11 keyword which means that a method is an "override" from a method from a base class. Consider this example:

   class Foo
   {
   public:
        virtual void func1();
   }

   class Bar : public Foo
   {
   public:
        void func1() override;
   }

If B::func1() signature doesn't equal A::func1() signature a compilation error will be generated because B::func1() does not override A::func1(), it will define a new method called func1() instead.

Bash mkdir and subfolders

To create multiple sub-folders

mkdir -p parentfolder/{subfolder1,subfolder2,subfolder3}

How to reliably open a file in the same directory as a Python script

Ok here is what I do

sys.argv is always what you type into the terminal or use as the file path when executing it with python.exe or pythonw.exe

For example you can run the file text.py several ways, they each give you a different answer they always give you the path that python was typed.

    C:\Documents and Settings\Admin>python test.py
    sys.argv[0]: test.py
    C:\Documents and Settings\Admin>python "C:\Documents and Settings\Admin\test.py"
    sys.argv[0]: C:\Documents and Settings\Admin\test.py

Ok so know you can get the file name, great big deal, now to get the application directory you can know use os.path, specifically abspath and dirname

    import sys, os
    print os.path.dirname(os.path.abspath(sys.argv[0]))

That will output this:

   C:\Documents and Settings\Admin\

it will always output this no matter if you type python test.py or python "C:\Documents and Settings\Admin\test.py"

The problem with using __file__ Consider these two files test.py

import sys
import os

def paths():
        print "__file__: %s" % __file__
        print "sys.argv: %s" % sys.argv[0]

        a_f = os.path.abspath(__file__)
        a_s = os.path.abspath(sys.argv[0])

        print "abs __file__: %s" % a_f
        print "abs sys.argv: %s" % a_s

if __name__ == "__main__":
    paths()

import_test.py

import test
import sys

test.paths()

print "--------"
print __file__
print sys.argv[0]

Output of "python test.py"

C:\Documents and Settings\Admin>python test.py
__file__: test.py
sys.argv: test.py
abs __file__: C:\Documents and Settings\Admin\test.py
abs sys.argv: C:\Documents and Settings\Admin\test.py

Output of "python test_import.py"

C:\Documents and Settings\Admin>python test_import.py
__file__: C:\Documents and Settings\Admin\test.pyc
sys.argv: test_import.py
abs __file__: C:\Documents and Settings\Admin\test.pyc
abs sys.argv: C:\Documents and Settings\Admin\test_import.py
--------
test_import.py
test_import.py

So as you can see file gives you always the python file it is being run from, where as sys.argv[0] gives you the file that you ran from the interpreter always. Depending on your needs you will need to choose which one best fits your needs.

Making an array of integers in iOS

If the order of your integers is not required, and if there are only unique values

you can also use NSIndexSet or NSMutableIndexSet You will be able to easily add and remove integers, or check if your array contains an integer with

- (void)addIndex:(NSUInteger)index
- (void)removeIndex:(NSUInteger)index
- (BOOL)containsIndexes:(NSIndexSet *)indexSet

Check the documentation for more info.

How to sort an array of objects by multiple fields?

Here's an extensible way to sort by multiple fields.

homes.sort(function(left, right) {
    var city_order = left.city.localeCompare(right.city);
    var price_order = parseInt(left.price) - parseInt(right.price);
    return city_order || -price_order;
});

Notes

  • A function passed to array sort is expected to return negative, zero, positive to indicate less, equal, greater.
  • a.localeCompare(b) is universally supported for strings, and returns -1,0,1 if a<b,a==b,a>b.
  • Subtraction works on numeric fields, because a - b gives -,0,+ if a<b,a==b,a>b.
  • || in the last line gives city priority over price.
  • Negate to reverse order in any field, as in -price_order
  • Date comparison, var date_order = new Date(left.date) - new Date(right.date); works like numerics because date math turns into milliseconds since 1970.
  • Add fields into the or-chain, return city_order || -price_order || date_order;
  • Subtraction works on boolean. I suggest you make it explicit, var goodness_order = Boolean(left.is_good) - Boolean(right.is_good)

Display help message with python argparse when script is called without any arguments

The cleanest solution will be to manually pass default argument if none were given on the command line:

parser.parse_args(args=None if sys.argv[1:] else ['--help'])

Complete example:

import argparse, sys

parser = argparse.ArgumentParser()
parser.add_argument('--host', default='localhost', help='Host to connect to')
# parse arguments
args = parser.parse_args(args=None if sys.argv[1:] else ['--help'])

# use your args
print("connecting to {}".format(args.host))

This will print complete help (not short usage) if called w/o arguments.

How to search JSON tree with jQuery

Once you have the JSON loaded into a JavaScript object, it's no longer a jQuery problem but is now a JavaScript problem. In JavaScript you could for instance write a search such as:

var people = myJson["people"];
var persons = people["person"];
for(var i=0; i < persons.length; ++i) {
    var person_i = persons[i];
    if(person_i["name"] == mySearchForName) {
        // found ! do something with 'person_i'.
        break;
    }
}
// not found !

Read file data without saving it in Flask

We simply did:

import io
from pathlib import Path

    def test_my_upload(self, accept_json):
        """Test my uploads endpoint for POST."""
        data = {
            "filePath[]": "/tmp/bin",
            "manifest[]": (io.StringIO(str(Path(__file__).parent /
                                           "path_to_file/npmlist.json")).read(),
                           'npmlist.json'),
        }
        headers = {
            'a': 'A',
            'b': 'B'
        }
        res = self.client.post(api_route_for('/test'),
                               data=data,
                               content_type='multipart/form-data',
                               headers=headers,
                               )
        assert res.status_code == 200

Xcode/Simulator: How to run older iOS version?

To add previous iOS simulator to Xcode 4.2, you need old xcode_3.2.6_and_ios_sdk_4.3.dmg (or similar version) installer file and do as following:

  • Mount the xcode_3.2.6_and_ios_sdk_4.3.dmg file
  • Open mounting disk image and choose menu: Go->Go to Folder...
  • Type /Volumes/Xcode and iOS SDK/Packages/ then click Go. There are many packages and find to iPhoneSimulatorSDK(version).pkg
  • Double click to install package you want to add and wait for installer displays.
  • In Installer click Continue and choose destination, Choose folder...
  • Explorer shows and select Developer folder and click Choose
  • Install and repeat with other simulator as you need.
  • Restart Xcode.

Now there are a list of your installed simulator.

C#: How to add subitems in ListView

Suppose you have a List Collection containing many items to show in a ListView, take the following example that iterates through the List Collection:

foreach (Inspection inspection in anInspector.getInspections())
  {
    ListViewItem item = new ListViewItem();
    item.Text=anInspector.getInspectorName().ToString();
    item.SubItems.Add(inspection.getInspectionDate().ToShortDateString());
    item.SubItems.Add(inspection.getHouse().getAddress().ToString());
    item.SubItems.Add(inspection.getHouse().getValue().ToString("C"));
    listView1.Items.Add(item);
  }

That code produces the following output in the ListView (of course depending how many items you have in the List Collection):

Basically the first column is a listviewitem containing many subitems (other columns). It may seem strange but listview is very flexible, you could even build a windows-like file explorer with it!

Display Parameter(Multi-value) in Report

Hopefully someone else finds this useful:

Using the Join is the best way to use a multi-value parameter. But what if you want to have an efficient 'Select All'? If there are 100s+ then the query will be very inefficient.

To solve this instead of using a SQL Query as is, change it to using an expression (click the Fx button top right) then build your query something like this (speech marks are necessary):

= "Select * from tProducts Where 1 = 1 " 
IIF(Parameters!ProductID.Value(0)=-1,Nothing," And ProductID In (" & Join(Parameters!ProductID.Value,"','") & ")")

In your Parameter do the following:

    SELECT -1 As ProductID, 'All' as ProductName Union All
    Select  
    tProducts.ProductID,tProducts.ProductName
    FROM
    tProducts

By building the query as an expression means you can make the SQL Statement more efficient but also handle the difficulty SQL Server has with handling values in an 'In' statement.

Div Background Image Z-Index Issue

Set your header and footer position to "absolute" and that should do the trick. Hope it helps and good luck with your project!

get keys of json-object in JavaScript

var jsonData = [{"person":"me","age":"30"},{"person":"you","age":"25"}];

for(var i in jsonData){
    var key = i;
    var val = jsonData[i];
    for(var j in val){
        var sub_key = j;
        var sub_val = val[j];
        console.log(sub_key);
    }
}

EDIT

var jsonObj = {"person":"me","age":"30"};
Object.keys(jsonObj);  // returns ["person", "age"]

Object has a property keys, returns an Array of keys from that Object

Chrome, FF & Safari supports Object.keys

How to make a pure css based dropdown menu?

see this is pure css bases dropdown menu:-

HTML

<ul id="menu">
      <li><a href="">Home</a></li>
      <li><a href="">About Us</a>
        <ul>
        <li><a href="">The Team</a></li>
        <li><a href="">History</a></li>
        <li><a href="">Vision</a></li>
        </ul>
      </li>
      <li><a href="">Products</a>
        <ul>
        <li><a href="">Cozy Couch</a></li>
        <li><a href="">Great Table</a></li>
        <li><a href="">Small Chair</a></li>
        <li><a href="">Shiny Shelf</a></li>
        <li><a href="">Invisible Nothing</a></li>
        </ul>
      </li>
      <li><a href="">Contact</a>
        <ul>
        <li><a href="">Online</a></li>
        <li><a href="">Right Here</a></li>
        <li><a href="">Somewhere Else</a></li>
        </ul>
      </li>
    </ul>

CSS

ul
{
    font-family: Arial, Verdana;
    font-size: 14px;
    margin: 0;
    padding: 0;
    list-style: none;
}

ul li
{
    display: block;
    position: relative;
    float: left;
}

li ul
{
    display: none;
}

ul li a 
{
    display: block;
    text-decoration: none;
    color: #ffffff;
    border-top: 1px solid #ffffff;
    padding: 5px 15px 5px 15px;
    background: #2C5463;
    margin-left: 1px;
    white-space: nowrap;
}

ul li a:hover 
{
    background: #617F8A;
}
li:hover ul 
{
    display: block;
    position: absolute;
}

li:hover li
{
    float: none;
    font-size: 11px;
}

li:hover a 
{
    background: #617F8A;
}

li:hover li a:hover 
{
    background: #95A9B1;
}

see the demo:- http://jsfiddle.net/XPE3w/7/

How to delete all files older than 3 days when "Argument list too long"?

Another solution for the original question, esp. useful if you want to remove only SOME of the older files in a folder, would be smth like this:

find . -name "*.sess" -mtime +100 

and so on.. Quotes block shell wildcards, thus allowing you to "find" millions of files :)

Properties file with a list as the value for an individual key

There's probably a another way or better. But this is how I do this in Spring Boot.

My property file contains the following lines. "," is the delimiter in each line.

mml.pots=STDEP:DETY=LI3;,STDEP:DETY=LIMA;
mml.isdn.grunntengingar=STDEP:DETY=LIBAE;,STDEP:DETY=LIBAMA;
mml.isdn.stofntengingar=STDEP:DETY=LIPRAE;,STDEP:DETY=LIPRAM;,STDEP:DETY=LIPRAGS;,STDEP:DETY=LIPRVGS;

My server config

@Configuration
public class ServerConfig {

    @Inject
    private Environment env;

    @Bean
    public MMLProperties mmlProperties() {
        MMLProperties properties = new MMLProperties();
        properties.setMmmlPots(env.getProperty("mml.pots"));
        properties.setMmmlPots(env.getProperty("mml.isdn.grunntengingar"));
        properties.setMmmlPots(env.getProperty("mml.isdn.stofntengingar"));
        return properties;
    }
}

MMLProperties class.

public class MMLProperties {
    private String mmlPots;
    private String mmlIsdnGrunntengingar;
    private String mmlIsdnStofntengingar;

    public MMLProperties() {
        super();
    }

    public void setMmmlPots(String mmlPots) {
        this.mmlPots = mmlPots;
    }

    public void setMmlIsdnGrunntengingar(String mmlIsdnGrunntengingar) {
        this.mmlIsdnGrunntengingar = mmlIsdnGrunntengingar;
    }

    public void setMmlIsdnStofntengingar(String mmlIsdnStofntengingar) {
        this.mmlIsdnStofntengingar = mmlIsdnStofntengingar;
    }

    // These three public getXXX functions then take care of spliting the properties into List
    public List<String> getMmmlCommandForPotsAsList() {
        return getPropertieAsList(mmlPots);
    }

    public List<String> getMmlCommandsForIsdnGrunntengingarAsList() {
        return getPropertieAsList(mmlIsdnGrunntengingar);
    }

    public List<String> getMmlCommandsForIsdnStofntengingarAsList() {
        return getPropertieAsList(mmlIsdnStofntengingar);
    }

    private List<String> getPropertieAsList(String propertie) {
        return ((propertie != null) || (propertie.length() > 0))
        ? Arrays.asList(propertie.split("\\s*,\\s*"))
        : Collections.emptyList();
    }
}

Then in my Runner class I Autowire MMLProperties

@Component
public class Runner implements CommandLineRunner {

    @Autowired
    MMLProperties mmlProperties;

    @Override
    public void run(String... arg0) throws Exception {
        // Now I can call my getXXX function to retrieve the properties as List
        for (String command : mmlProperties.getMmmlCommandForPotsAsList()) {
            System.out.println(command);
        }
    }
}

Hope this helps

Groovy / grails how to determine a data type?

somObject instanceof Date

should be

somObject instanceOf Date

jQuery when element becomes visible

I like plugin https://github.com/hazzik/livequery It works without timers!

Simple usage

$('.some:visible').livequery( function(){ ... } );

But you need to fix a mistake. Replace line

$jQlq.registerPlugin('append', 'prepend', 'after', 'before', 'wrap', 'attr', 'removeAttr', 'addClass', 'removeClass', 'toggleClass', 'empty', 'remove', 'html', 'prop', 'removeProp');

to

$jQlq.registerPlugin('show', 'append', 'prepend', 'after', 'before', 'wrap', 'attr', 'removeAttr', 'addClass', 'removeClass', 'toggleClass', 'empty', 'remove', 'html', 'prop', 'removeProp');

What is the best way to get all the divisors of a number?

To expand on what Shimi has said, you should only be running your loop from 1 to the square root of n. Then to find the pair, do n / i, and this will cover the whole problem space.

As was also noted, this is a NP, or 'difficult' problem. Exhaustive search, the way you are doing it, is about as good as it gets for guaranteed answers. This fact is used by encryption algorithms and the like to help secure them. If someone were to solve this problem, most if not all of our current 'secure' communication would be rendered insecure.

Python code:

import math

def divisorGenerator(n):
    large_divisors = []
    for i in xrange(1, int(math.sqrt(n) + 1)):
        if n % i == 0:
            yield i
            if i*i != n:
                large_divisors.append(n / i)
    for divisor in reversed(large_divisors):
        yield divisor

print list(divisorGenerator(100))

Which should output a list like:

[1, 2, 4, 5, 10, 20, 25, 50, 100]

Creating the checkbox dynamically using JavaScript?

You can create a function:

function changeInputType(oldObj, oTyp, nValue) {
  var newObject = document.createElement('input');
  newObject.type = oTyp;
  if(oldObj.size) newObject.size = oldObj.size;
  if(oldObj.value) newObject.value = nValue;
  if(oldObj.name) newObject.name = oldObj.name;
  if(oldObj.id) newObject.id = oldObj.id;
  if(oldObj.className) newObject.className = oldObj.className;
  oldObj.parentNode.replaceChild(newObject,oldObj);
  return newObject;
}

And you do a call like:

changeInputType(document.getElementById('DATE_RANGE_VALUE'), 'checkbox', 7);

How to delete files recursively from an S3 bucket

In case using AWS-SKD for ruby V2.

s3.list_objects(bucket: bucket_name, prefix: "foo/").contents.each do |obj|
  next if obj.key == "foo/" 
  resp = s3.delete_object({
    bucket: bucket_name,
    key: obj.key,
  })
end

attention please, all "foo/*" under bucket will delete.

How to initialize log4j properly?

Log4j by default looks for a file called log4j.properties or log4j.xml on the classpath.

You can control which file it uses to initialize itself by setting system properties as described here (Look for the "Default Initialization Procedure" section).

For example:

java -Dlog4j.configuration=customName ....

Will cause log4j to look for a file called customName on the classpath.

If you are having problems I find it helpful to turn on the log4j.debug:

-Dlog4j.debug

It will print to System.out lots of helpful information about which file it used to initialize itself, which loggers / appenders got configured and how etc.

The configuration file can be a java properties file or an xml file. Here is a sample of the properties file format taken from the log4j intro documentation page:

log4j.rootLogger=debug, stdout, R

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log

log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1

log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

How do I calculate power-of in C#?

You are looking for the static method Math.Pow().

Reference to a non-shared member requires an object reference occurs when calling public sub

Go to the Declaration of the desired object and mark it Shared.

Friend Shared WithEvents MyGridCustomer As Janus.Windows.GridEX.GridEX

Convert JSON String To C# Object

Convert a JSON string into an object in C#. Using below test case.. its worked for me. Here "MenuInfo" is my C# class object.

JsonTextReader reader = null;
try
{
    WebClient webClient = new WebClient();
    JObject result = JObject.Parse(webClient.DownloadString("YOUR URL"));
    reader = new JsonTextReader(new System.IO.StringReader(result.ToString()));
    reader.SupportMultipleContent = true;
}
catch(Exception)
{}

JsonSerializer serializer = new JsonSerializer();
MenuInfo menuInfo = serializer.Deserialize<MenuInfo>(reader);

Resize a large bitmap file to scaled output file on Android

Why not use the API?

int h = 48; // height in pixels
int w = 48; // width in pixels    
Bitmap scaled = Bitmap.createScaledBitmap(largeBitmap, w, h, true);

how do I change text in a label with swift?

use a simple formula: WHO.WHAT = VALUE

where,

WHO is the element in the storyboard you want to make changes to for eg. label

WHAT is the property of that element you wish to change for eg. text

VALUE is the change that you wish to be displayed

for eg. if I want to change the text from story text to You see a fork in the road in the label as shown in screenshot 1

In this case, our WHO is the label (element in the storyboard), WHAT is the text (property of element) and VALUE will be You see a fork in the road

so our final code will be as follows: Final code

screenshot 1 changes to screenshot 2 once the above code is executed.

I hope this solution helps you solve your issue. Thank you!

ssh : Permission denied (publickey,gssapi-with-mic)

Setting PasswordAuthentication to yes, is not the best way to go , is not as secure as using private and public keys for authentication !

First make sure that that you have the fallowing permissions set, on the server side.

First check your home dir (SERVER SIDE)

[vini@random ~]$ ls -ld ~

drwx------. 3 vini vini 127 Nov 23 15:29 /home/vini

if it is not like this, run

chmod 0700 /home/your_home

Now check .ssh folder

[vini@random ~]$ ls -ld  /home/vini/.ssh/

drwx------. 2 vini vini 29 Nov 23 15:28 /home/vini/.ssh/

if it is not looking like this, run

chmod 0700 /home/your_home/.ssh

now make sure that authorized_keys looks like this

[vini@venon ~]$ ls -ld  /home/vini/.ssh/authorized_keys 

-rw-------. 1 vini vini 393 Nov 23 15:28 /home/vini/.ssh/authorized_keys

or just run

chmod 0600 /home/your_home/.ssh/authorized_keys

After that go to /etc/ssh/sshd_config

For best security set

PermitRootLogin no

PubkeyAuthentication yes

keep as yes for testing purposes

PasswordAuthentication yes

Make sure that

ChallengeResponseAuthentication no

Comment those lines for GSSAPI

# #GSSAPIAuthentication yes
# #GSSAPICleanupCredentials no

Make sure that is set to UsePAM yes

UsePAM yes

now restart sshd service

systemctl restart sshd 

on the client side

cd /home/your_home/.ssh

generate new keys; setting a password is optional but is a good idea

ssh-keygen -t rsa -b 2048  

copy pub key to your server

ssh-copy-id -i id_rsa.pub user_name@server_ip 

start ssh agent 

eval $(ssh-agent)

ssh-add /home/user/.ssh/your_private_key

now your are good to go !

ssh user_name@server_ip

if everything works just fine

make a backup of your private key and then deny PasswordAuthentication

PasswordAuthentication no 

Restart you server

now anyone trying to ssh into your server, without your keys should get

vini@random: Permission denied (publickey).

keep script kids away from your business, and good luck

How to resize an Image C#

Note: this will not work with ASP.Net Core because WebImage depends on System.Web, but on previous versions of ASP.Net I used this snippet many times and was useful.

String ThumbfullPath = Path.GetFileNameWithoutExtension(file.FileName) + "80x80.jpg";
var ThumbfullPath2 = Path.Combine(ThumbfullPath, fileThumb);
using (MemoryStream stream = new MemoryStream(System.IO.File.ReadAllBytes(fullPath)))
{
      var thumbnail = new WebImage(stream).Resize(80, 80);
      thumbnail.Save(ThumbfullPath2, "jpg");
}

Regular expression for matching latitude/longitude coordinates?

Actually Alix Axel, above regex is wrong in latitude, longitude ranges point of view.

Latitude measurements range from –90° to +90° Longitude measurements range from –180° to +180°

So the regex given below validates more accurately.
Also, as per my thought no one should restrict decimal point in latitude/longitude.

^([-+]?\d{1,2}([.]\d+)?),\s*([-+]?\d{1,3}([.]\d+)?)$

OR for Objective C

^([-+]?\\d{1,2}([.]\\d+)?),\\s*([-+]?\\d{1,3}([.]\\d+)?)$

How do I negate a test with regular expressions in a bash script?

You had it right, just put a space between the ! and the [[ like if ! [[

How can I tell if a DOM element is visible in the current viewport?

Here is a function that tells if an element is in visible in the current viewport of a parent element:

function inParentViewport(el, pa) {
    if (typeof jQuery === "function"){
        if (el instanceof jQuery)
            el = el[0];
        if (pa instanceof jQuery)
            pa = pa[0];
    }

    var e = el.getBoundingClientRect();
    var p = pa.getBoundingClientRect();

    return (
        e.bottom >= p.top &&
        e.right >= p.left &&
        e.top <= p.bottom &&
        e.left <= p.right
    );
}

How to connect Bitbucket to Jenkins properly

I had a similar problems, till I got it working. Below is the full listing of the integration:

  1. Generate public/private keys pair: ssh-keygen -t rsa
  2. Copy the public key (~/.ssh/id_rsa.pub) and paste it in Bitbucket SSH keys, in user’s account management console: enter image description here

  3. Copy the private key (~/.ssh/id_rsa) to new user (or even existing one) with private key credentials, in this case, username will not make a difference, so username can be anything: enter image description here

  4. run this command to test if you can get access to Bitbucket account: ssh -T [email protected]

  5. OPTIONAL: Now, you can use your git to to copy repo to your desk without passwjord git clone [email protected]:username/repo_name.git
  6. Now you can enable Bitbucket hooks for Jenkins push notifications and automatic builds, you will do that in 2 steps:

    1. Add an authentication token inside the job/project you configure, it can be anything: enter image description here

    2. In Bitbucket hooks: choose jenkins hooks, and fill the fields as below: enter image description here

Where:

**End point**: username:usertoken@jenkins_domain_or_ip
**Project name**: is the name of job you created on Jenkins
**Token**: Is the authorization token you added in the above steps in your Jenkins' job/project 

Recommendation: I usually add the usertoken as the authorization Token (in both Jenkins Auth Token job configuration and Bitbucket hooks), making them one variable to ease things on myself.

Font is not available to the JVM with Jasper Reports

Create jasper report in multiple languages(Unicode)

1)Install font in ireport desginer

2)create extension of font(we will use it in applications classpath)

3)install font on os(optional)

4)paste all .ttf of font in jre->lib->fonts directory (otherwise web application will throw error font is not available to JVM)

Can you pass parameters to an AngularJS controller on creation?

One way of doing that would be having a separate service that can be used as a 'vessel' for those arguments where they're public data members.

In C, how should I read a text file and print all strings

Instead just directly print the characters onto the console because the text file maybe very large and you may require a lot of memory.

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

int main() {

    FILE *f;
    char c;
    f=fopen("test.txt","rt");

    while((c=fgetc(f))!=EOF){
        printf("%c",c);
    }

    fclose(f);
    return 0;
}

How to create a sticky left sidebar menu using bootstrap 3?

Bootstrap 3

Here is a working left sidebar example:

http://bootply.com/90936 (similar to the Bootstrap docs)

The trick is using the affix component along with some CSS to position it:

  #sidebar.affix-top {
    position: static;
    margin-top:30px;
    width:228px;
  }

  #sidebar.affix {
    position: fixed;
    top:70px;
    width:228px;
  }

EDIT- Another example with footer and affix-bottom


Bootstrap 4

The Affix component has been removed in Bootstrap 4, so to create a sticky sidebar, you can use a 3rd party Affix plugin like this Bootstrap 4 sticky sidebar example, or use the sticky-top class is explained in this answer.

Related: Create a responsive navbar sidebar "drawer" in Bootstrap 4?

Update TextView Every Second

Extending @endian 's answer, you could use a thread and call a method to update the TextView. Below is some code I made up on the spot.

java.util.Date noteTS;
String time, date;
TextView tvTime, tvDate;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.deskclock);

    tvTime = (TextView) findViewById(R.id.tvTime);
    tvDate = (TextView) findViewById(R.id.tvDate);

    Thread t = new Thread() {

        @Override
        public void run() {
            try {
                while (!isInterrupted()) {
                    Thread.sleep(1000);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updateTextView();
                        }
                    });
                }
            } catch (InterruptedException e) {
            }
        }
    };

    t.start();
}

private void updateTextView() {
    noteTS = Calendar.getInstance().getTime();

    String time = "hh:mm"; // 12:00
    tvTime.setText(DateFormat.format(time, noteTS));

    String date = "dd MMMMM yyyy"; // 01 January 2013
    tvDate.setText(DateFormat.format(date, noteTS));
}

How to get request URL in Spring Boot RestController

Add a parameter of type UriComponentsBuilder to your controller method. Spring will give you an instance that's preconfigured with the URI for the current request, and you can then customize it (such as by using MvcUriComponentsBuilder.relativeTo to point at a different controller using the same prefix).

Tomcat: LifecycleException when deploying

I got stuck and problem solved Don't use the path that is "Map Network Drive", but use the \server\folder structure instead

Local variable referenced before assignment?

Put a global statement at the top of your function and you should be good:

def onLoadFinished(result):
    global feed
    ...

To demonstrate what I mean, look at this little test:

x = 0
def t():
    x += 1
t()

this blows up with your exact same error where as:

x = 0
def t():
    global x
    x += 1
t()

does not.

The reason for this is that, inside t, Python thinks that x is a local variable. Furthermore, unless you explicitly tell it that x is global, it will try to use a local variable named x in x += 1. But, since there is no x defined in the local scope of t, it throws an error.

Joining pairs of elements of a list

just to be pythonic :-)

>>> x = ['a1sd','23df','aaa','ccc','rrrr', 'ssss', 'e', '']
>>> [x[i] + x[i+1] for i in range(0,len(x),2)]
['a1sd23df', 'aaaccc', 'rrrrssss', 'e']

in case the you want to be alarmed if the list length is odd you can try:

[x[i] + x[i+1] if not len(x) %2 else 'odd index' for i in range(0,len(x),2)]

Best of Luck