Programs & Examples On #Pax

0

#1292 - Incorrect date value: '0000-00-00'

You have 3 options to make your way:
1. Define a date value like '1970-01-01'
2. Select NULL from the dropdown to keep it blank.
3. Select CURRENT_TIMESTAMP to set current datetime as default value.

How to remove commits from a pull request

So do the following ,

Lets say your branch name is my_branch and this has the extra commits.

  1. git checkout -b my_branch_with_extra_commits (Keeping this branch saved under a different name)
  2. gitk (Opens git console)
  3. Look for the commit you want to keep. Copy the SHA of that commit to a notepad.
  4. git checkout my_branch
  5. gitk (This will open the git console )
  6. Right click on the commit you want to revert to (State before your changes) and click on "reset branch to here"
  7. Do a git pull --rebase origin branch_name_to _merge_to
  8. git cherry-pick <SHA you copied in step 3. >

Now look at the local branch commit history and make sure everything looks good.

Send XML data to webservice using php curl

Previous anwser works fine. I would just add that you dont need to specify CURLOPT_POSTFIELDS as "xmlRequest=" . $input_xml to read your $_POST. You can use file_get_contents('php://input') to get the raw post data as plain XML.

Error LNK2019: Unresolved External Symbol in Visual Studio

When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

If the cookie is generated from script, then you can send the cookie manually along with the cookie from the file(using cookie-file option). For example:

# sending manually set cookie
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: test=cookie"));

# sending cookies from file
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);

In this case curl will send your defined cookie along with the cookies from the file.

If the cookie is generated through javascrript, then you have to trace it out how its generated and then you can send it using the above method(through http-header).

The utma utmc, utmz are seen when cookies are sent from Mozilla. You shouldn't bet worry about these things anymore.

Finally, the way you are doing is alright. Just make sure you are using absolute path for the file names(i.e. /var/dir/cookie.txt) instead of relative one.

Always enable the verbose mode when working with curl. It will help you a lot on tracing the requests. Also it will save lot of your times.

curl_setopt($ch, CURLOPT_VERBOSE, true);

System.Collections.Generic.IEnumerable' does not contain any definition for 'ToList'

You're missing a reference to System.Linq.

Add

using System.Linq

to get access to the ToList() function on the current code file.


To give a little bit of information over why this is necessary, Enumerable.ToList<TSource> is an extension method. Extension methods are defined outside the original class that it targets. In this case, the extension method is defined on System.Linq namespace.

Decorators with parameters?

In my instance, I decided to solve this via a one-line lambda to create a new decorator function:

def finished_message(function, message="Finished!"):

    def wrapper(*args, **kwargs):
        output = function(*args,**kwargs)
        print(message)
        return output

    return wrapper

@finished_message
def func():
    pass

my_finished_message = lambda f: finished_message(f, "All Done!")

@my_finished_message
def my_func():
    pass

if __name__ == '__main__':
    func()
    my_func()

When executed, this prints:

Finished!
All Done!

Perhaps not as extensible as other solutions, but worked for me.

Python 2.6: Class inside a Class?

It sounds like you are talking about aggregation. Each instance of your player class can contain zero or more instances of Airplane, which, in turn, can contain zero or more instances of Flight. You can implement this in Python using the built-in list type to save you naming variables with numbers.

class Flight(object):

    def __init__(self, duration):
        self.duration = duration


class Airplane(object):

    def __init__(self):
        self.flights = []

    def add_flight(self, duration):
        self.flights.append(Flight(duration))


class Player(object):

    def __init__ (self, stock = 0, bank = 200000, fuel = 0, total_pax = 0):
        self.stock = stock
        self.bank = bank
        self.fuel = fuel
        self.total_pax = total_pax
        self.airplanes = []


    def add_planes(self):
        self.airplanes.append(Airplane())



if __name__ == '__main__':
    player = Player()
    player.add_planes()
    player.airplanes[0].add_flight(5)

Tomcat started in Eclipse but unable to connect to http://localhost:8085/

You need to start the Apache Tomcat services.

Win+R --> sevices.msc

Then, search for Apache Tomcat and right click on it and click on Start. This will start the service and then you'll be able to see Apache Tomcat homepage on the localhost .

How to set headers in http get request?

Pay attention that in http.Request header "Host" can not be set via Set method

req.Header.Set("Host", "domain.tld")

but can be set directly:

req.Host = "domain.tld":

req, err := http.NewRequest("GET", "http://10.0.0.1/", nil)
if err != nil {
    ...
}

req.Host = "domain.tld"
client := &http.Client{}
resp, err := client.Do(req)

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

In a conda environment, this is what solved my problem (I was missing cudart64-100.dll:

  1. Downloaded it from dll-files.com/CUDART64_100.DLL

  2. Put it in my conda environment at C:\Users\<user>\Anaconda3\envs\<env name>\Library\bin

That's all it took! You can double check if it's working:

import tensorflow as tf
tf.config.experimental.list_physical_devices('GPU')

Winforms TableLayoutPanel adding rows programmatically

Here's my code for adding a new row to a two-column TableLayoutColumn:

private void AddRow(Control label, Control value)
{
    int rowIndex = AddTableRow();
    detailTable.Controls.Add(label, LabelColumnIndex, rowIndex);
    if (value != null)
    {
        detailTable.Controls.Add(value, ValueColumnIndex, rowIndex);
    }
}

private int AddTableRow()
{
    int index = detailTable.RowCount++;
    RowStyle style = new RowStyle(SizeType.AutoSize);
    detailTable.RowStyles.Add(style);
    return index;
}

The label control goes in the left column and the value control goes in the right column. The controls are generally of type Label and have their AutoSize property set to true.

I don't think it matters too much, but for reference, here is the designer code that sets up detailTable:

this.detailTable.ColumnCount = 2;
this.detailTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.detailTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.detailTable.Dock = System.Windows.Forms.DockStyle.Fill;
this.detailTable.Location = new System.Drawing.Point(0, 0);
this.detailTable.Name = "detailTable";
this.detailTable.RowCount = 1;
this.detailTable.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.detailTable.Size = new System.Drawing.Size(266, 436);
this.detailTable.TabIndex = 0;

This all works just fine. You should be aware that there appear to be some problems with disposing controls from a TableLayoutPanel dynamically using the Controls property (at least in some versions of the framework). If you need to remove controls, I suggest disposing the entire TableLayoutPanel and creating a new one.

Temporary table in SQL server causing ' There is already an object named' error

I usually put these lines at the beginning of my stored procedure, and then at the end.

It is an "exists" check for #temp tables.

IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
begin
        drop table #MyCoolTempTable
end

Full Example:

CREATE PROCEDURE [dbo].[uspTempTableSuperSafeExample]
AS
BEGIN
    SET NOCOUNT ON;


    IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
    BEGIN
            DROP TABLE #MyCoolTempTable
    END


    CREATE TABLE #MyCoolTempTable (
        MyCoolTempTableKey INT IDENTITY(1,1),
        MyValue VARCHAR(128)
    )  

    INSERT INTO #MyCoolTempTable (MyValue)
        SELECT LEFT(@@VERSION, 128)
        UNION ALL SELECT TOP 10 LEFT(name, 128) from sysobjects

    SELECT MyCoolTempTableKey, MyValue FROM #MyCoolTempTable


    IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
    BEGIN
            DROP TABLE #MyCoolTempTable
    END


    SET NOCOUNT OFF;
END
GO

Debugging in Maven?

I found an easy way to do this -

Just enter a command like this -

>mvn -Dtest=TestClassName#methodname -Dmaven.surefire.debug test

It will start listening to 5005 port. Now just create a remote debugging in Eclipse through Debug Configurations for localhost(any host) and port 5005.

Source - https://doc.nuxeo.com/display/CORG/How+to+Debug+a+Test+Run+with+Maven

Font size relative to the user's screen resolution?

Not sure why is this complicated. I would do this basic javascript

<body onresize='document.getElementsByTagName("body")[0].style[ "font-size" ] = document.body.clientWidth*(12/1280) + "px";'>

Where 12 means 12px at 1280 resolution. You decide the value you want here

Using sendmail from bash script for multiple recipients

to use sendmail from the shell script

subject="mail subject"
body="Hello World"
from="[email protected]"
to="[email protected],[email protected]"
echo -e "Subject:${subject}\n${body}" | sendmail -f "${from}" -t "${to}"

How to add header data in XMLHttpRequest when using formdata?

Check to see if the key-value pair is actually showing up in the request:

In Chrome, found somewhere like: F12: Developer Tools > Network Tab > Whatever request you have sent > "view source" under Response Headers

Depending on your testing workflow, if whatever pair you added isn't there, you may just need to clear your browser cache. To verify that your browser is using your most up-to-date code, you can check the page's sources, in Chrome this is found somewhere like: F12: Developer Tools > Sources Tab > YourJavascriptSrc.js and check your code.

But as other answers have said:

xhttp.setRequestHeader(key, value);

should add a key-value pair to your request header, just make sure to place it after your open() and before your send()

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

how to properly display an iFrame in mobile safari

Don't scroll the IFrame page or its content, scroll the parent page. If you control the IFrame content, you can use the iframe-resizer library to turn the iframe element itself into a proper block level element, with a natural/correct/native height. Also, don't attempt to position (fixed, absolute) your iframe in the parent page, or present an iframe in a modal window, especially if it has form elements.

I also suspect that iOS Safari has a non-standards behavior that expands your iframe's height to its natural height, much like the iframe-resizer library will do for desktop browsers, which seem to render responsive iframe content at height 0px or 150px or some other not useful default. If you need to contrain width, try a max-width style inside the iframe.

What is causing this error - "Fatal error: Unable to find local grunt"

None of the above worked for me because i had grunt installed globally (recommended in several of these answers, oddly) and that was messing everything up. Here's what did work:

npm uninstall -g grunt
npm install

Only now was a local grunt installed, and useable, for me.

Git: Pull from other remote

upstream in the github example is just the name they've chosen to refer to that repository. You may choose any that you like when using git remote add. Depending on what you select for this name, your git pull usage will change. For example, if you use:

git remote add upstream git://github.com/somename/original-project.git

then you would use this to pull changes:

git pull upstream master

But, if you choose origin for the name of the remote repo, your commands would be:

To name the remote repo in your local config: git remote add origin git://github.com/somename/original-project.git

And to pull: git pull origin master

ReflectionException: Class ClassName does not exist - Laravel

For some reason I had to run composer dumpautoload -o. Notice flag -o which mean with optimization. I don't have any idea why it works only with it but give it a try. Perhaps it helps someone.

What is the difference between Integer and int in Java?

In Java int is a primitive data type while Integer is a Helper class, it is use to convert for one data type to other.

For example:

         double doubleValue = 156.5d;
         Double doubleObject  = new Double(doubleValue);
         Byte myByteValue = doubleObject.byteValue ();
         String myStringValue = doubleObject.toString();

Primitive data types are store the fastest available memory where the Helper class is complex and store in heap memory.

reference from "David Gassner" Java Essential Training.

A TypeScript GUID class?

I found this https://typescriptbcl.codeplex.com/SourceControl/latest

here is the Guid version they have in case the link does not work later.

module System {
    export class Guid {
        constructor (public guid: string) {
            this._guid = guid;
        }

        private _guid: string;

        public ToString(): string {
            return this.guid;
        }

        // Static member
        static MakeNew(): Guid {
            var result: string;
            var i: string;
            var j: number;

            result = "";
            for (j = 0; j < 32; j++) {
                if (j == 8 || j == 12 || j == 16 || j == 20)
                    result = result + '-';
                i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
                result = result + i;
            }
            return new Guid(result);
        }
    }
}

How do you add a scroll bar to a div?

If you want to add a scroll bar using jquery the following will work. If your div had a id of 'mydiv' you could us the following jquery id selector with css property:

jQuery('#mydiv').css("overflow-y", "scroll");

JavaScript dictionary with names

An object technically is a dictionary.

var myMappings = {
    mykey1: 'myValue',
    mykey2: 'myValue'
};

var myVal = myMappings['myKey1'];

alert(myVal); // myValue

You can even loop through one.

for(var key in myMappings) {
    var myVal = myMappings[key];
    alert(myVal);
}

There is no reason whatsoever to reinvent the wheel. And of course, assignment goes like:

myMappings['mykey3'] = 'my value';

And ContainsKey:

if (myMappings.hasOwnProperty('myKey3')) {
    alert('key already exists!');
}

I suggest you follow this: http://javascriptissexy.com/how-to-learn-javascript-properly/

How can I execute Python scripts using Anaconda's version of Python?

I know this is an old post, but I recently came across with the same problem. However, adding Anaconda to PYTHONPATH wasn't working for me. What got it fixed was the following:

  1. Added Anaconda to the PYTHONPATH and remove any other distribution of Python from any paths.
  2. Opened the command prompt and started python (Here I had to verify that it was indeed running under the Anaconda dist)
  3. Ran the following lines inside anaconda

    >>> import sys
    >>> sys.path
    ['','C:\\Anaconda','C:\\Anaconda\\Scripts','C:\\Anaconda\\python27.zip','C:\\Anaconda\\DLLs','C:\\Anaconda\\lib','C:\\Anaconda\\lib\\plat-win','C:\\Anaconda\\lib\\lib-tk','C:\\Anaconda\\lib\\site-packages','C:\\Anaconda\\lib\\site-packages\\PIL','C:\\Anaconda\\lib\\site-packages\\Sphinx-1.2.3-py2.7.egg','C:\\Anaconda\\lib\\site-packages\\win32', 'C:\\Anaconda\\lib\\site-packages\\win32\\lib', 'C:\\Anaconda\\lib\\site-packages\\Pythonwin','C:\\Anaconda\\lib\\site-packages\\runipy-0.1.1-py2.7.egg','C:\\Anaconda\\lib\\site-packages\\setuptools-5.8-py2.7.egg']
    
  4. Copied the displayed path

  5. Within the script that I'm trying to execute on double click, changed the path to the previously copied one.

    import sys
    sys.path =['','C:\\Anaconda','C:\\Anaconda\\Scripts','C:\\Anaconda\\python27.zip','C:\\Anaconda\\DLLs','C:\\Anaconda\\lib','C:\\Anaconda\\lib\\plat-win','C:\\Anaconda\\lib\\lib-tk','C:\\Anaconda\\lib\\site-packages','C:\\Anaconda\\lib\\site-packages\\PIL','C:\\Anaconda\\lib\\site-packages\\Sphinx-1.2.3-py2.7.egg','C:\\Anaconda\\lib\\site-packages\\win32', 'C:\\Anaconda\\lib\\site-packages\\win32\\lib', 'C:\\Anaconda\\lib\\site-packages\\Pythonwin','C:\\Anaconda\\lib\\site-packages\\runipy-0.1.1-py2.7.egg','C:\\Anaconda\\lib\\site-packages\\setuptools-5.8-py2.7.egg']
    
  6. Changed the default application for the script to 'python'

After doing this, my scripts are working on double click.

How to connect SQLite with Java?

connection = DriverManager.getConnection("jdbc:sqlite:D:\\testdb.db");

Instead of this put

connection = DriverManager.getConnection("jdbc:sqlite:D:\\testdb");

Matplotlib (pyplot) savefig outputs blank image

Calling savefig before show() worked for me.

fig ,ax = plt.subplots(figsize = (4,4))
sns.barplot(x='sex', y='tip', color='g', ax=ax,data=tips)
sns.barplot(x='sex', y='tip', color='b', ax=ax,data=tips)
ax.legend(['Male','Female'], facecolor='w')

plt.savefig('figure.png')
plt.show()

Squash my last X commits together using Git

In the branch you would like to combine the commits on, run:

git rebase -i HEAD~(n number of commits back to review)

example:

git rebase -i HEAD~1

This will open the text editor and you must switch the 'pick' in front of each commit with 'squash' if you would like these commits to be merged together. From documentation:

p, pick = use commit

s, squash = use commit, but meld into previous commit

For example, if you are looking to merge all the commits into one, the 'pick' is the first commit you made and all future ones (placed below the first) should be set to 'squash'. If using vim, use :x in insert mode to save and exit the editor.

Then to continue the rebase:

git rebase --continue

For more on this and other ways to rewrite your commit history see this helpful post

How do I empty an array in JavaScript?

In case you are interested in the memory allocation, you may compare each approach using something like this jsfiddle in conjunction with chrome dev tools' timeline tab. You will want to use the trash bin icon at the bottom to force a garbage collection after 'clearing' the array. This should give you a more definite answer for the browser of your choice. A lot of answers here are old and I wouldn't rely on them but rather test as in @tanguy_k's answer above.

(for an intro to the aforementioned tab you can check out here)

Stackoverflow forces me to copy the jsfiddle so here it is:

<html>
<script>
var size = 1000*100
window.onload = function() {
  document.getElementById("quantifier").value = size
}

function scaffold()
{
  console.log("processing Scaffold...");
  a = new Array
}
function start()
{
  size = document.getElementById("quantifier").value
  console.log("Starting... quantifier is " + size);
  console.log("starting test")
  for (i=0; i<size; i++){
    a[i]="something"
  }
  console.log("done...")
}

function tearDown()
{
  console.log("processing teardown");
  a.length=0
}

</script>
<body>
    <span style="color:green;">Quantifier:</span>
    <input id="quantifier" style="color:green;" type="text"></input>
    <button onclick="scaffold()">Scaffold</button>
    <button onclick="start()">Start</button>
    <button onclick="tearDown()">Clean</button>
    <br/>
</body>
</html>

And you should take note that it may depend on the type of the array elements, as javascript manages strings differently than other primitive types, not to mention arrays of objects. The type may affect what happens.

TypeScript hashmap/dictionary interface

The most simple and the correct way is to use Record type Record<string, string>

const myVar : Record<string, string> = {
   key1: 'val1',
   key2: 'val2',
}

Java - How to convert type collection into ArrayList?

As other people have mentioned, ArrayList has a constructor that takes a collection of items, and adds all of them. Here's the documentation:

http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html#ArrayList%28java.util.Collection%29

So you need to do:

ArrayList<MyNode> myNodeList = new ArrayList<MyNode>(this.getVertices());

However, in another comment you said that was giving you a compiler error. It looks like your class MyGraph is a generic class. And so getVertices() actually returns type V, not type myNode.

I think your code should look like this:

public V getNode(int nodeId){
        ArrayList<V> myNodeList = new ArrayList<V>(this.getVertices());
        return myNodeList(nodeId);
}

But, that said it's a very inefficient way to extract a node. What you might want to do is store the nodes in a binary tree, then when you get a request for the nth node, you do a binary search.

How to use onClick() or onSelect() on option tag in a JSP page?

If you need to change the value of another field, you can use this:

<input type="hidden" id="mainvalue" name="mainvalue" value="0">
<select onChange="document.getElementById('mainvalue').value = this.value;">
<option value="0">option 1</option>
<option value="1">option 2</option>
</select>

Postgresql - change the size of a varchar column to lower length

There's a description of how to do this at Resize a column in a PostgreSQL table without changing data. You have to hack the database catalog data. The only way to do this officially is with ALTER TABLE, and as you've noted that change will lock and rewrite the entire table while it's running.

Make sure you read the Character Types section of the docs before changing this. All sorts of weird cases to be aware of here. The length check is done when values are stored into the rows. If you hack a lower limit in there, that will not reduce the size of existing values at all. You would be wise to do a scan over the whole table looking for rows where the length of the field is >40 characters after making the change. You'll need to figure out how to truncate those manually--so you're back some locks just on oversize ones--because if someone tries to update anything on that row it's going to reject it as too big now, at the point it goes to store the new version of the row. Hilarity ensues for the user.

VARCHAR is a terrible type that exists in PostgreSQL only to comply with its associated terrible part of the SQL standard. If you don't care about multi-database compatibility, consider storing your data as TEXT and add a constraint to limits its length. Constraints you can change around without this table lock/rewrite problem, and they can do more integrity checking than just the weak length check.

how to get the one entry from hashmap without iterating

If you really want the API you suggested, you could subclass HashMap and keep track of the keys in a List for example. Don't see the point in this really, but it gives you what you want. If you explain the intended use case, maybe we can come up with a better solution.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("unchecked")
public class IndexedMap extends HashMap {

    private List<Object> keyIndex;

    public IndexedMap() {
        keyIndex = new ArrayList<Object>();
    }

    /**
     * Returns the key at the specified position in this Map's keyIndex.
     * 
     * @param index
     *            index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException
     *             if the index is out of range (index < 0 || index >= size())
     */
    public Object get(int index) {
        return keyIndex.get(index);
    }

    @Override
    public Object put(Object key, Object value) {

        addKeyToIndex(key);
        return super.put(key, value);
    }

    @Override
    public void putAll(Map source) {

        for (Object key : source.keySet()) {
            addKeyToIndex(key);
        }
        super.putAll(source);
    }

    private void addKeyToIndex(Object key) {

        if (!keyIndex.contains(key)) {
            keyIndex.add(key);
        }
    }

    @Override
    public Object remove(Object key) {

        keyIndex.remove(key);
        return super.remove(key);
    }
}

EDIT: I deliberately did not delve into the generics side of this...

how to find my angular version in my project?

ng --version command will show only the installed angular version in your computer instead of the actual project version.

if you really want to know the project version, Go to your project, use the below command

npm list -local

enter image description here

What's the difference between "super()" and "super(props)" in React when using es6 classes?

There is only one reason when one needs to pass props to super():

When you want to access this.props in constructor.

Passing:

class MyComponent extends React.Component {    
    constructor(props) {
        super(props)

        console.log(this.props)
        // -> { icon: 'home', … }
    }
}

Not passing:

class MyComponent extends React.Component {    
    constructor(props) {
        super()

        console.log(this.props)
        // -> undefined

        // Props parameter is still available
        console.log(props)
        // -> { icon: 'home', … }
    }

    render() {
        // No difference outside constructor
        console.log(this.props)
        // -> { icon: 'home', … }
    }
}

Note that passing or not passing props to super has no effect on later uses of this.props outside constructor. That is render, shouldComponentUpdate, or event handlers always have access to it.

This is explicitly said in one Sophie Alpert's answer to a similar question.


The documentation—State and Lifecycle, Adding Local State to a Class, point 2—recommends:

Class components should always call the base constructor with props.

However, no reason is provided. We can speculate it is either because of subclassing or for future compatibility.

(Thanks @MattBrowne for the link)

How to dynamically add a style for text-align using jQuery

 $(this).css({'text-align':'center'}); 

You can use class name and id in place of this

$('.classname').css({'text-align':'center'});

or

$('#id').css({'text-align':'center'});

How to use regex in file find

find /home/test -regextype posix-extended -regex '^.*test\.log\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.zip' -mtime +3
  1. -name uses globular expressions, aka wildcards. What you want is -regex
  2. To use intervals as you intend, you need to tell find to use Extended Regular Expressions via the -regextype posix-extended flag
  3. You need to escape out the periods because in regex a period has the special meaning of any single character. What you want is a literal period denoted by \.
  4. To match only those files that are greater than 3 days old, you need to prefix your number with a + as in -mtime +3.

Proof of Concept

$ find . -regextype posix-extended -regex '^.*test\.log\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.zip'
./test.log.1234-12-12.zip

No module named 'openpyxl' - Python 3.4 - Ubuntu

If you're using Python3, then install:

python3 -m pip install --user xlsxwriter

This will run pip with the appropriate version of Python3. If you run bare pip3 and have many versions of Python install, it will still fail leading to more confusion.

The --user flag will allow to install as a regular user and no require root.

jQuery - how can I find the element with a certain id?

As all html ids are unique in a valid html document why not search for the ID directly? If you're concerned if they type in an id that isn't a table then you can inspect the tag type that way?

Just an idea!

S

how to write javascript code inside php

At the time the script is executed, the button does not exist because the DOM is not fully loaded. The easiest solution would be to put the script block after the form.

Another solution would be to capture the window.onload event or use the jQuery library (overkill if you only have this one JavaScript).

Pandas convert string to int

You need add parameter errors='coerce' to function to_numeric:

ID = pd.to_numeric(ID, errors='coerce')

If ID is column:

df.ID = pd.to_numeric(df.ID, errors='coerce')

but non numeric are converted to NaN, so all values are float.

For int need convert NaN to some value e.g. 0 and then cast to int:

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)

Sample:

df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
              ID
0  4806105017087
1  4806105017087
2       CN414149

print (pd.to_numeric(df.ID, errors='coerce'))
0    4.806105e+12
1    4.806105e+12
2             NaN
Name: ID, dtype: float64

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
              ID
0  4806105017087
1  4806105017087
2              0

EDIT: If use pandas 0.25+ then is possible use integer_na:

df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
              ID
0  4806105017087
1  4806105017087
2            NaN

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

The MapUtils class offered by the Apache Commons project offers a MapUtils.debugPrint method which will pretty print your map.

How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest

Setting CSS width to 1% or 100% of an element according to all specs I could find out is related to the parent. Although Blink Rendering Engine (Chrome) and Gecko (Firefox) at the moment of writing seems to handle that 1% or 100% (make a columns shrink or a column to fill available space) well, it is not guaranteed according to all CSS specifications I could find to render it properly.

One option is to replace table with CSS4 flex divs:

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

That works in new browsers i.e. IE11+ see table at the bottom of the article.

Could not reserve enough space for object heap to start JVM

I had the same problem when using a 32 bit version of java in a 64 bit environment. When using 64 java in a 64 OS it was ok.

Cannot run Eclipse; JVM terminated. Exit code=13

I tried many way and placed -VM argument at suggested place. But It would not work. Finally I got solution. -Vm args should be place eclipse.ini file before execution of any plugin or jar. I tried with latest eclipse [Photon ] in ubuntu 18.04 It is perfectly working for me.

-startup
-vm        
/usr/local/java/jdk1.8.0_251/bin/java.exe
plugins/org.eclipse.equinox.launcher_1.5.700.v20200207-2156.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.1100.v20190907-0426
-product
org.eclipse.epp.package.jee.product
-showsplash
org.eclipse.epp.package.common
--launcher.defaultAction
openFile
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.8
[email protected]/eclipse-workspace
-XX:+UseG1GC
-XX:+UseStringDeduplication
--add-modules=ALL-SYSTEM
-Dosgi.requiredJavaVersion=1.8
-Dosgi.dataAreaRequiresExplicitInit=true
-Xms256m
-Xmx2048m
--add-modules=ALL-SYSTEM

Print: Entry, ":CFBundleIdentifier", Does Not Exist

I had this happen to me when my node_modules folder got screwy after installing a new package. I killed the folder rm -rf node_modules and then did an npm install to re-install my packages and that fixed it.

Create an enum with string values

I have tried in TypeScript 1.5 like below and it's worked for me

module App.Constants {
   export enum e{
        Hello= ("Hello") as any,
World= ("World") as any
    }
}

Is it possible to run JavaFX applications on iOS, Android or Windows Phone 8?

Yes you can run JavaFX application on iOS, android, desktop, RaspberryPI (no windows8 mobile yet).

Work in Action :

We did it! JavaFX8 multimedia project on iPad, Android, Windows and Mac!

JavaFX Everywhere

Ensemble8 Javafx8 Android Demo

My Sample JavaFX application Running on Raspberry Pi

My Sample Application Running on Android

JavaFX on iOS and Android

Dev Resources :

Android :

Building and deploying JavaFX Applications on Android

iOS :

NetBeans support for JavaFX for iOS is out!

Develop a JavaFX + iOS app with RoboVM + e(fx)clipse tools in 10 minutes

If you are going to develop serious applications here is some more info

Misc :

At present for JavaFX Oracle priority list is Desktop (Mac,windows,linux) and Embedded (Raspberry Pi, beagle Board etc) .For iOS/android oracle done most of the hardwork and opnesourced javafxports of these platforms as part of OpenJFX ,but there is no JVM from oracle for ios/android.Community is putting all together by filling missing piece(JVM) for ios/android,Community made good progress in running JavaFX on ios (RoboVM) / android(DalvikVM). If you want you can also contribute to the community by sponsoring (Become a RoboVM sponsor) or start developing apps and report issues.

Edit 06/23/2014 :

Johan Vos created a website for javafx ports JavaFX on Mobile and Tablets,check this for updated info ..

How to rsync only a specific list of files?

This answer is not the direct answer for the question. But it should help you figure out which solution fits best for your problem.

When analysing the problem you should activate the debug option -vv

Then rsync will output which files are included or excluded by which pattern:

building file list ... 
[sender] hiding file FILE1 because of pattern FILE1*
[sender] showing file FILE2 because of pattern *

Closing Applications

Application.Exit is for Windows Forms applications - it informs all message pumps that they should terminate, waits for them to finish processing events and then terminates the application. Note that it doesn't necessarily force the application to exit.

Environment.Exit is applicable for all Windows applications, however it is mainly intended for use in console applications. It immediately terminates the process with the given exit code.

In general you should use Application.Exit in Windows Forms applications and Environment.Exit in console applications, (although I prefer to let the Main method / entry point run to completion rather than call Environment.Exit in console applications).

For more detail see the MSDN documentation.

What size do you use for varchar(MAX) in your parameter declaration?

The maximum SqlDbType.VarChar size is 2147483647.

If you would use a generic oledb connection instead of sql, I found here there is also a LongVarChar datatype. Its max size is 2147483647.

cmd.Parameters.Add("@blah", OleDbType.LongVarChar, -1).Value = "very big string";

What are the differences between a superkey and a candidate key?

Candidate key is a super key from which you cannot remove any fields.

For instance, a software release can be identified either by major/minor version, or by the build date (we assume nightly builds).

Storing date in three fields is not a good idea of course, but let's pretend it is for demonstration purposes:

year  month date  major  minor
2008  01    13     0      1
2008  04    23     0      2
2009  11    05     1      0
2010  04    05     1      1

So (year, major, minor) or (year, month, date, major) are super keys (since they are unique) but not candidate keys, since you can remove year or major and the remaining set of columns will still be a super key.

(year, month, date) and (major, minor) are candidate keys, since you cannot remove any of the fields from them without breaking uniqueness.

Git merge master into feature branch

In Eclipse -

1)Checkout master branch

Git Repositories ->Click on your repository -> click on Local ->double click master branch
->Click on yes for check out

2)Pull master branch

Right click on project ->click on Team -> Click on Pull

3)Checkout your feature branch(follow same steps mentioned in 1 point)

4)Merge master into feature

Git Repositories ->Click on your repository -> click on Local ->Right Click on your selected feature branch ->Click on merge ->Click on Local ->Click on Master ->Click on Merge.

5)Now you will get all changes of Master branch in feature branch. Remove conflict if any.

For conflict if any exists ,follow this -
Changes mentioned as Head(<<<<<< HEAD) is your change, Changes mentioned in branch(>>>>>>> branch) is other person change, you can update file accordingly.

Note - You need to do add to index for conflicts files

6)commit and push your changes in feature branch.

Right click on project ->click on Team -> Click on commit -> Commit and Push.

OR

Git Repositories ->Click on your repository -> click on Local ->Right Click on your selected feature branch ->Click on Push Branch ->Preview ->Push

Using IQueryable with Linq

Although Reed Copsey and Marc Gravell already described about IQueryable (and also IEnumerable) enough,mI want to add little more here by providing a small example on IQueryable and IEnumerable as many users asked for it

Example: I have created two table in database

   CREATE TABLE [dbo].[Employee]([PersonId] [int] NOT NULL PRIMARY KEY,[Gender] [nchar](1) NOT NULL)
   CREATE TABLE [dbo].[Person]([PersonId] [int] NOT NULL PRIMARY KEY,[FirstName] [nvarchar](50) NOT NULL,[LastName] [nvarchar](50) NOT NULL)

The Primary key(PersonId) of table Employee is also a forgein key(personid) of table Person

Next i added ado.net entity model in my application and create below service class on that

public class SomeServiceClass
{   
    public IQueryable<Employee> GetEmployeeAndPersonDetailIQueryable(IEnumerable<int> employeesToCollect)
    {
        DemoIQueryableEntities db = new DemoIQueryableEntities();
        var allDetails = from Employee e in db.Employees
                         join Person p in db.People on e.PersonId equals p.PersonId
                         where employeesToCollect.Contains(e.PersonId)
                         select e;
        return allDetails;
    }

    public IEnumerable<Employee> GetEmployeeAndPersonDetailIEnumerable(IEnumerable<int> employeesToCollect)
    {
        DemoIQueryableEntities db = new DemoIQueryableEntities();
        var allDetails = from Employee e in db.Employees
                         join Person p in db.People on e.PersonId equals p.PersonId
                         where employeesToCollect.Contains(e.PersonId)
                         select e;
        return allDetails;
    }
}

they contains same linq. It called in program.cs as defined below

class Program
{
    static void Main(string[] args)
    {
        SomeServiceClass s= new SomeServiceClass(); 

        var employeesToCollect= new []{0,1,2,3};

        //IQueryable execution part
        var IQueryableList = s.GetEmployeeAndPersonDetailIQueryable(employeesToCollect).Where(i => i.Gender=="M");            
        foreach (var emp in IQueryableList)
        {
            System.Console.WriteLine("ID:{0}, EName:{1},Gender:{2}", emp.PersonId, emp.Person.FirstName, emp.Gender);
        }
        System.Console.WriteLine("IQueryable contain {0} row in result set", IQueryableList.Count());

        //IEnumerable execution part
        var IEnumerableList = s.GetEmployeeAndPersonDetailIEnumerable(employeesToCollect).Where(i => i.Gender == "M");
        foreach (var emp in IEnumerableList)
        {
           System.Console.WriteLine("ID:{0}, EName:{1},Gender:{2}", emp.PersonId, emp.Person.FirstName, emp.Gender);
        }
        System.Console.WriteLine("IEnumerable contain {0} row in result set", IEnumerableList.Count());

        Console.ReadKey();
    }
}

The output is same for both obviously

ID:1, EName:Ken,Gender:M  
ID:3, EName:Roberto,Gender:M  
IQueryable contain 2 row in result set  
ID:1, EName:Ken,Gender:M  
ID:3, EName:Roberto,Gender:M  
IEnumerable contain 2 row in result set

So the question is what/where is the difference? It does not seem to have any difference right? Really!!

Let's have a look on sql queries generated and executed by entity framwork 5 during these period

IQueryable execution part

--IQueryableQuery1 
SELECT 
[Extent1].[PersonId] AS [PersonId], 
[Extent1].[Gender] AS [Gender]
FROM [dbo].[Employee] AS [Extent1]
WHERE ([Extent1].[PersonId] IN (0,1,2,3)) AND (N'M' = [Extent1].[Gender])

--IQueryableQuery2
SELECT 
[GroupBy1].[A1] AS [C1]
FROM ( SELECT 
    COUNT(1) AS [A1]
    FROM [dbo].[Employee] AS [Extent1]
    WHERE ([Extent1].[PersonId] IN (0,1,2,3)) AND (N'M' = [Extent1].[Gender])
)  AS [GroupBy1]

IEnumerable execution part

--IEnumerableQuery1
SELECT 
[Extent1].[PersonId] AS [PersonId], 
[Extent1].[Gender] AS [Gender]
FROM [dbo].[Employee] AS [Extent1]
WHERE [Extent1].[PersonId] IN (0,1,2,3)

--IEnumerableQuery2
SELECT 
[Extent1].[PersonId] AS [PersonId], 
[Extent1].[Gender] AS [Gender]
FROM [dbo].[Employee] AS [Extent1]
WHERE [Extent1].[PersonId] IN (0,1,2,3)

Common script for both execution part

/* these two query will execute for both IQueryable or IEnumerable to get details from Person table
   Ignore these two queries here because it has nothing to do with IQueryable vs IEnumerable
--ICommonQuery1 
exec sp_executesql N'SELECT 
[Extent1].[PersonId] AS [PersonId], 
[Extent1].[FirstName] AS [FirstName], 
[Extent1].[LastName] AS [LastName]
FROM [dbo].[Person] AS [Extent1]
WHERE [Extent1].[PersonId] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=1

--ICommonQuery2
exec sp_executesql N'SELECT 
[Extent1].[PersonId] AS [PersonId], 
[Extent1].[FirstName] AS [FirstName], 
[Extent1].[LastName] AS [LastName]
FROM [dbo].[Person] AS [Extent1]
WHERE [Extent1].[PersonId] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=3
*/

So you have few questions now, let me guess those and try to answer them

Why are different scripts generated for same result?

Lets find out some points here,

all queries has one common part

WHERE [Extent1].[PersonId] IN (0,1,2,3)

why? Because both function IQueryable<Employee> GetEmployeeAndPersonDetailIQueryable and IEnumerable<Employee> GetEmployeeAndPersonDetailIEnumerable of SomeServiceClass contains one common line in linq queries

where employeesToCollect.Contains(e.PersonId)

Than why is the AND (N'M' = [Extent1].[Gender]) part is missing in IEnumerable execution part, while in both function calling we used Where(i => i.Gender == "M") inprogram.cs`

Now we are in the point where difference came between IQueryable and IEnumerable

What entity framwork does when an IQueryable method called, it tooks linq statement written inside the method and try to find out if more linq expressions are defined on the resultset, it then gathers all linq queries defined until the result need to fetch and constructs more appropriate sql query to execute.

It provide a lots of benefits like,

  • only those rows populated by sql server which could be valid by the whole linq query execution
  • helps sql server performance by not selecting unnecessary rows
  • network cost get reduce

like here in example sql server returned to application only two rows after IQueryable execution` but returned THREE rows for IEnumerable query why?

In case of IEnumerable method, entity framework took linq statement written inside the method and constructs sql query when result need to fetch. it does not include rest linq part to constructs the sql query. Like here no filtering is done in sql server on column gender.

But the outputs are same? Because 'IEnumerable filters the result further in application level after retrieving result from sql server

SO, what should someone choose? I personally prefer to define function result as IQueryable<T> because there are lots of benefit it has over IEnumerable like, you could join two or more IQueryable functions, which generate more specific script to sql server.

Here in example you can see an IQueryable Query(IQueryableQuery2) generates a more specific script than IEnumerable query(IEnumerableQuery2) which is much more acceptable in my point of view.

What does the keyword Set actually do in VBA?

From MSDN:

Set Keyword: In VBA, the Set keyword is necessary to distinguish between assignment of an object and assignment of the default property of the object. Since default properties are not supported in Visual Basic .NET, the Set keyword is not needed and is no longer supported.

Random float number generation

In my opinion the above answer do give some 'random' float, but none of them is truly a random float (i.e. they miss a part of the float representation). Before I will rush into my implementation lets first have a look at the ANSI/IEEE standard format for floats:

|sign (1-bit)| e (8-bits) | f (23-bit) |

the number represented by this word is (-1 * sign) * 2^e * 1.f

note the the 'e' number is a biased (with a bias of 127) number thus ranging from -127 to 126. The most simple (and actually most random) function is to just write the data of a random int into a float, thus

int tmp = rand();
float f = (float)*((float*)&tmp);

note that if you do float f = (float)rand(); it will convert the integer into a float (thus 10 will become 10.0).

So now if you want to limit the maximum value you can do something like (not sure if this works)

int tmp = rand();
float f = *((float*)&tmp);
tmp = (unsigned int)f       // note float to int conversion!
tmp %= max_number;
f -= tmp;

but if you look at the structure of the float you can see that the maximum value of a float is (approx) 2^127 which is way larger as the maximum value of an int (2^32) thus ruling out a significant part of the numbers that can be represented by a float. This is my final implementation:

/**
 * Function generates a random float using the upper_bound float to determine 
 * the upper bound for the exponent and for the fractional part.
 * @param min_exp sets the minimum number (closest to 0) to 1 * e^min_exp (min -127)
 * @param max_exp sets the maximum number to 2 * e^max_exp (max 126)
 * @param sign_flag if sign_flag = 0 the random number is always positive, if 
 *              sign_flag = 1 then the sign bit is random as well
 * @return a random float
 */
float randf(int min_exp, int max_exp, char sign_flag) {
    assert(min_exp <= max_exp);

    int min_exp_mod = min_exp + 126;

    int sign_mod = sign_flag + 1;
    int frac_mod = (1 << 23);

    int s = rand() % sign_mod;  // note x % 1 = 0
    int e = (rand() % max_exp) + min_exp_mod;
    int f = rand() % frac_mod;

    int tmp = (s << 31) | (e << 23) | f;

    float r = (float)*((float*)(&tmp));

    /** uncomment if you want to see the structure of the float. */
//    printf("%x, %x, %x, %x, %f\n", (s << 31), (e << 23), f, tmp, r);

    return r;
}

using this function randf(0, 8, 0) will return a random number between 0.0 and 255.0

How to find item with max value using linq?

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);

Get url without querystring

Request.RawUrl.Split('?')[0]

Just for url name only !!

Permission denied for relation

Connect to the right database first, then run:

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO jerry;

Open a new tab on button click in AngularJS

Proper HTML way: just surround your button with anchor element and add attribute target="_blank". It is as simple as that:

<a ng-href="{{yourDynamicURL}}" target="_blank">
    <h1>Open me in new Tab</h1>
</a>

where you can set in the controller:

$scope.yourDynamicURL = 'https://stackoverflow.com';

MongoDB: Server has startup warnings ''Access control is not enabled for the database''

Mongodb v3.4

You need to do the following to create a secure database:

Make sure the user starting the process has permissions and that the directories exist (/data/db in this case).

1) Start MongoDB without access control.

mongod --port 27017 --dbpath /data/db

2) Connect to the instance.

mongo --port 27017

3) Create the user administrator (in the admin authentication database).

use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: "abc123",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

4) Re-start the MongoDB instance with access control.

mongod --auth --port 27017 --dbpath /data/db

5) Connect and authenticate as the user administrator.

mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"

6) Create additional users as needed for your deployment (e.g. in the test authentication database).

use test
db.createUser(
  {
    user: "myTester",
    pwd: "xyz123",
    roles: [ { role: "readWrite", db: "test" },
             { role: "read", db: "reporting" } ]
  }
)

7) Connect and authenticate as myTester.

mongo --port 27017 -u "myTester" -p "xyz123" --authenticationDatabase "test"

I basically just explained the short version of the official docs here: https://docs.mongodb.com/master/tutorial/enable-authentication/

Truncate Decimal number not Round Off

Forget Everything just check out this

double num = 2.22939393;
num  = Convert.ToDouble(num.ToString("#0.000"));

Error: Tablespace for table xxx exists. Please DISCARD the tablespace before IMPORT

Had this issue several times. If you have a large DB and want to try avoiding backup/restore (with added missing table), try few times back and forth:

DROP TABLE my_table;

ALTER TABLE my_table DISCARD TABLESPACE;

-and-

rm my_table.ibd (orphan w/o corresponding my_table.frm) located in /var/lib/mysql/my_db/ directory

-and then-

CREATE TABLE IF NOT EXISTS my_table (...)

how to output every line in a file python

Did you try

for line in open("masters", "r").readlines(): print line

?

readline() 

only reads "a line", on the other hand

readlines()

reads whole lines and gives you a list of all lines.

SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)

Anyone who has this error, especially on Azure, try adding "tcp:" to the db-server-name in your connection string in your application. This forces the sql client to communicate with the db using tcp. I'm assuming the connection is UDP by default and there can be intermittent connection issues

What is the use of the square brackets [] in sql statements?

In addition Some Sharepoint databases contain hyphens in their names. Using square brackets in SQL Statements allow the names to be parsed correctly.

error::make_unique is not a member of ‘std’

This happens to me while working with XCode (I'm using the most current version of XCode in 2019...). I'm using, CMake for build integration. Using the following directive in CMakeLists.txt fixed it for me:

set(CMAKE_CXX_STANDARD 14).

Example:

cmake_minimum_required(VERSION 3.14.0)
set(CMAKE_CXX_STANDARD 14)

# Rest of your declarations...

jQuery Select first and second td

$(".location table tbody tr").each(function(){
    $('td:first', this).addClass('black').next().addClass('black');
});

another:

$(".location table tbody tr").find('td:first, td:nth-child(2)').addClass('black');

'if' in prolog?

Yes, there is such a control construct in ISO Prolog, called ->. You use it like this:

( condition -> then_clause ; else_clause )

Here is an example that uses a chain of else-if-clauses:

(   X < 0 ->
    writeln('X is negative.  That's weird!  Failing now.'),
    fail
;   X =:= 0 ->
    writeln('X is zero.')
;   writeln('X is positive.')
)

Note that if you omit the else-clause, the condition failing will mean that the whole if-statement will fail. Therefore, I recommend always including the else-clause (even if it is just true).

Why is String immutable in Java?

String is given as immutable by Sun micro systems,because string can used to store as key in map collection. StringBuffer is mutable .That is the reason,It cannot be used as key in map object

How do I tokenize a string in C++?

Use strtok. In my opinion, there isn't a need to build a class around tokenizing unless strtok doesn't provide you with what you need. It might not, but in 15+ years of writing various parsing code in C and C++, I've always used strtok. Here is an example

char myString[] = "The quick brown fox";
char *p = strtok(myString, " ");
while (p) {
    printf ("Token: %s\n", p);
    p = strtok(NULL, " ");
}

A few caveats (which might not suit your needs). The string is "destroyed" in the process, meaning that EOS characters are placed inline in the delimter spots. Correct usage might require you to make a non-const version of the string. You can also change the list of delimiters mid parse.

In my own opinion, the above code is far simpler and easier to use than writing a separate class for it. To me, this is one of those functions that the language provides and it does it well and cleanly. It's simply a "C based" solution. It's appropriate, it's easy, and you don't have to write a lot of extra code :-)

How to define an empty object in PHP

Here an example with the iteration:

<?php
$colors = (object)[];
$colors->red = "#F00";
$colors->slateblue = "#6A5ACD";
$colors->orange = "#FFA500";

foreach ($colors as $key => $value) : ?>
    <p style="background-color:<?= $value ?>">
        <?= $key ?> -> <?= $value ?>
    </p>
<?php endforeach; ?>

Converting PHP result array to JSON

json_encode is available in php > 5.2.0:

echojson_encode($row);

Password Protect a SQLite DB. Is it possible?

Use SQLCipher, it's an opensource extension for SQLite that provides transparent 256-bit AES encryption of database files. http://sqlcipher.net

How to get URI from an asset File?

InputStream is = getResources().getAssets().open("terms.txt");
String textfile = convertStreamToString(is);
    
public static String convertStreamToString(InputStream is)
        throws IOException {

    Writer writer = new StringWriter();
    char[] buffer = new char[2048];

    try {
        Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } finally {
        is.close();
    }

    String text = writer.toString();
    return text;
}

Right way to split an std::string into a vector<string>

If the string has both spaces and commas you can use the string class function

found_index = myString.find_first_of(delims_str, begin_index) 

in a loop. Checking for != npos and inserting into a vector. If you prefer old school you can also use C's

strtok() 

method.

Can local storage ever be considered secure?

WebCrypto

The concerns with cryptography in client-side (browser) javascript are detailed below. All but one of these concerns does not apply to the WebCrypto API, which is now reasonably well supported.

For an offline app, you must still design and implement a secure keystore.

Aside: If you are using Node.js, use the builtin crypto API.

Native-Javascript Cryptography (pre-WebCrypto)

I presume the primary concern is someone with physical access to the computer reading the localStorage for your site, and you want cryptography to help prevent that access.

If someone has physical access you are also open to attacks other and worse than reading. These include (but are not limited to): keyloggers, offline script modification, local script injection, browser cache poisoning, and DNS redirects. Those attacks only work if the user uses the machine after it has been compromised. Nevertheless, physical access in such a scenario means you have bigger problems.

So keep in mind that the limited scenario where local crypto is valuable would be if the machine is stolen.

There are libraries that do implement the desired functionality, e.g. Stanford Javascript Crypto Library. There are inherent weaknesses, though (as referred to in the link from @ircmaxell's answer):

  1. Lack of entropy / random number generation;
  2. Lack of a secure keystore i.e. the private key must be password-protected if stored locally, or stored on the server (which bars offline access);
  3. Lack of secure-erase;
  4. Lack of timing characteristics.

Each of these weaknesses corresponds with a category of cryptographic compromise. In other words, while you may have "crypto" by name, it will be well below the rigour one aspires to in practice.

All that being said, the actuarial assessment is not as trivial as "Javascript crypto is weak, do not use it". This is not an endorsement, strictly a caveat and it requires you to completely understand the exposure of the above weaknesses, the frequency and cost of the vectors you face, and your capacity for mitigation or insurance in the event of failure: Javascript crypto, in spite of its weaknesses, may reduce your exposure but only against thieves with limited technical capacity. However, you should presume Javascript crypto has no value against a determined and capable attacker who is targeting that information. Some would consider it misleading to call the data "encrypted" when so many weaknesses are known to be inherent to the implementation. In other words, you can marginally decrease your technical exposure but you increase your financial exposure from disclosure. Each situation is different, of course - and the analysis of reducing the technical exposure to financial exposure is non-trivial. Here is an illustrative analogy: Some banks require weak passwords, in spite of the inherent risk, because their exposure to losses from weak passwords is less than the end-user costs of supporting strong passwords.

If you read the last paragraph and thought "Some guy on the Internet named Brian says I can use Javascript crypto", do not use Javascript crypto.

For the use case described in the question it would seem to make more sense for users to encrypt their local partition or home directory and use a strong password. That type of security is generally well tested, widely trusted, and commonly available.

Should I return EXIT_SUCCESS or 0 from main()?

0 is, by definition, a magic number. EXIT_SUCCESS is almost universally equal to 0, happily enough. So why not just return/exit 0?

exit(EXIT_SUCCESS); is abundantly clear in meaning.

exit(0); on the other hand, is counterintuitive in some ways. Someone not familiar with shell behavior might assume that 0 == false == bad, just like every other usage of 0 in C. But no - in this one special case, 0 == success == good. For most experienced devs, not going to be a problem. But why trip up the new guy for absolutely no reason?

tl;dr - if there's a defined constant for your magic number, there's almost never a reason not to used the constant in the first place. It's more searchable, often clearer, etc. and it doesn't cost you anything.

Bootstrap 3 - disable navbar collapse

After close examining, not 300k lines but there are around 3-4 CSS properties that you need to override:

.navbar-collapse.collapse {
  display: block!important;
}

.navbar-nav>li, .navbar-nav {
  float: left !important;
}

.navbar-nav.navbar-right:last-child {
  margin-right: -15px !important;
}

.navbar-right {
  float: right!important;
}

And with this your menu won't collapse.

DEMO (jsfiddle)

EXPLANATION

The four CSS properties do the respective:

  1. The default .collapse property in bootstrap hides the right-side of the menu for tablets(landscape) and phones and instead a toggle button is displayed to hide/show it. Thus this property overrides the default and persistently shows those elements.

  2. For the right-side menu to appear on the same line along with the left-side, we need the left-side to be floating left.

  3. This property is present by default in bootstrap but not on tablet(portrait) to phone resolution. You can skip this one, it's likely to not affect your overall navbar.

  4. This keeps the right-side menu to the right while the inner elements (li) will follow the property 2. So we have left-side float left and right-side float right which brings them into one line.

How to create a md5 hash of a string in C?

As other answers have mentioned, the following calls will compute the hash:

MD5Context md5;
MD5Init(&md5);
MD5Update(&md5, data, datalen);
MD5Final(digest, &md5);

The purpose of splitting it up into that many functions is to let you stream large datasets.

For example, if you're hashing a 10GB file and it doesn't fit into ram, here's how you would go about doing it. You would read the file in smaller chunks and call MD5Update on them.

MD5Context md5;
MD5Init(&md5);

fread(/* Read a block into data. */)
MD5Update(&md5, data, datalen);

fread(/* Read the next block into data. */)
MD5Update(&md5, data, datalen);

fread(/* Read the next block into data. */)
MD5Update(&md5, data, datalen);

...

//  Now finish to get the final hash value.
MD5Final(digest, &md5);

How to Deserialize XML document

How about you just save the xml to a file, and use xsd to generate C# classes?

  1. Write the file to disk (I named it foo.xml)
  2. Generate the xsd: xsd foo.xml
  3. Generate the C#: xsd foo.xsd /classes

Et voila - and C# code file that should be able to read the data via XmlSerializer:

    XmlSerializer ser = new XmlSerializer(typeof(Cars));
    Cars cars;
    using (XmlReader reader = XmlReader.Create(path))
    {
        cars = (Cars) ser.Deserialize(reader);
    }

(include the generated foo.cs in the project)

executing a function in sql plus

declare
  x number;
begin
  x := myfunc(myargs);
end;

Alternatively:

select myfunc(myargs) from dual;

How do pointer-to-pointer's work in C? (and when might you use them?)

Pointers to Pointers

Since we can have pointers to int, and pointers to char, and pointers to any structures we've defined, and in fact pointers to any type in C, it shouldn't come as too much of a surprise that we can have pointers to other pointers.

Removing the password from a VBA project

This has a simple method using SendKeys to unprotect the VBA project. This would get you into the project, so you'd have to continue on using SendKeys to figure out a way to remove the password protection: http://www.pcreview.co.uk/forums/thread-989191.php

And here's one that uses a more advanced, somewhat more reliable method for unprotecting. Again, it will only unlock the VB project for you. http://www.ozgrid.com/forum/showthread.php?t=13006&page=2

I haven't tried either method, but this may save you some time if it's what you need to do...

WCF Service , how to increase the timeout?

The timeout configuration needs to be set at the client level, so the configuration I was setting in the web.config had no effect, the WCF test tool has its own configuration and there is where you need to set the timeout.

Slicing a dictionary

set intersection and dict comprehension can be used here

# the dictionary
d = {1:2, 3:4, 5:6, 7:8}

# the subset of keys I'm interested in
l = (1,5)

>>>{key:d[key] for key in set(l) & set(d)}
{1: 2, 5: 6}

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's an old discussion thread where I listed the main differences and the conditions in which you should use each of these methods. I think you may find it useful to go through the discussion.

To explain the differences as relevant to your posted example:

a. When you use RegisterStartupScript, it will render your script after all the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM.

Here is the rendered source of the page when you invoke the RegisterStartupScript method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <div> <span id="lblDisplayDate">Label</span>
            <br />
            <input type="submit" name="btnPostback" value="Register Startup Script" id="btnPostback" />
            <br />
            <input type="submit" name="btnPostBack2" value="Register" id="btnPostBack2" />
        </div>
        <div>
            <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="someViewstategibberish" />
        </div>
        <!-- Note this part -->
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            lbl.style.color = 'red';
        </script>
    </form>
    <!-- Note this part -->
</body>
</html>

b. When you use RegisterClientScriptBlock, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error.

Here is the rendered source of the page when you invoke the RegisterClientScriptBlock method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            // Error is thrown in the next line because lbl is null.
            lbl.style.color = 'green';

Therefore, to summarize, you should call the latter method if you intend to render a function definition. You can then render the call to that function using the former method (or add a client side attribute).

Edit after comments:


For instance, the following function would work:

protected void btnPostBack2_Click(object sender, EventArgs e) 
{ 
  System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
  sb.Append("<script language='javascript'>function ChangeColor() {"); 
  sb.Append("var lbl = document.getElementById('lblDisplayDate');"); 
  sb.Append("lbl.style.color='green';"); 
  sb.Append("}</script>"); 

  //Render the function definition. 
  if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock")) 
  {
    ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString()); 
  }

  //Render the function invocation. 
  string funcCall = "<script language='javascript'>ChangeColor();</script>"; 

  if (!ClientScript.IsStartupScriptRegistered("JSScript"))
  { 
    ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall); 
  } 
} 

First Or Create

An update:

As of Laravel 5.3 doing this in a single step is possible; the firstOrCreate method now accepts an optional second array as an argument.

The first array argument is the array on which the fields/values are matched, and the second array is the additional fields to use in the creation of the model if no match is found via matching the fields/values in the first array:

See documentation

How to view UTF-8 Characters in VIM or Gvim

I couldn't get any other fonts I installed to show up in my Windows GVim editor, so I just switched to Lucida Console which has at least somewhat better UTF-8 support. Add this to the end of your _vimrc:

" For making everything utf-8
set enc=utf-8
set guifont=Lucida_Console:h9:cANSI
set guifontwide=Lucida_Console:h12

Now I see at least some UTF-8 characters.

pandas unique values multiple columns

list(set(df[['Col1', 'Col2']].as_matrix().reshape((1,-1)).tolist()[0]))

The output will be ['Mary', 'Joe', 'Steve', 'Bob', 'Bill']

Joining pandas dataframes by column names

you can use the left_on and right_on options as follows:

pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')

I was not sure from the question if you only wanted to merge if the key was in the left hand dataframe. If that is the case then the following will do that (the above will in effect do a many to many merge)

pd.merge(frame_1, frame_2, how='left', left_on='county_ID', right_on='countyid')

How to create a WPF Window without a border that can be resized via a grip only?

If you set the AllowsTransparency property on the Window (even without setting any transparency values) the border disappears and you can only resize via the grip.

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="640" Height="480" 
    WindowStyle="None"
    AllowsTransparency="True"
    ResizeMode="CanResizeWithGrip">

    <!-- Content -->

</Window>

Result looks like:

Matching strings with wildcard

Using of WildcardPattern from System.Management.Automation may be an option.

pattern = new WildcardPattern(patternString);
pattern.IsMatch(stringToMatch);

Visual Studio UI may not allow you to add System.Management.Automation assembly to References of your project. Feel free to add it manually, as described here.

Javascript isnull

return (results||0) && results[1] || 0;

The && operator acts as guard and returns the 0 if results if falsy and return the rightmost part if truthy.

Default property value in React component using TypeScript

You can use the spread operator to re-assign props with a standard functional component. The thing I like about this approach is that you can mix required props with optional ones that have a default value.

interface MyProps {
   text: string;
   optionalText?: string;
}

const defaultProps = {
   optionalText = "foo";
}

const MyComponent = (props: MyProps) => {
   props = { ...defaultProps, ...props }
}

Python Traceback (most recent call last)

In Python2, input is evaluated, input() is equivalent to eval(raw_input()). When you enter klj, Python tries to evaluate that name and raises an error because that name is not defined.

Use raw_input to get a string from the user in Python2.

Demo 1: klj is not defined:

>>> input()
klj
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'klj' is not defined

Demo 2: klj is defined:

>>> klj = 'hi'
>>> input()
klj
'hi'

Demo 3: getting a string with raw_input:

>>> raw_input()
klj
'klj'

How to convert HTML file to word?

Other Alternatives from just renaming the file to .doc.....

http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word(office.11).aspx

Here is a good place to start. You can also try using this Office Open XML.

http://www.ecma-international.org/publications/standards/Ecma-376.htm

How do I convert an array object to a string in PowerShell?

$a = "This", "Is", "a", "cat"

foreach ( $word in $a ) { $sent = "$sent $word" }
$sent = $sent.Substring(1)

Write-Host $sent

How to select option in drop down using Capybara

It is not a direct answer, but you can (if your server permit):

1) Create a model for your Organization; extra: It will be easier to populate your HTML.

2) Create a factory (FactoryGirl) for your model;

3) Create a list (create_list) with the factory;

4) 'pick' (sample) a Organization from the list with:

# Random select
option = Organization.all.sample 

# Select the FIRST(0) by id
option = Organization.all[0] 

# Select the SECOND(1) after some restriction
option = Organization.where(some_attr: some_value)[2]
option = Organization.where("some_attr OP some_value")[2] #OP is "=", "<", ">", so on... 

Eclipse not recognizing JVM 1.8

Here are steps:

  • download 1.8 JDK from this site
  • install it
  • copy the jre folder & paste it in "C:\Program Files (x86)\EclipseNeon\"
  • rename the folder to "jre"
  • start the eclipse again

It should work.

How do I connect to a specific Wi-Fi network in Android programmatically?

You need to create WifiConfiguration instance like this:

String networkSSID = "test";
String networkPass = "pass";

WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\"";   // Please note the quotes. String should contain ssid in quotes

Then, for WEP network you need to do this:

conf.wepKeys[0] = "\"" + networkPass + "\""; 
conf.wepTxKeyIndex = 0;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); 

For WPA network you need to add passphrase like this:

conf.preSharedKey = "\""+ networkPass +"\"";

For Open network you need to do this:

conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

Then, you need to add it to Android wifi manager settings:

WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); 
wifiManager.addNetwork(conf);

And finally, you might need to enable it, so Android connects to it:

List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
    if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
         wifiManager.disconnect();
         wifiManager.enableNetwork(i.networkId, true);
         wifiManager.reconnect();               

         break;
    }           
 }

UPD: In case of WEP, if your password is in hex, you do not need to surround it with quotes.

SQL Server: Cannot insert an explicit value into a timestamp column

According to MSDN, timestamp

Is a data type that exposes automatically generated, unique binary numbers within a database. timestamp is generally used as a mechanism for version-stamping table rows. The storage size is 8 bytes. The timestamp data type is just an incrementing number and does not preserve a date or a time. To record a date or time, use a datetime data type.

You're probably looking for the datetime data type instead.

Cron and virtualenv

Don't look any further:

0 3 * * * /usr/bin/env bash -c 'cd /home/user/project && source /home/user/project/env/bin/activate && ./manage.py command arg' > /dev/null 2>&1

Generic approach:

* * * * * /usr/bin/env bash -c 'YOUR_COMMAND_HERE' > /dev/null 2>&1

The beauty about this is you DO NOT need to change the SHELL variable for crontab from sh to bash

How to delete a localStorage item when the browser window/tab is closed?

localStorage.removeItem(key);  //item

localStorage.clear(); //all items

How to return history of validation loss in Keras

I have also found that you can use verbose=2 to make keras print out the Losses:

history = model.fit(X, Y, validation_split=0.33, nb_epoch=150, batch_size=10, verbose=2)

And that would print nice lines like this:

Epoch 1/1
 - 5s - loss: 0.6046 - acc: 0.9999 - val_loss: 0.4403 - val_acc: 0.9999

According to their documentation:

verbose: 0, 1, or 2. Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch.

How to include() all PHP files from a directory?

If there are NO dependencies between files... here is a recursive function to include_once ALL php files in ALL subdirs:

$paths = array();

function include_recursive( $path, $debug=false){
  foreach( glob( "$path/*") as $filename){        
    if( strpos( $filename, '.php') !== FALSE){ 
       # php files:
       include_once $filename;
       if( $debug) echo "<!-- included: $filename -->\n";
    } else { # dirs
       $paths[] = $filename; 
    }
  }
  # Time to process the dirs:
  for( $i=count($paths)-1; $i>0; $i--){
    $path = $paths[$i];
    unset( $paths[$i]);
    include_recursive( $path);
  }
}

include_recursive( "tree_to_include");
# or... to view debug in page source:
include_recursive( "tree_to_include", 'debug');

How to make a phone call in android and come back to my activity when the call is done?

  Intent callIntent = new Intent(Intent.ACTION_CALL);  
  callIntent.setData(Uri.parse("tel:"+number));  
   startActivity(callIntent);   

 **Add permission :**

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

Recursively add the entire folder to a repository

Both "git add *" and "git add SocialApp" called from top directory should add recursively all directories.

Probably you have no files in SocialApp/SourceCode/DevTrunk/SocialApp and this is the reason.

Try to call "touch SocialApp/SourceCode/DevTrunk/SocialApp/.temporary" (and check .gitignore) and then try git add again.

How to search for an element in an stl list?

What you can do and what you should do are different matters.

If the list is very short, or you are only ever going to call find once then use the linear approach above.

However linear-search is one of the biggest evils I find in slow code, and consider using an ordered collection (set or multiset if you allow duplicates). If you need to keep a list for other reasons eg using an LRU technique or you need to maintain the insertion order or some other order, create an index for it. You can actually do that using a std::set of the list iterators (or multiset) although you need to maintain this any time your list is modified.

How do you run a .bat file from PHP?

You might need to run it via cmd, eg:

system("cmd /c C:[path to file]");

Bootstrap css hides portion of container below navbar navbar-fixed-top

This is handled by adding some padding to the top of the <body>.

As per Bootstrap's documentation on .navbar-fixed-top, try out your own values or use our snippet below. Tip: By default, the navbar is 50px high.

  body {
    padding-top: 70px;
  }

Also, take a look at the source for this example and open starter-template.css.

Running sites on "localhost" is extremely slow

For people using a mac. When you're using different host names say test.local and test2.local. Try changing test.local to test.dev. I found out that Mac OS X lion controls the .local tld. So when you change it to something else it's faster.

And of course use above suggestions like turning off the ipv6 reference in your hosts file:
#::1 localhost

and setting this in the hosts file: 127.0.0.1 localhost

so it points to ipv4.

How do I make a composite key with SQL Server Management Studio?

Open up the table designer in SQL Server Management Studio (right-click table and select 'Design')

Holding down the Ctrl key highlight two or more columns in the left hand table margin

Hit the little 'Key' on the standard menu bar at the top

You're done..

:-)

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

How to check if a string is numeric?

Use this

public static boolean isNum(String strNum) {
    boolean ret = true;
    try {

        Double.parseDouble(strNum);

    }catch (NumberFormatException e) {
        ret = false;
    }
    return ret;
}

Difference between e.target and e.currentTarget

I like visual answers.

enter image description here

When you click #btn, two event handlers get called and they output what you see in the picture.

Demo here: https://jsfiddle.net/ujhe1key/

How to apply an XSLT Stylesheet in C#

This might help you

public static string TransformDocument(string doc, string stylesheetPath)
{
    Func<string,XmlDocument> GetXmlDocument = (xmlContent) =>
     {
         XmlDocument xmlDocument = new XmlDocument();
         xmlDocument.LoadXml(xmlContent);
         return xmlDocument;
     };

    try
    {
        var document = GetXmlDocument(doc);
        var style = GetXmlDocument(File.ReadAllText(stylesheetPath));

        System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform();
        transform.Load(style); // compiled stylesheet
        System.IO.StringWriter writer = new System.IO.StringWriter();
        XmlReader xmlReadB = new XmlTextReader(new StringReader(document.DocumentElement.OuterXml));
        transform.Transform(xmlReadB, null, writer);
        return writer.ToString();
    }
    catch (Exception ex)
    {
        throw ex;
    }

}   

Difference between drop table and truncate table?

truncate removes all the rows, but not the table itself, it is essentially equivalent to deleting with no where clause, but usually faster.

Uncaught TypeError: data.push is not a function

one things to remember push work only with array[] not object{}.

if you want to add Like object o inside inside n


_x000D_
_x000D_
a={ b:"c",
D:"e",
F: {g:"h",
I:"j",
k:{ l:"m"
}}
}

a.F.k.n = { o: "p" };
a.F.k.n = { o: "p" };
console.log(a);
_x000D_
_x000D_
_x000D_

System.out.println() shortcut on Intellij IDEA

On MAC you can do sout + return or ?+j (cmd+j) opens live template suggestions, enter sout to choose System.out.println();

HTML Upload MAX_FILE_SIZE does not appear to work

Actually, it doesn't really work. You can find an explanation in one of the comments in the manual page: http://www.php.net/manual/en/features.file-upload.php#74692

Answer to updated question: the obvious difference is that server-side checks are reliable, client-side checks are not.

No content to map due to end-of-input jackson parser

I got this error when sending a GET request with postman. The request required no parameters. My mistake was I had a blank line in the request body.

Index Error: list index out of range (Python)

Generally it means that you are providing an index for which a list element does not exist.

E.g, if your list was [1, 3, 5, 7], and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

You should execute the next query:

GRANT ALL ON TABLE mytable TO myuser;

Or if your error is in a view then maybe the table does not have permission, so you should execute the next query:

GRANT ALL ON TABLE tbm_grupo TO myuser;

How to fix error with xml2-config not found when installing PHP from sources?

I had the same issue when I used a DockerFile. My Docker is based on the php:5.5-apache image.

I got that error when executing the command "RUN docker-php-ext-install soap"

I have solved it by adding the following command to my DockerFile

"RUN apt-get update && apt-get install -y libxml2-dev"

get UTC timestamp in python with datetime

If input datetime object is in UTC:

>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0)
>>> timestamp = (dt - datetime(1970, 1, 1)).total_seconds()
1199145600.0

Note: it returns float i.e., microseconds are represented as fractions of a second.

If input date object is in UTC:

>>> from datetime import date
>>> utc_date = date(2008, 1, 1)
>>> timestamp = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * 24*60*60
1199145600

See more details at Converting datetime.date to UTC timestamp in Python.

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

This is not possible with css, but I have used one css trick in one of my website, please check if this works for you.

The trick is: wrap the input box with a div and make it relative, place a transparent image inside the div and make it absolute over the input text box, so that no one can edit it.

css

.txtBox{
    width:250px;
    height:25px;
    position:relative;
}
.txtBox input{
    width:250px;
    height:25px;
}
.txtBox img{
    position:absolute;
    top:0;
    left:0
}

html

<div class="txtBox">
<input name="" type="text" value="Text Box" />
<img src="http://dev.w3.org/2007/mobileok-ref/test/data/ROOT/GraphicsForSpacingTest/1/largeTransparent.gif" width="250" height="25" alt="" />
</div>

jsFiddle File

Removing index column in pandas when reading a csv

If your problem is same as mine where you just want to reset the column headers from 0 to column size. Do

df = pd.DataFrame(df.values);

EDIT:

Not a good idea if you have heterogenous data types. Better just use

df.columns = range(len(df.columns))

How do I add a library project to Android Studio?

You can do this easily. Go to menu File -> New -> Import Module...:

Enter image description here

Browse for the directory which contains the module. Click Finish:

Enter image description here

Go to Project Structure and add Module Dependency:

Enter image description here

Note: If you receive an SDK error, update that one.

How do I get the classes of all columns in a data frame?

You can use purrr as well, which is similar to apply family functions:

as.data.frame(purrr::map_chr(mtcars, class))
purrr::map_df(mtcars, class)

How can I calculate the number of lines changed between two commits in Git?

I just solved this problem for myself, so I'll share what I came up with. Here's the end result:

> git summary --since=yesterday
total: 114 file changes, 13800 insertions(+) 638 deletions(-)

The underlying command looks like this:

git log --numstat --format="" "$@" | awk '{files += 1}{ins += $1}{del += $2} END{print "total: "files" files, "ins" insertions(+) "del" deletions(-)"}'

Note the $@ in the log command to pass on your arguments such as --author="Brian" or --since=yesterday.

Escaping the awk to put it into a git alias was messy, so instead, I put it into an executable script on my path (~/bin/git-stat-sum), then used the script in the alias in my .gitconfig:

[alias]
    summary = !git-stat-sum \"$@\"

And it works really well. One last thing to note is that file changes is the number of changes to files, not the number of unique files changed. That's what I was looking for, but it may not be what you expect.

Here's another example or two

git summary --author=brian
git summary master..dev
# combine them as you like
git summary --author=brian master..dev
git summary --all

Really, you should be able to replace any git log command with git summary.

Prevent flex items from overflowing a container

max-width works for me.

aside {
  flex: 0 1 200px;
  max-width: 200px;
}

Variables of CSS pre-processors allows to avoid hard-coding.

aside {
  $WIDTH: 200px;
  flex: 0 1 $WIDTH;
  max-width: $WIDTH;
}

overflow: hidden also works, but I lately I try do not use it because it hides the elements as popups and dropdowns.

How to build minified and uncompressed bundle with webpack?

You can format your webpack.config.js like this:

var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');

module.exports = {
    context: __dirname,
    devtool: debug ? "inline-sourcemap" : null,
    entry: "./entry.js",
    output: {
        path: __dirname + "/dist",
        filename: "library.min.js"
    },
    plugins: debug ? [] : [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
    ],
};'

And then to build it unminified run (while in the project's main directory):

$ webpack

To build it minified run:

$ NODE_ENV=production webpack

Notes: Make sure that for the unminified version you change the output file name to library.js and for the minified library.min.js so they do not overwrite each other.

SQL Server Text type vs. varchar data type

In SQL server 2005 new datatypes were introduced: varchar(max) and nvarchar(max) They have the advantages of the old text type: they can contain op to 2GB of data, but they also have most of the advantages of varchar and nvarchar. Among these advantages are the ability to use string manipulation functions such as substring().

Also, varchar(max) is stored in the table's (disk/memory) space while the size is below 8Kb. Only when you place more data in the field, it's is stored out of the table's space. Data stored in the table's space is (usually) retrieved quicker.

In short, never use Text, as there is a better alternative: (n)varchar(max). And only use varchar(max) when a regular varchar is not big enough, ie if you expect teh string that you're going to store will exceed 8000 characters.

As was noted, you can use SUBSTRING on the TEXT datatype,but only as long the TEXT fields contains less than 8000 characters.

Detect URLs in text with JavaScript

try this:

function isUrl(s) {
    if (!isUrl.rx_url) {
        // taken from https://gist.github.com/dperini/729294
        isUrl.rx_url=/^(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i;
        // valid prefixes
        isUrl.prefixes=['http:\/\/', 'https:\/\/', 'ftp:\/\/', 'www.'];
        // taken from https://w3techs.com/technologies/overview/top_level_domain/all
        isUrl.domains=['com','ru','net','org','de','jp','uk','br','pl','in','it','fr','au','info','nl','ir','cn','es','cz','kr','ua','ca','eu','biz','za','gr','co','ro','se','tw','mx','vn','tr','ch','hu','at','be','dk','tv','me','ar','no','us','sk','xyz','fi','id','cl','by','nz','il','ie','pt','kz','io','my','lt','hk','cc','sg','edu','pk','su','bg','th','top','lv','hr','pe','club','rs','ae','az','si','ph','pro','ng','tk','ee','asia','mobi'];
    }

    if (!isUrl.rx_url.test(s)) return false;
    for (let i=0; i<isUrl.prefixes.length; i++) if (s.startsWith(isUrl.prefixes[i])) return true;
    for (let i=0; i<isUrl.domains.length; i++) if (s.endsWith('.'+isUrl.domains[i]) || s.includes('.'+isUrl.domains[i]+'\/') ||s.includes('.'+isUrl.domains[i]+'?')) return true;
    return false;
}

function isEmail(s) {
    if (!isEmail.rx_email) {
        // taken from http://stackoverflow.com/a/16016476/460084
        var sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
        var sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
        var sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
        var sQuotedPair = '\\x5c[\\x00-\\x7f]';
        var sDomainLiteral = '\\x5b(' + sDtext + '|' + sQuotedPair + ')*\\x5d';
        var sQuotedString = '\\x22(' + sQtext + '|' + sQuotedPair + ')*\\x22';
        var sDomain_ref = sAtom;
        var sSubDomain = '(' + sDomain_ref + '|' + sDomainLiteral + ')';
        var sWord = '(' + sAtom + '|' + sQuotedString + ')';
        var sDomain = sSubDomain + '(\\x2e' + sSubDomain + ')*';
        var sLocalPart = sWord + '(\\x2e' + sWord + ')*';
        var sAddrSpec = sLocalPart + '\\x40' + sDomain; // complete RFC822 email address spec
        var sValidEmail = '^' + sAddrSpec + '$'; // as whole string

        isEmail.rx_email = new RegExp(sValidEmail);
    }

    return isEmail.rx_email.test(s);
}

will also recognize urls such as google.com , http://www.google.bla , http://google.bla , www.google.bla but not google.bla

How can I see what I am about to push with git?

To see which files are changed and view the actual code changes compared to the master branch you could use:

git diff --stat --patch origin master

NOTE: If you happen to use any of the Intellij IDEs then you can right-click your top-level project, select Git > Compare with branch > and pick the origin you want e.g. origin/master. In the file tree that will appear you can double-click the files to see a visual diff. Unlike the command-line option above you can edit your local versions from the diff window.

Full screen background image in an activity

There are several ways you can do it.

Option 1:

Create different perfect images for different dpi and place them in related drawable folder. Then set

android:background="@drawable/your_image"

Option 2:

Add a single large image. Use FrameLayout. As a first child add an ImageView. Set the following in your ImageView.

android:src="@drawable/your_image"
android:scaleType = "centerCrop"

concatenate two database columns into one resultset column

The SQL standard way of doing this would be:

SELECT COALESCE(field1, '') || COALESCE(field2, '') || COALESCE(field3, '') FROM table1

Example:

INSERT INTO table1 VALUES ('hello', null, 'world');
SELECT COALESCE(field1, '') || COALESCE(field2, '') || COALESCE(field3, '') FROM table1;

helloworld

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

So while this is answered and accepted it still came up as a top search result and the answers though laid out (after lots of research) left me scratching my head and digging a lot further. So here's a quick layout of how I resolved the issue.

Assuming my server is myserver.myhome.com and my static IP address is 192.168.1.150:

  1. Edit the hosts file

    $ sudo nano -w /etc/hosts
    
    127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
    
    127.0.0.1 myserver.myhome.com myserver
    
    192.168.1.150 myserver.myhome.com myserver
    
    ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
    ::1 myserver.myhome.com myserver
    
  2. Edit httpd.conf

    $ sudo nano -w /etc/apache2/httpd.conf
    
    ServerName myserver.myhome.com
    
  3. Edit network

    $ sudo nano -w /etc/sysconfig/network HOSTNAME=myserver.myhome.com
    
  4. Verify

    $ hostname
    
    (output) myserver.myhome.com
    
    $ hostname -f
    
    (output) myserver.myhome.com
    
  5. Restart Apache

    $ sudo /etc/init.d/apache2 restart
    

It appeared the difference was including myserver.myhome.com to both the 127.0.0.1 as well as the static IP address 192.168.1.150 in the hosts file. The same on Ubuntu Server and CentOS.

"Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed

I tried the main parts of each answer, to no avail. What finally fixed it for me was to export the following environment variables:

LD_LIBRARY_PATH=/usr/local/lib:~/Qt/5.9.1/gcc_64/lib
QT_QPA_PLATFORM_PLUGIN_PATH=~/Qt/5.9.1/gcc_64/plugins/ 

How to configure Eclipse build path to use Maven dependencies?

Add this to .classpath file ..

<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
    <attributes>
        <attribute name="maven.pomderived" value="true"/>
    </attributes>
</classpathentry>

Thx

How to send a GET request from PHP?

I like using fsockopen open for this.

Autocompletion in Vim

is what you are looking for something like intellisense?

insevim seems to address the issue.

link to screenshots here

Angular - "has no exported member 'Observable'"

My resolution was adding the following import: import { of } from 'rxjs/observable/of';

So the overall code of hero.service.ts after the change is:

import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
import { of } from 'rxjs/observable/of';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class HeroService {

  constructor() { }

  getHeroes(): Observable<Hero[]> {
    return of(HEROES);
  }
}

Byte array to image conversion

First Install This Package:

Install-Package SixLabors.ImageSharp -Version 1.0.0-beta0007

[SixLabors.ImageSharp][1] [1]: https://www.nuget.org/packages/SixLabors.ImageSharp

Then use Below Code For Cast Byte Array To Image :

Image<Rgba32> image = Image.Load(byteArray); 

For Get ImageFormat Use Below Code:

IImageFormat format = Image.DetectFormat(byteArray);

For Mutate Image Use Below Code:

image.Mutate(x => x.Resize(new Size(1280, 960)));

how to compare two elements in jquery

The collection results you get back from a jQuery collection do not support set-based comparison. You can use compare the individual members one by one though, there are no utilities for this that I know of in jQuery.

Build not visible in itunes connect

Check your all privacy access policy option in Info.plist file.

Android Studio says "cannot resolve symbol" but project compiles

No idea if this will work or not but my only thought so far: right click the jar file in file tree within AS and select "Add as library..."

EDIT: You can do "File" -> "Invalidate Caches...", and select "Invalidate and Restart" option to fix this.

EDIT 2: This fix should work for all similar incidents and is not a twitter4j specific resolution.

How to run a Powershell script from the command line and pass a directory as a parameter

Using the flag -Command you can execute your entire powershell line as if it was a command in the PowerShell prompt:

powershell -Command "& '<PATH_TO_PS1_FILE>' '<ARG_1>' '<ARG_2>' ... '<ARG_N>'"

This solved my issue with running PowerShell commands in Visual Studio Post-Build and Pre-Build events.

How to include CSS file in Symfony 2 and Twig?

The other answers are valid, but the Official Symfony Best Practices guide suggests using the web/ folder to store all assets, instead of different bundles.

Scattering your web assets across tens of different bundles makes it more difficult to manage them. Your designers' lives will be much easier if all the application assets are in one location.

Templates also benefit from centralizing your assets, because the links are much more concise[...]

I'd add to this by suggesting that you only put micro-assets within micro-bundles, such as a few lines of styles only required for a button in a button bundle, for example.

How can I copy data from one column to another in the same table?

This will update all the rows in that columns if safe mode is not enabled.

UPDATE table SET columnB = columnA;

If safe mode is enabled then you will need to use a where clause. I use primary key as greater than 0 basically all will be updated

UPDATE table SET columnB = columnA where table.column>0;

Comments in .gitignore?

Do git help gitignore

You will get the help page with following line:

A line starting with # serves as a comment.

"The system cannot find the file specified" when running C++ program

I got this problem during debug mode and the missing file was from a static library I was using. The problem was solved by using step over instead of step into during debugging

The program can't start because MSVCR110.dll is missing from your computer

You can download the required files from the Microsoft website or online or reinstall the Visual studio 2012 to fix this.

Clear text from textarea with selenium

Option a)

If you want to ensure keyboard events are fired, consider using sendKeys(CharSequence).

Example 1:

 from selenium.webdriver.common.keys import Keys
 # ...
 webElement.sendKeys(Keys.CONTROL + "a");
 webElement.sendKeys(Keys.DELETE);

Example 2:

 from selenium.webdriver.common.keys import Keys
 # ...
 webElement.sendKeys(Keys.BACK_SPACE); //do repeatedly, e.g. in while loop

WebElement

There are many ways to get the required WebElement, e.g.:

  • driver.find_element_by_id
  • driver.find_element_by_xpath
  • driver.find_element

Option b)

 webElement.clear();

If this element is a text entry element, this will clear the value.

Note that the events fired by this event may not be as you'd expect. In particular, we don't fire any keyboard or mouse events.

Can I specify maxlength in css?

As others have answered, there is no current way to add maxlength directly to a CSS class.

However, this creative solution can achieve what you are looking for.

I have the jQuery in a file named maxLengths.js which I reference in site (site.master for ASP)

run the snippet to see it in action, works well.

jquery, css, html:

_x000D_
_x000D_
$(function () {_x000D_
    $(".maxLenAddress1").keypress(function (event) {_x000D_
_x000D_
        if ($(this).val().length == 5) { /* obv 5 is too small for an address field, just want to use as an example though */_x000D_
            return false;_x000D_
        } else {_x000D_
            return true;_x000D_
        }_x000D_
_x000D_
    });_x000D_
});
_x000D_
.maxLenAddress1{} /* this is here mostly for intellisense usage, but can be altered if you like */
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="text" class="maxLenAddress1" />
_x000D_
_x000D_
_x000D_

The advantage of using this: if it is decided the max length for this type of field needs to be pushed out or in across your entire application you can change it in one spot. Comes in handy for field lengths for things like customer codes, full name fields, email fields, any field common across your application.

Force to open "Save As..." popup open at text link click for PDF in HTML

With large PDF files the browser hangs. In Mozilla, menu Tools ? Options ? Applications, then next to the content type Adobe Acrobat document. In the Action drop down, select Always ask.

This did not work for me, so what worked was:

Menu Tools* ? Add-ons ? Adobe Acrobat (Adobe PDF plugin for Firefox) ? DISABLE. Now I am able to download e-books!

'sprintf': double precision in C

From your question it seems like you are using C99, as you have used %lf for double.

To achieve the desired output replace:

sprintf(aa, "%lf", a);

with

sprintf(aa, "%0.7f", a);

The general syntax "%A.B" means to use B digits after decimal point. The meaning of the A is more complicated, but can be read about here.

Compare two data.frames to find the rows in data.frame 1 that are not present in data.frame 2

Maybe it is too simplistic, but I used this solution and I find it very useful when I have a primary key that I can use to compare data sets. Hope it can help.

a1 <- data.frame(a = 1:5, b = letters[1:5])
a2 <- data.frame(a = 1:3, b = letters[1:3])
different.names <- (!a1$a %in% a2$a)
not.in.a2 <- a1[different.names,]

Check if checkbox is NOT checked on click - jQuery

The answer already posted will work. If you want to use the jQuery :not you can do this:

if ($(this).is(':not(:checked)'))

or

if ($(this).attr('checked') == false)

What are the differences between a HashMap and a Hashtable in Java?

Since Hashtable in Java is a subclass of Dictionary class which is now obsolete due to the existence of Map Interface, it is not used anymore. Moreover, there isn't anything you can't do with a class that implements the Map Interface that you can do with a Hashtable.

Jquery function return value

The return statement you have is stuck in the inner function, so it won't return from the outer function. You just need a little more code:

function getMachine(color, qty) {
    var returnValue = null;
    $("#getMachine li").each(function() {
        var thisArray = $(this).text().split("~");
        if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
            returnValue = thisArray[3];
            return false; // this breaks out of the each
        }
    });
    return returnValue;
}

var retval = getMachine(color, qty);

Cannot assign requested address using ServerSocket.socketBind

The port is taken by another process. Possibly an unterminated older run of your program. Make sure your program has exited cleanly or kill it.

Avoiding "resource is out of sync with the filesystem"

If you are a regular Eclipse user than you might have got this error many times. The error simply says, “you’ve made changes in files in your workspace from outside eclipse”. The simplest solution would be to select the project and press F5 (Right click -> Refresh).

if you need more explanation you can read from this web site

How to insert tab character when expandtab option is on in Vim

From the documentation on expandtab:

To insert a real tab when expandtab is on, use CTRL-V<Tab>. See also :retab and ins-expandtab.
This option is reset when the paste option is set and restored when the paste option is reset.

So if you have a mapping for toggling the paste option, e.g.

set pastetoggle=<F2>

you could also do <F2>Tab<F2>.

How to convert list to string

>>> L = [1,2,3]       
>>> " ".join(str(x) for x in L)
'1 2 3'

How to convert View Model into JSON object in ASP.NET MVC?

<htmltag id=’elementId’ data-ZZZZ’=’@Html.Raw(Json.Encode(Model))’ />

Refer https://highspeedlowdrag.wordpress.com/2014/08/23/mvc-data-to-jquery-data/

I did below and it works like charm.

<input id="hdnElement" class="hdnElement" type="hidden" value='@Html.Raw(Json.Encode(Model))'>

How to record phone calls in android?

The answer of pratt is bit uncomplete, because when you restart your device your app will working stop, recording stop, its become useless.

i m adding some line that copy in your project for complete working of Pratt answer.

<receiver
        android:name=".DeviceAdminDemo"
        android:permission="android.permission.BIND_DEVICE_ADMIN">
        <meta-data
            android:name="android.app.admin"
            android:resource="@xml/device_admin" />

        <intent-filter>
            <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
            <action android:name="android.app.action.DEVICE_ADMIN_DISABLED" />
            <action android:name="android.app.action.DEVICE_ADMIN_DISABLE_REQUESTED" />
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <category android:name="android.intent.category.HOME" />
        </intent-filter>
    </receiver>

put this code in onReceive of DeviceAdminDemo

@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);

    context.stopService(new Intent(context, TService.class));
    Intent myIntent = new Intent(context, TService.class);
    context.startService(myIntent);

}

How to access single elements in a table in R

?"[" pretty much covers the various ways of accessing elements of things.

Under usage it lists these:

x[i]
x[i, j, ... , drop = TRUE]
x[[i, exact = TRUE]]
x[[i, j, ..., exact = TRUE]]
x$name
getElement(object, name)

x[i] <- value
x[i, j, ...] <- value
x[[i]] <- value
x$i <- value

The second item is sufficient for your purpose

Under Arguments it points out that with [ the arguments i and j can be numeric, character or logical

So these work:

data[1,1]
data[1,"V1"]

As does this:

data$V1[1]

and keeping in mind a data frame is a list of vectors:

data[[1]][1]
data[["V1"]][1]

will also both work.

So that's a few things to be going on with. I suggest you type in the examples at the bottom of the help page one line at a time (yes, actually type the whole thing in one line at a time and see what they all do, you'll pick up stuff very quickly and the typing rather than copypasting is an important part of helping to commit it to memory.)

How to get first element in a list of tuples?

when I ran (as suggested above):

>>> a = [(1, u'abc'), (2, u'def')]
>>> import operator
>>> b = map(operator.itemgetter(0), a)
>>> b

instead of returning:

[1, 2]

I received this as the return:

<map at 0xb387eb8>

I found I had to use list():

>>> b = list(map(operator.itemgetter(0), a))

to successfully return a list using this suggestion. That said, I'm happy with this solution, thanks. (tested/run using Spyder, iPython console, Python v3.6)

Swift error : signal SIGABRT how to solve it

This is a very common error and can happen for multiple reasons. The most common is when an IBOUTLET/IBACTION connected to a view controller in the storyboard is deleted from the swift file but not from the storyboard. If this is not the case, use the log in the bottom toolbar to find out what the error is and diagnose it. You can use breakpoints and debugging to aid you in finding the error.

To find out how to fix the error please use this article that I found on Google: https://rayaans.com/fixing-the-notorious-sigabrt-error-in-xcode

PHP: cannot declare class because the name is already in use

Another option to include_once or require_once is to use class autoloading. http://php.net/manual/en/language.oop5.autoload.php

How to securely save username/password (local)?

If you are just going to verify/validate the entered user name and password, use the Rfc2898DerivedBytes class (also known as Password Based Key Derivation Function 2 or PBKDF2). This is more secure than using encryption like Triple DES or AES because there is no practical way to go from the result of RFC2898DerivedBytes back to the password. You can only go from a password to the result. See Is it ok to use SHA1 hash of password as a salt when deriving encryption key and IV from password string? for an example and discussion for .Net or String encrypt / decrypt with password c# Metro Style for WinRT/Metro.

If you are storing the password for reuse, such as supplying it to a third party, use the Windows Data Protection API (DPAPI). This uses operating system generated and protected keys and the Triple DES encryption algorithm to encrypt and decrypt information. This means your application does not have to worry about generating and protecting the encryption keys, a major concern when using cryptography.

In C#, use the System.Security.Cryptography.ProtectedData class. For example, to encrypt a piece of data, use ProtectedData.Protect():

// Data to protect. Convert a string to a byte[] using Encoding.UTF8.GetBytes().
byte[] plaintext; 

// Generate additional entropy (will be used as the Initialization vector)
byte[] entropy = new byte[20];
using(RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
    rng.GetBytes(entropy);
}

byte[] ciphertext = ProtectedData.Protect(plaintext, entropy,
    DataProtectionScope.CurrentUser);

Store the entropy and ciphertext securely, such as in a file or registry key with permissions set so only the current user can read it. To get access to the original data, use ProtectedData.Unprotect():

byte[] plaintext= ProtectedData.Unprotect(ciphertext, entropy,
    DataProtectionScope.CurrentUser);

Note that there are additional security considerations. For example, avoid storing secrets like passwords as a string. Strings are immutable, being they cannot be notified in memory so someone looking at the application's memory or a memory dump may see the password. Use SecureString or a byte[] instead and remember to dispose or zero them as soon as the password is no longer needed.

What's the function like sum() but for multiplication? product()?

I prefer the answers a and b above using functools.reduce() and the answer using numpy.prod(), but here is yet another solution using itertools.accumulate():

import itertools
import operator
prod = list(itertools.accumulate((3, 4, 5), operator.mul))[-1]

Do while loop in SQL Server 2008

I am not sure about DO-WHILE IN MS SQL Server 2008 but you can change your WHILE loop logic, so as to USE like DO-WHILE loop.

Examples are taken from here: http://blog.sqlauthority.com/2007/10/24/sql-server-simple-example-of-while-loop-with-continue-and-break-keywords/

  1. Example of WHILE Loop

    DECLARE @intFlag INT
    SET @intFlag = 1
    WHILE (@intFlag <=5)
    BEGIN
        PRINT @intFlag
        SET @intFlag = @intFlag + 1
    END
    GO
    

    ResultSet:

    1
    2
    3
    4
    5
    
  2. Example of WHILE Loop with BREAK keyword

    DECLARE @intFlag INT
    SET @intFlag = 1
    WHILE (@intFlag <=5)
    BEGIN
        PRINT @intFlag
        SET @intFlag = @intFlag + 1
        IF @intFlag = 4
            BREAK;
    END
    GO
    

    ResultSet:

    1
    2
    3
    
  3. Example of WHILE Loop with CONTINUE and BREAK keywords

    DECLARE @intFlag INT
    SET @intFlag = 1
    WHILE (@intFlag <=5)
    BEGIN
        PRINT @intFlag
        SET @intFlag = @intFlag + 1
        CONTINUE;
        IF @intFlag = 4 -- This will never executed
            BREAK;
    END
    GO
    

    ResultSet:

    1
    2
    3
    4
    5
    

But try to avoid loops at database level. Reference.

How to extract multiple JSON objects from one file?

So, as was mentioned in a couple comments containing the data in an array is simpler but the solution does not scale well in terms of efficiency as the data set size increases. You really should only use an iterator when you want to access a random object in the array, otherwise, generators are the way to go. Below I have prototyped a reader function which reads each json object individually and returns a generator.

The basic idea is to signal the reader to split on the carriage character "\n" (or "\r\n" for Windows). Python can do this with the file.readline() function.

import json
def json_reader(filename):
    with open(filename) as f:
        for line in f:
            yield json.loads(line)

However, this method only really works when the file is written as you have it -- with each object separated by a newline character. Below I wrote an example of a writer that separates an array of json objects and saves each one on a new line.

def json_writer(file, json_objects):
    with open(file, "w") as f:
        for jsonobj in json_objects:
            jsonstr = json.dumps(jsonobj)
            f.write(jsonstr + "\n")

You could also do the same operation with file.writelines() and a list comprehension:

...
    json_strs = [json.dumps(j) + "\n" for j in json_objects]
    f.writelines(json_strs)
...

And if you wanted to append the data instead of writing a new file just change open(file, "w") to open(file, "a").

In the end I find this helps a great deal not only with readability when I try and open json files in a text editor but also in terms of using memory more efficiently.

On that note if you change your mind at some point and you want a list out of the reader, Python allows you to put a generator function inside of a list and populate the list automatically. In other words, just write

lst = list(json_reader(file))

PHP post_max_size overrides upload_max_filesize

change in php.ini max_input_vars 1000

How to programmatically set style attribute in a view

If you are using the Support library, you could simply use

TextViewCompat.setTextAppearance(textView, R.style.AppTheme_TextStyle_ButtonDefault_Whatever);

for TextViews and Buttons. There are similar classes for the rest of Views :-)

How do I debug error ECONNRESET in Node.js?

Try adding these options to socket.io:

const options = { transports: ['websocket'], pingTimeout: 3000, pingInterval: 5000 };

I hope this will help you !

Why is exception.printStackTrace() considered bad practice?

First thing printStackTrace() is not expensive as you state, because the stack trace is filled when the exception is created itself.

The idea is to pass anything that goes to logs through a logger framework, so that the logging can be controlled. Hence instead of using printStackTrace, just use something like Logger.log(msg, exception);

How to Use UTF-8 Collation in SQL Server database?

Looks like this will be finally supported in the SQL Server 2019! SQL Server 2019 - whats new?

From BOL:

UTF-8 support

Full support for the widely used UTF-8 character encoding as an import or export encoding, or as database-level or column-level collation for text data. UTF-8 is allowed in the CHAR and VARCHAR datatypes, and is enabled when creating or changing an object’s collation to a collation with the UTF8 suffix.

For example,LATIN1_GENERAL_100_CI_AS_SC to LATIN1_GENERAL_100_CI_AS_SC_UTF8. UTF-8 is only available to Windows collations that support supplementary characters, as introduced in SQL Server 2012. NCHAR and NVARCHAR allow UTF-16 encoding only, and remain unchanged.

This feature may provide significant storage savings, depending on the character set in use. For example, changing an existing column data type with ASCII strings from NCHAR(10) to CHAR(10) using an UTF-8 enabled collation, translates into nearly 50% reduction in storage requirements. This reduction is because NCHAR(10) requires 22 bytes for storage, whereas CHAR(10) requires 12 bytes for the same Unicode string.

2019-05-14 update:

Documentation seems to be updated now and explains our options staring in MSSQL 2019 in section "Collation and Unicode Support".

2019-07-24 update:

Article by Pedro Lopes - Senior Program Manager @ Microsoft about introducing UTF-8 support for Azure SQL Database

Visual Studio Code compile on save

Step 1

In your tsconfig.json

"compileOnSave": true, // change it to true and save the application

if problem is still there then apply step-2

Step 2

Restart your editor

if still problem not resolved then apply step-3

Step 3

Change any route, revert it back and save the application. It'll start compiling. i.e.

const routes: Routes = [
  {
    path: '', // i.e. remove , (comma) and then insert it and save, it'll start compiling
    component: MyComponent
  }
]

How to change workspace and build record Root Directory on Jenkins?

EDIT: Per other comments, the "Advanced..." button appears to have been removed in more recent versions of Jenkins. If your version doesn't have it, see knorx's answer.

I had the same problem, and even after finding this old pull request I still had trouble finding where to specify the Workspace Root Directory or Build Record Root Directory at the system level, versus specifying a custom workspace for each job.

To set these:

  1. Navigate to Jenkins -> Manage Jenkins -> Configure System
  2. Right at the top, under Home directory, click the Advanced... button: advanced button under Home directory
  3. Now the fields for Workspace Root Directory and Build Record Root Directory appear: additional directory options
  4. The information that appears if you click the help bubbles to the left of each option is very instructive. In particular (from the Workspace Root Directory help):

    This value may include the following variables:

    • ${JENKINS_HOME} — Absolute path of the Jenkins home directory
    • ${ITEM_ROOTDIR} — Absolute path of the directory where Jenkins stores the configuration and related metadata for a given job
    • ${ITEM_FULL_NAME} — The full name of a given job, which may be slash-separated, e.g. foo/bar for the job bar in folder foo


    The value should normally include ${ITEM_ROOTDIR} or ${ITEM_FULL_NAME}, otherwise different jobs will end up sharing the same workspace.

Python Unicode Encode Error

A better solution:

if type(value) == str:
    # Ignore errors even if the string is not proper UTF-8 or has
    # broken marker bytes.
    # Python built-in function unicode() can do this.
    value = unicode(value, "utf-8", errors="ignore")
else:
    # Assume the value object has proper __unicode__() method
    value = unicode(value)

If you would like to read more about why:

http://docs.plone.org/manage/troubleshooting/unicode.html#id1

Is there a function to split a string in PL/SQL?

function numinstr(p_source in varchar2,p_token in varchar2)
return pls_integer
is
    v_occurrence pls_integer := 1;
    v_start pls_integer := 1;
    v_loc pls_integer;
begin
    v_loc:=instr(p_source, p_token, 1, 1);
    while v_loc > 0 loop
      v_occurrence := v_occurrence+1;
      v_start:=v_loc+1;
      v_loc:=instr(p_source, p_token, v_start, 1);
    end loop;
    return v_occurrence-1;
end numinstr;
  --
  --
  --
  --
function get_split_field(p_source in varchar2,p_delim in varchar2,nth pls_integer)
return varchar2
is
    v_num_delims pls_integer;
    first_pos pls_integer;
    final_pos pls_integer;
    len_delim pls_integer := length(p_delim);
    ret_len pls_integer;
begin
    v_num_delims := numinstr(p_source,p_delim);
    if nth < 1 or nth > v_num_delims+1 then
      return null;
    else
      if nth = 1 then
        first_pos := 1;
      else
        first_pos := instr(p_source, p_delim, 1, nth-1) + len_delim;
      end if;
      if nth > v_num_delims then
        final_pos := length(p_source);
      else
        final_pos := instr(p_source, p_delim, 1, nth) - 1;
      end if;
      ret_len := (final_pos - first_pos) + 1;
      return substr(p_source, first_pos, ret_len);
    end if;
end get_split_field;

Reading and writing environment variables in Python?

If you want to pass global variables into new scripts, you can create a python file that is only meant for holding global variables (e.g. globals.py). When you import this file at the top of the child script, it should have access to all of those variables.

If you are writing to these variables, then that is a different story. That involves concurrency and locking the variables, which I'm not going to get into unless you want.

How To Add An "a href" Link To A "div"?

try to implement with javascript this:

<div id="mydiv" onclick="myhref('http://web.com');" >some stuff </div>
<script type="text/javascript">
    function myhref(web){
      window.location.href = web;}
</script>

less than 10 add 0 to number

You can write a generic function to do this...

var numberFormat = function(number, width) {
    return new Array(+width + 1 - (number + '').length).join('0') + number;
}

jsFiddle.

That way, it's not a problem to deal with any arbitrarily width.

What's the difference between Git Revert, Checkout and Reset?

If you broke the tree but didn't commit the code, you can use git reset, and if you just want to restore one file, you can use git checkout.

If you broke the tree and committed the code, you can use git revert HEAD.

http://book.git-scm.com/4_undoing_in_git_-_reset,_checkout_and_revert.html

YouTube Autoplay not working

mute=1 or muted=1 as suggested by @Fab will work. However, if you wish to enable autoplay with sound you should add allow="autoplay" to your embedded <iframe>.

<iframe type="text/html" src="https://www.youtube.com/embed/-ePDPGXkvlw?autoplay=1" frameborder="0" allow="autoplay"></iframe>

This is officially supported and documented in Google's Autoplay Policy Changes 2017 post

Iframe delegation A feature policy allows developers to selectively enable and disable use of various browser features and APIs. Once an origin has received autoplay permission, it can delegate that permission to cross-origin iframes with a new feature policy for autoplay. Note that autoplay is allowed by default on same-origin iframes.

<!-- Autoplay is allowed. -->
<iframe src="https://cross-origin.com/myvideo.html" allow="autoplay">

<!-- Autoplay and Fullscreen are allowed. -->
<iframe src="https://cross-origin.com/myvideo.html" allow="autoplay; fullscreen">

When the feature policy for autoplay is disabled, calls to play() without a user gesture will reject the promise with a NotAllowedError DOMException. And the autoplay attribute will also be ignored.

How to use OpenFileDialog to select a folder?

this should be the most obvious and straight forward way

using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
{

   System.Windows.Forms.DialogResult result = dialog.ShowDialog();

   if(result == System.Windows.Forms.DialogResult.OK)
   {
      selectedFolder = dialog.SelectedPath;
   }

}

Dictionary of dictionaries in Python?

dictionary's setdefault is a good way to update an existing dict entry if it's there, or create a new one if it's not all in one go:

Looping style:

# This is our sample data
data = [("Milter", "Miller", 4), ("Milter", "Miler", 4), ("Milter", "Malter", 2)]

# dictionary we want for the result
dictionary = {}

# loop that makes it work
for realName, falseName, position in data:
    dictionary.setdefault(realName, {})[falseName] = position

dictionary now equals:

{'Milter': {'Malter': 2, 'Miler': 4, 'Miller': 4}}

windows batch file rename

Use REN Command

Ren is for rename

ren ( where the file is located ) ( the new name )

example

ren C:\Users\&username%\Desktop\aaa.txt bbb.txt

it will change aaa.txt to bbb.txt

Your code will be :

ren (file located)AAA_a001.jpg a001.AAA.jpg

ren (file located)BBB_a002.jpg a002.BBB.jpg

ren (file located)CCC_a003.jpg a003.CCC.jpg

and so on

IT WILL NOT WORK IF THERE IS SPACES!

Hope it helps :D

How does Python's super() work with multiple inheritance?

I would like to add to what @Visionscaper says at the top:

Third --> First --> object --> Second --> object

In this case the interpreter doesnt filter out the object class because its duplicated, rather its because Second appears in a head position and doesnt appear in the tail position in a hierarchy subset. While object only appears in tail positions and is not considered a strong position in C3 algorithm to determine priority.

The linearisation(mro) of a class C, L(C), is the

  • the Class C
  • plus the merge of
    • linearisation of its parents P1, P2, .. = L(P1, P2, ...) and
    • the list of its parents P1, P2, ..

Linearised Merge is done by selecting the common classes that appears as the head of lists and not the tail since order matters(will become clear below)

The linearisation of Third can be computed as follows:

    L(O)  := [O]  // the linearization(mro) of O(object), because O has no parents

    L(First)  :=  [First] + merge(L(O), [O])
               =  [First] + merge([O], [O])
               =  [First, O]

    // Similarly, 
    L(Second)  := [Second, O]

    L(Third)   := [Third] + merge(L(First), L(Second), [First, Second])
                = [Third] + merge([First, O], [Second, O], [First, Second])
// class First is a good candidate for the first merge step, because it only appears as the head of the first and last lists
// class O is not a good candidate for the next merge step, because it also appears in the tails of list 1 and 2, 
                = [Third, First] + merge([O], [Second, O], [Second])
// class Second is a good candidate for the second merge step, because it appears as the head of the list 2 and 3
                = [Third, First, Second] + merge([O], [O])            
                = [Third, First, Second, O]

Thus for a super() implementation in the following code:

class First(object):
  def __init__(self):
    super(First, self).__init__()
    print "first"

class Second(object):
  def __init__(self):
    super(Second, self).__init__()
    print "second"

class Third(First, Second):
  def __init__(self):
    super(Third, self).__init__()
    print "that's it"

it becomes obvious how this method will be resolved

Third.__init__() ---> First.__init__() ---> Second.__init__() ---> 
Object.__init__() ---> returns ---> Second.__init__() -
prints "second" - returns ---> First.__init__() -
prints "first" - returns ---> Third.__init__() - prints "that's it"

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

If you use MAMP, you might have to set the socket: unix_socket: /Applications/MAMP/tmp/mysql/mysql.sock

Genymotion error at start 'Unable to load virtualbox'

For Windows there are 2 installers. Did you use the bundle containing VirtualBox installer? It is call Windows 32/64 bits (with VirtualBox).

Connecting to Microsoft SQL server using Python

An alternative approach would be installing Microsoft ODBC Driver 13, then replace SQLOLEDB with ODBC Driver 13 for SQL Server

Regards.

How to auto-generate a C# class file from a JSON string

Five options:

Pros and Cons:

  • jsonclassgenerator converts to PascalCase but the others do not.

  • app.quicktype.io has some logic to recognize dictionaries and handle JSON properties whose names are invalid c# identifiers.

Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?

Since we're all guessing, I might as well give mine: I've always thought it stood for Python. That may sound pretty stupid -- what, P for Python?! -- but in my defense, I vaguely remembered this thread [emphasis mine]:

Subject: Claiming (?P...) regex syntax extensions

From: Guido van Rossum ([email protected])

Date: Dec 10, 1997 3:36:19 pm

I have an unusual request for the Perl developers (those that develop the Perl language). I hope this (perl5-porters) is the right list. I am cc'ing the Python string-sig because it is the origin of most of the work I'm discussing here.

You are probably aware of Python. I am Python's creator; I am planning to release a next "major" version, Python 1.5, by the end of this year. I hope that Python and Perl can co-exist in years to come; cross-pollination can be good for both languages. (I believe Larry had a good look at Python when he added objects to Perl 5; O'Reilly publishes books about both languages.)

As you may know, Python 1.5 adds a new regular expression module that more closely matches Perl's syntax. We've tried to be as close to the Perl syntax as possible within Python's syntax. However, the regex syntax has some Python-specific extensions, which all begin with (?P . Currently there are two of them:

(?P<foo>...) Similar to regular grouping parentheses, but the text
matched by the group is accessible after the match has been performed, via the symbolic group name "foo".

(?P=foo) Matches the same string as that matched by the group named "foo". Equivalent to \1, \2, etc. except that the group is referred
to by name, not number.

I hope that this Python-specific extension won't conflict with any future Perl extensions to the Perl regex syntax. If you have plans to use (?P, please let us know as soon as possible so we can resolve the conflict. Otherwise, it would be nice if the (?P syntax could be permanently reserved for Python-specific syntax extensions. (Is there some kind of registry of extensions?)

to which Larry Wall replied:

[...] There's no registry as of now--yours is the first request from outside perl5-porters, so it's a pretty low-bandwidth activity. (Sorry it was even lower last week--I was off in New York at Internet World.)

Anyway, as far as I'm concerned, you may certainly have 'P' with my blessing. (Obviously Perl doesn't need the 'P' at this point. :-) [...]

So I don't know what the original choice of P was motivated by -- pattern? placeholder? penguins? -- but you can understand why I've always associated it with Python. Which considering that (1) I don't like regular expressions and avoid them wherever possible, and (2) this thread happened fifteen years ago, is kind of odd.

Data was not saved: object references an unsaved transient instance - save the transient instance before flushing

To add my 2 cents, I got this same issue when I m accidentally sending null as the ID. Below code depicts my scenario (and anyway OP didn't mention any specific scenario).

Employee emp = new Employee();
emp.setDept(new Dept(deptId)); // -----> when deptId PKID is null, same error will be thrown
// calls to other setters...
em.persist(emp);

Here I m setting the existing department id to a new employee instance without actually getting the department entity first, as I don't want to another select query to fire.

In some scenarios, deptId PKID is coming as null from calling method and I m getting the same error.

So, watch for null values for PK ID

Same answer given here

"Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

This error might be caused by the jQuery event-aliases like .load(), .unload() or .error() that all are deprecated since jQuery 1.8. Lookup for these aliases in your code and replace them with the .on() method instead. For example, replace the following deprecated excerpt:

$(window).load(function(){...});

with the following:

$(window).on('load', function(){ ...});

How to use function srand() with time.h?

If you chose to srand, it is a good idea to then call rand() at least once before you use it, because it is a kind of horrible primitive psuedo-random generator. See Stack Overflow question Why does rand() % 7 always return 0?.

srand(time(NULL));
rand();
//Now use rand()

If available, either random or arc4rand would be better.