Programs & Examples On #M2crypto

M2Crypto is the most complete Python wrapper for OpenSSL featuring RSA, DSA, DH, HMACs, message digests, symmetric ciphers (including AES); SSL functionality to implement clients and servers; HTTPS extensions to Python's httplib, urllib, and xmlrpclib; unforgeable HMAC'ing AuthCookies for web session management; FTP/TLS client and server; S/MIME; ZServerSSL.

How do I update a Python package?

How was the package originally installed? If it was via apt, you could just be able to do apt-get remove python-m2crypto

If you installed it via easy_install, I'm pretty sure the only way is to just trash the files under lib, shared, etc..

My recommendation in the future? Use something like pip to install your packages. Furthermore, you could look up into something called virtualenv so your packages are stored on a per-environment basis, rather than solely on root.

With pip, it's pretty easy:

pip install m2crypto

But you can also install from git, svn, etc repos with the right address. This is all explained in the pip documentation

Check if textbox has empty value

The check can be done like this:

if (!!inp.val()) {

}

and even shorter:

if (inp.val()) {

}

Error "Metadata file '...\Release\project.dll' could not be found in Visual Studio"

in my case i was working on a branch off master. so i checked out master branch, ran a build and then checked out my branch. It fixed the issue. If you already are on master, i suggest you check out previous commit and then build it.

How to add rows dynamically into table layout

Here's technique I figured out after a bit of trial and error that allows you to preserve your XML styles and avoid the issues of using a <merge/> (i.e. inflate() requires a merge to attach to root, and returns the root node). No runtime new TableRow()s or new TextView()s required.

Code

Note: Here CheckBalanceActivity is some sample Activity class

TableLayout table = (TableLayout)CheckBalanceActivity.this.findViewById(R.id.attrib_table);
for(ResourceBalance b : xmlDoc.balance_info)
{
    // Inflate your row "template" and fill out the fields.
    TableRow row = (TableRow)LayoutInflater.from(CheckBalanceActivity.this).inflate(R.layout.attrib_row, null);
    ((TextView)row.findViewById(R.id.attrib_name)).setText(b.NAME);
    ((TextView)row.findViewById(R.id.attrib_value)).setText(b.VALUE);
    table.addView(row);
}
table.requestLayout();     // Not sure if this is needed.

attrib_row.xml

<?xml version="1.0" encoding="utf-8"?>
<TableRow style="@style/PlanAttribute"  xmlns:android="http://schemas.android.com/apk/res/android">
    <TextView
        style="@style/PlanAttributeText"
        android:id="@+id/attrib_name"
        android:textStyle="bold"/>
    <TextView
        style="@style/PlanAttributeText"
        android:id="@+id/attrib_value"
        android:gravity="right"
        android:textStyle="normal"/>
</TableRow>

[Vue warn]: Cannot find element

You can solve it in two ways.

  1. Make sure you put the CDN into the end of html page and place your own script after that. Example:
    <body>
      <div id="main">
        <div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
      </div>
    </body>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
    <script src="js/app.js"></script>

where you need to put same javascript code you wrote in any other JavaScript file or in html file.

  1. Use window.onload function in your JavaScript file.

Getting the text from a drop-down box

document.getElementById('newSkill').options[document.getElementById('newSkill').selectedIndex].value 

Should work

TypeError: 'float' object not iterable

for i in count: means for i in 7:, which won't work. The bit after the in should be of an iterable type, not a number. Try this:

for i in range(count):

How can I start and check my MySQL log?

For me, general_log didn't worked. But adding this to my.ini worked

[mysqld]
log-output=FILE
slow_query_log = 1
slow_query_log_file = "d:/temp/developer.log"

Git, How to reset origin/master to a commit?

Assuming that your branch is called master both here and remotely, and that your remote is called origin you could do:

git reset --hard <commit-hash>
git push -f origin master

However, you should avoid doing this if anyone else is working with your remote repository and has pulled your changes. In that case, it would be better to revert the commits that you don't want, then push as normal.

Disable/Enable Submit Button until all forms have been filled

Here is my way of validating a form with a disabled button. Check out the snippet below:

_x000D_
_x000D_
var inp = document.getElementsByTagName("input");_x000D_
var btn = document.getElementById("btn");_x000D_
// Disable the button dynamically using javascript_x000D_
btn.disabled = "disabled";_x000D_
_x000D_
function checkForm() {_x000D_
    for (var i = 0; i < inp.length; i++) {_x000D_
        if (inp[i].checkValidity() == false) {_x000D_
            btn.disabled = "disabled";_x000D_
        } else {_x000D_
            btn.disabled = false;_x000D_
        }_x000D_
    }_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="UTF-8"/>_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>_x000D_
    <title>JavaScript</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<h1>Javascript form validation</h1>_x000D_
<p>Javascript constraint form validation example:</p>_x000D_
_x000D_
<form onkeyup="checkForm()" autocomplete="off" novalidate>_x000D_
    <input type="text" name="fname" placeholder="First Name" required><br><br>_x000D_
    <input type="text" name="lname" placeholder="Last Name" required><br><br>_x000D_
    <button type="submit" id="btn">Submit</button>_x000D_
</form>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


Example explained:

  1. We create a variable to store all the input elements.
    var inp = document.getElementsByTagName("input");
    
  2. We create another variable to store the button element
    var btn = document.getElementById("btn");
    
  3. We loop over the collection of input elements
    for (var i = 0; i < inp.length; i++) {
        // Code
    }
    
  4. Finally, We use the checkValidity() method to check if the input elements (with a required attribute) are valid or not (Code is inserted inside the for loop). If it is invalid, then the button will remain disabled, else the attribute is removed.
    for (var i = 0; i < inp.length; i++) {
        if (inp[i].checkValidity() == false) {
            btn.disabled = "disabled";
        } else {
            btn.disabled = false;
        }
    }
    

how to reference a YAML "setting" from elsewhere in the same YAML file?

In some languages, you can use an alternative library, For example, tampax is an implementation of YAML handling variables:

const tampax = require('tampax');

const yamlString = `
dude:
  name: Arthur
weapon:
  favorite: Excalibur
  useless: knife
sentence: "{{dude.name}} use {{weapon.favorite}}. The goal is {{goal}}."`;

const r = tampax.yamlParseString(yamlString, { goal: 'to kill Mordred' });
console.log(r.sentence);

// output : "Arthur use Excalibur. The goal is to kill Mordred."

Editor's Note: poster is also the author of this package.

Why do you need ./ (dot-slash) before executable or script name to run it in bash?

When bash interprets the command line, it looks for commands in locations described in the environment variable $PATH. To see it type:

echo $PATH

You will have some paths separated by colons. As you will see the current path . is usually not in $PATH. So Bash cannot find your command if it is in the current directory. You can change it by having:

PATH=$PATH:.

This line adds the current directory in $PATH so you can do:

manage.py syncdb

It is not recommended as it has security issue, plus you can have weird behaviours, as . varies upon the directory you are in :)

Avoid:

PATH=.:$PATH

As you can “mask” some standard command and open the door to security breach :)

Just my two cents.

Android: ListView elements with multiple clickable buttons

I don't have much experience than above users but I faced this same issue and I Solved this with below Solution

<Button
        android:id="@+id/btnRemove"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/btnEdit"
        android:layout_weight="1"
        android:background="@drawable/btn"
        android:text="@string/remove" 
        android:onClick="btnRemoveClick"
        />

btnRemoveClick Click event

public void btnRemoveClick(View v)
{
    final int position = listviewItem.getPositionForView((View) v.getParent()); 
    listItem.remove(position);
    ItemAdapter.notifyDataSetChanged();

}

How to force Hibernate to return dates as java.util.Date instead of Timestamp?

Here is solution for Hibernate 4.3.7.Final.

pacakge-info.java contains

@TypeDefs(
    {
        @TypeDef(
                name = "javaUtilDateType",
                defaultForType = java.util.Date.class,
                typeClass = JavaUtilDateType.class
        )
    })
package some.pack;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;

And JavaUtilDateType:

package some.other.or.same.pack;

import java.sql.Timestamp;
import java.util.Comparator;
import java.util.Date;
import org.hibernate.HibernateException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.type.AbstractSingleColumnStandardBasicType;
import org.hibernate.type.LiteralType;
import org.hibernate.type.StringType;
import org.hibernate.type.TimestampType;
import org.hibernate.type.VersionType;
import org.hibernate.type.descriptor.WrapperOptions;
import org.hibernate.type.descriptor.java.JdbcTimestampTypeDescriptor;
import org.hibernate.type.descriptor.sql.TimestampTypeDescriptor;

/**
 * Note: Depends on hibernate implementation details hibernate-core-4.3.7.Final.
 *
 * @see
 * <a href="http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch06.html#types-custom">Hibernate
 * Documentation</a>
 * @see TimestampType
 */
public class JavaUtilDateType
        extends AbstractSingleColumnStandardBasicType<Date>
        implements VersionType<Date>, LiteralType<Date> {

    public static final TimestampType INSTANCE = new TimestampType();

    public JavaUtilDateType() {
        super(
                TimestampTypeDescriptor.INSTANCE,
                new JdbcTimestampTypeDescriptor() {

                    @Override
                    public Date fromString(String string) {
                        return new Date(super.fromString(string).getTime());
                    }

                    @Override
                    public <X> Date wrap(X value, WrapperOptions options) {
                        return new Date(super.wrap(value, options).getTime());
                    }

                }
        );
    }

    @Override
    public String getName() {
        return "timestamp";
    }

    @Override
    public String[] getRegistrationKeys() {
        return new String[]{getName(), Timestamp.class.getName(), java.util.Date.class.getName()};
    }

    @Override
    public Date next(Date current, SessionImplementor session) {
        return seed(session);
    }

    @Override
    public Date seed(SessionImplementor session) {
        return new Timestamp(System.currentTimeMillis());
    }

    @Override
    public Comparator<Date> getComparator() {
        return getJavaTypeDescriptor().getComparator();
    }

    @Override
    public String objectToSQLString(Date value, Dialect dialect) throws Exception {
        final Timestamp ts = Timestamp.class.isInstance(value)
                ? (Timestamp) value
                : new Timestamp(value.getTime());
        // TODO : use JDBC date literal escape syntax? -> {d 'date-string'} in yyyy-mm-dd hh:mm:ss[.f...] format
        return StringType.INSTANCE.objectToSQLString(ts.toString(), dialect);
    }

    @Override
    public Date fromStringValue(String xml) throws HibernateException {
        return fromString(xml);
    }
}

This solution mostly relies on TimestampType implementation with adding additional behaviour through anonymous class of type JdbcTimestampTypeDescriptor.

How to call a JavaScript function from PHP?

you can try this one also:-

    public function PHPFunction()
    {
            echo '<script type="text/javascript">
                 test();
            </script>'; 
    }
    <script type="text/javascript">
    public function test()
    {
        alert('In test Function');
    }
    </script>

How to find if directory exists in Python

There is a convenient Unipath module.

>>> from unipath import Path 
>>>  
>>> Path('/var/log').exists()
True
>>> Path('/var/log').isdir()
True

Other related things you might need:

>>> Path('/var/log/system.log').parent
Path('/var/log')
>>> Path('/var/log/system.log').ancestor(2)
Path('/var')
>>> Path('/var/log/system.log').listdir()
[Path('/var/foo'), Path('/var/bar')]
>>> (Path('/var/log') + '/system.log').isfile()
True

You can install it using pip:

$ pip3 install unipath

It's similar to the built-in pathlib. The difference is that it treats every path as a string (Path is a subclass of the str), so if some function expects a string, you can easily pass it a Path object without a need to convert it to a string.

For example, this works great with Django and settings.py:

# settings.py
BASE_DIR = Path(__file__).ancestor(2)
STATIC_ROOT = BASE_DIR + '/tmp/static'

How do I lowercase a string in Python?

How to convert string to lowercase in Python?

Is there any way to convert an entire user inputted string from uppercase, or even part uppercase to lowercase?

E.g. Kilometers --> kilometers

The canonical Pythonic way of doing this is

>>> 'Kilometers'.lower()
'kilometers'

However, if the purpose is to do case insensitive matching, you should use case-folding:

>>> 'Kilometers'.casefold()
'kilometers'

Here's why:

>>> "Maße".casefold()
'masse'
>>> "Maße".lower()
'maße'
>>> "MASSE" == "Maße"
False
>>> "MASSE".lower() == "Maße".lower()
False
>>> "MASSE".casefold() == "Maße".casefold()
True

This is a str method in Python 3, but in Python 2, you'll want to look at the PyICU or py2casefold - several answers address this here.

Unicode Python 3

Python 3 handles plain string literals as unicode:

>>> string = '????????'
>>> string
'????????'
>>> string.lower()
'????????'

Python 2, plain string literals are bytes

In Python 2, the below, pasted into a shell, encodes the literal as a string of bytes, using utf-8.

And lower doesn't map any changes that bytes would be aware of, so we get the same string.

>>> string = '????????'
>>> string
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> string.lower()
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> print string.lower()
????????

In scripts, Python will object to non-ascii (as of Python 2.5, and warning in Python 2.4) bytes being in a string with no encoding given, since the intended coding would be ambiguous. For more on that, see the Unicode how-to in the docs and PEP 263

Use Unicode literals, not str literals

So we need a unicode string to handle this conversion, accomplished easily with a unicode string literal, which disambiguates with a u prefix (and note the u prefix also works in Python 3):

>>> unicode_literal = u'????????'
>>> print(unicode_literal.lower())
????????

Note that the bytes are completely different from the str bytes - the escape character is '\u' followed by the 2-byte width, or 16 bit representation of these unicode letters:

>>> unicode_literal
u'\u041a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> unicode_literal.lower()
u'\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'

Now if we only have it in the form of a str, we need to convert it to unicode. Python's Unicode type is a universal encoding format that has many advantages relative to most other encodings. We can either use the unicode constructor or str.decode method with the codec to convert the str to unicode:

>>> unicode_from_string = unicode(string, 'utf-8') # "encoding" unicode from string
>>> print(unicode_from_string.lower())
????????
>>> string_to_unicode = string.decode('utf-8') 
>>> print(string_to_unicode.lower())
????????
>>> unicode_from_string == string_to_unicode == unicode_literal
True

Both methods convert to the unicode type - and same as the unicode_literal.

Best Practice, use Unicode

It is recommended that you always work with text in Unicode.

Software should only work with Unicode strings internally, converting to a particular encoding on output.

Can encode back when necessary

However, to get the lowercase back in type str, encode the python string to utf-8 again:

>>> print string
????????
>>> string
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> string.decode('utf-8')
u'\u041a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> string.decode('utf-8').lower()
u'\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> string.decode('utf-8').lower().encode('utf-8')
'\xd0\xba\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> print string.decode('utf-8').lower().encode('utf-8')
????????

So in Python 2, Unicode can encode into Python strings, and Python strings can decode into the Unicode type.

Console output in a Qt GUI app?

I also played with this, discovering that redirecting output worked, but I never saw output to the console window, which is present for every windows application. This is my solution so far, until I find a Qt replacement for ShowWindow and GetConsoleWindow.

Run this from a command prompt without parameters - get the window. Run from command prompt with parameters (eg. cmd aaa bbb ccc) - you get the text output on the command prompt window - just as you would expect for any Windows console app.

Please excuse the lame example - it represents about 30 minutes of tinkering.

#include "mainwindow.h"
#include <QTextStream>
#include <QCoreApplication>
#include <QApplication>
#include <QWidget>
#include <windows.h>

QT_USE_NAMESPACE

int main(int argc, char *argv[])
{
    if (argc > 1)   {
        // User has specified command-line arguments
        QCoreApplication a(argc, argv);
        QTextStream  out(stdout);
        int     i;

        ShowWindow (GetConsoleWindow(),SW_NORMAL);
        for (i=1; i<argc; i++)
             out << i << ':' << argv [i] << endl;
        out << endl << "Hello, World" << endl;
        out << "Application Directory Path:" << a.applicationDirPath() << endl;
        out << "Application File Path:" << a.applicationFilePath() << endl;
        MessageBox (0,(LPCWSTR)"Continue?",(LPCWSTR)"Silly Question",MB_YESNO);
        return 0;
    } else  {
        QApplication a(argc, argv);
        MainWindow w;

        w.setWindowTitle("Simple example");
        w.show();
        return a.exec();
    }
}

bash shell nested for loop

The question does not contain a nested loop, just a single loop. But THIS nested version works, too:

# for i in c d; do for j in a b; do echo $i $j; done; done
c a
c b
d a
d b

How do I use ROW_NUMBER()?

Need to create virtual table by using WITH table AS, which is mention in given Query.

By using this virtual table, you can perform CRUD operation w.r.t row_number.

QUERY:

WITH table AS
-
(SELECT row_number() OVER(ORDER BY UserId) rn, * FROM Users)
-
SELECT * FROM table WHERE UserName='Joe'
-

You can use INSERT, UPDATE or DELETE in last sentence by in spite of SELECT.

CentOS 7 and Puppet unable to install nc

You can use a case in this case, to separate versions one example is using FACT os (which returns the version etc of your system... the command facter will return the details:

root@sytem# facter -p os
{"name"=>"CentOS", "family"=>"RedHat", "release"=>{"major"=>"7", "minor"=>"0", "full"=>"7.0.1406"}}

#we capture release hash
$curr_os = $os['release']

case $curr_os['major'] {
  '7': { .... something }
  *: {something}
}

That is an fast example, Might have typos, or not exactly working. But using system facts you can see what happens.

The OS fact provides you 3 main variables: name, family, release... Under release you have a small dictionary with more information about your os! combining these you can create cases to meet your targets.

Echo tab characters in bash script

res="\t\tx"
echo -e "[${res}]"

How to choose the right bean scope?

Since JSF 2.3 all the bean scopes defined in package javax.faces.bean package have been deprecated to align the scopes with CDI. Moreover they're only applicable if your bean is using @ManagedBean annotation. If you are using JSF versions below 2.3 refer to the legacy answer at the end.


From JSF 2.3 here are scopes that can be used on JSF Backing Beans:

1. @javax.enterprise.context.ApplicationScoped: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. This is useful when you have data for whole application.

2. @javax.enterprise.context.SessionScoped: The session scope persists from the time that a session is established until session termination. The session context is shared between all requests that occur in the same HTTP session. This is useful when you wont to save data for a specific client for a particular session.

3. @javax.enterprise.context.ConversationScoped: The conversation scope persists as log as the bean lives. The scope provides 2 methods: Conversation.begin() and Conversation.end(). These methods should called explicitly, either to start or end the life of a bean.

4. @javax.enterprise.context.RequestScoped: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.

5. @javax.faces.flow.FlowScoped: The Flow scope persists as long as the Flow lives. A flow may be defined as a contained set of pages (or views) that define a unit of work. Flow scoped been is active as long as user navigates with in the Flow.

6. @javax.faces.view.ViewScoped: A bean in view scope persists while the same JSF page is redisplayed. As soon as the user navigates to a different page, the bean goes out of scope.


The following legacy answer applies JSF version before 2.3

As of JSF 2.x there are 4 Bean Scopes:

  • @SessionScoped
  • @RequestScoped
  • @ApplicationScoped
  • @ViewScoped

Session Scope: The session scope persists from the time that a session is established until session termination. A session terminates if the web application invokes the invalidate method on the HttpSession object, or if it times out.

RequestScope: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.

ApplicationScope: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. You place managed beans into the application scope if a single bean should be shared among all instances of a web application. The bean is constructed when it is first requested by any user of the application, and it stays alive until the web application is removed from the application server.

ViewScope: View scope was added in JSF 2.0. A bean in view scope persists while the same JSF page is redisplayed. (The JSF specification uses the term view for a JSF page.) As soon as the user navigates to a different page, the bean goes out of scope.

Choose the scope you based on your requirement.

Source: Core Java Server Faces 3rd Edition by David Geary & Cay Horstmann [Page no. 51 - 54] enter image description here

Linux cmd to search for a class file among jars irrespective of jar path

Use deepgrep and deepfind. On debian-based systems you can install them by:

sudo apt-get install strigi-utils

Both commands search for nested archives as well. In your case the command would look like:

find . -name "*.jar" | xargs -I {} deepfind {} | grep Hello.class

What is a JavaBean exactly?

In practice, Beans are just objects which are handy to use. Serializing them means to be able easily to persist them (store in a form that is easily recovered).

Typical uses of Beans in real world:

  • simple reusable objects POJO (Plain Old Java Objects)
  • visual objects
  • Spring uses Beans for objects to handle (for instance, User object that needs to be serialized in session)
  • EJB (Enterprise Java Beans), more complex objects, like JSF Beans (JSF is old quite outdated technology) or JSP Beans

So in fact, Beans are just a convention / standard to expect something from a Java object that it would behave (serialization) and give some ways to change it (setters for properties) in a certain way.

How to use them, is just your invention, but most common cases I enlisted above.

How to update RecyclerView Adapter Data?

The best and the coolest way to add new data to the present data is

 ArrayList<String> newItems = new ArrayList<String>();
 newItems = getList();
 int oldListItemscount = alcontainerDetails.size();
 alcontainerDetails.addAll(newItems);           
 recyclerview.getAdapter().notifyItemChanged(oldListItemscount+1, al_containerDetails);

How to set default vim colorscheme

Ubuntu 17.10 default doesn't have the ~/.vimrc file, we need create it and put the setting colorscheme color_scheme_name in it.

By the way, colorscheme desert is good scheme to choose.

php date validation

Nicolas solution is best. If you want in regex,

try this,

this will validate for, 01/01/1900 through 12/31/2099 Matches invalid dates such as February 31st Accepts dashes, spaces, forward slashes and dots as date separators

(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9]{2}

How to get data from database in javascript based on the value passed to the function

'SELECT * FROM Employ where number = ' + parseInt(val, 10) + ';'

For example, if val is "10" then this will end up building the string:

"SELECT * FROM Employ where number = 10;"

Commenting out a set of lines in a shell script

The most versatile and safe method is putting the comment into a void quoted here-document, like this:

<<"COMMENT"
    This long comment text includes ${parameter:=expansion}
    `command substitution` and $((arithmetic++ + --expansion)).
COMMENT

Quoting the COMMENT delimiter above is necessary to prevent parameter expansion, command substitution and arithmetic expansion, which would happen otherwise, as Bash manual states and POSIX shell standard specifies.

In the case above, not quoting COMMENT would result in variable parameter being assigned text expansion, if it was empty or unset, executing command command substitution, incrementing variable arithmetic and decrementing variable expansion.

Comparing other solutions to this:

Using if false; then comment text fi requires the comment text to be syntactically correct Bash code whereas natural comments are often not, if only for possible unbalanced apostrophes. The same goes for : || { comment text } construct.

Putting comments into a single-quoted void command argument, as in :'comment text', has the drawback of inability to include apostrophes. Double-quoted arguments, as in :"comment text", are still subject to parameter expansion, command substitution and arithmetic expansion, the same as unquoted here-document contents and can lead to the side-effects described above.

Using scripts and editor facilities to automatically prefix each line in a block with '#' has some merit, but doesn't exactly answer the question.

What are the valid Style Format Strings for a Reporting Services [SSRS] Expression?

As mentioned, you can use:

=Format(Fields!Price.Value, "C")

A digit after the "C" will specify precision:

=Format(Fields!Price.Value, "C0")
=Format(Fields!Price.Value, "C1")

You can also use Excel-style masks like this:

=Format(Fields!Price.Value, "#,##0.00")

Haven't tested the last one, but there's the idea. Also works with dates:

=Format(Fields!Date.Value, "yyyy-MM-dd")

Increment a database field by 1

If you can safely make (firstName, lastName) the PRIMARY KEY or at least put a UNIQUE key on them, then you could do this:

INSERT INTO logins (firstName, lastName, logins) VALUES ('Steve', 'Smith', 1)
ON DUPLICATE KEY UPDATE logins = logins + 1;

If you can't do that, then you'd have to fetch whatever that primary key is first, so I don't think you could achieve what you want in one query.

Docker expose all ports or range of ports from 7000 to 8000

For anyone facing this issue and ending up on this post...the issue is still open - https://github.com/moby/moby/issues/11185

Max or Default?

Sounds like a case for DefaultIfEmpty (untested code follows):

Dim x = (From y In context.MyTable _
         Where y.MyField = value _
         Select y.MyCounter).DefaultIfEmpty.Max

How do I update the element at a certain position in an ArrayList?

Let arrList be the ArrayList and newValue the new String, then just do:

arrList.set(5, newValue);

This can be found in the java api reference here.

Android Studio : Failure [INSTALL_FAILED_OLDER_SDK]

Change file AndroidManifest.xml

<uses-sdk android:minSdkVersion="19"/>
<uses-sdk android:minSdkVersion="14"/>

go get results in 'terminal prompts disabled' error for github private repo

I found this extremely helpful, and it solved my problem. This command will allow your 2FA to do its thing (and save you the trouble of entering your username and password):

git config --global --add url."[email protected]:".insteadOf "https://github.com/"

Source: http://albertech.blogspot.com/2016/11/fix-git-error-could-not-read-username.html

If you're not using 2FA, you can still use SSH and this will work.

Edit: added the --add flag as suggested by slatunje.

Should I put #! (shebang) in Python scripts, and what form should it take?

Use first

which python

This will give the output as the location where my python interpreter (binary) is present.

This output could be any such as

/usr/bin/python

or

/bin/python

Now appropriately select the shebang line and use it.

To generalize we can use:

#!/usr/bin/env

or

#!/bin/env

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

Visual Studio 2015/2017's live debugger is injecting code that contains the deprecated call.

React Modifying Textarea Values

As a newbie in React world, I came across a similar issues where I could not edit the textarea and struggled with binding. It's worth knowing about controlled and uncontrolled elements when it comes to react.

The value of the following uncontrolled textarea cannot be changed because of value

 <textarea type="text" value="some value"
    onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following uncontrolled textarea can be changed because of use of defaultValue or no value attribute

<textarea type="text" defaultValue="sample" 
    onChange={(event) => this.handleOnChange(event)}></textarea>

<textarea type="text" 
   onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following controlled textarea can be changed because of how value is mapped to a state as well as the onChange event listener

<textarea value={this.state.textareaValue} 
onChange={(event) => this.handleOnChange(event)}></textarea>

Here is my solution using different syntax. I prefer the auto-bind than manual binding however, if I were to not use {(event) => this.onXXXX(event)} then that would cause the content of textarea to be not editable OR the event.preventDefault() does not work as expected. Still a lot to learn I suppose.

class Editor extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      textareaValue: ''
    }
  }
  handleOnChange(event) {
    this.setState({
      textareaValue: event.target.value
    })
  }
  handleOnSubmit(event) {
    event.preventDefault();
    this.setState({
      textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
    })
  }
  render() {
    return <div>
        <form onSubmit={(event) => this.handleOnSubmit(event)}>
          <textarea rows={10} cols={30} value={this.state.textareaValue} 
            onChange={(event) => this.handleOnChange(event)}></textarea>
          <br/>
          <input type="submit" value="Save"/>
        </form>
      </div>
  }
}
ReactDOM.render(<Editor />, document.getElementById("content"));

The versions of libraries are

"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4" 

Using CSS how to change only the 2nd column of a table

on this web http://quirksmode.org/css/css2/columns.html i found that easy way

<table>
<col style="background-color: #6374AB; color: #ffffff" />
<col span="2" style="background-color: #07B133; color: #ffffff;" />
<tr>..

What does /p mean in set /p?

For future reference, you can get help for any command by using the /? switch, which should explain what switches do what.

According to the set /? screen, the format for set /p is SET /P variable=[promptString] which would indicate that the p in /p is "prompt." It just prints in your example because <nul passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.

/L in for /L generates a List of numbers.

From ping /?:

Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
            [-r count] [-s count] [[-j host-list] | [-k host-list]]
            [-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name

Options:
    -t             Ping the specified host until stopped.
                   To see statistics and continue - type Control-Break;
                   To stop - type Control-C.
    -a             Resolve addresses to hostnames.
    -n count       Number of echo requests to send.
    -l size        Send buffer size.
    -f             Set Don't Fragment flag in packet (IPv4-only).
    -i TTL         Time To Live.
    -v TOS         Type Of Service (IPv4-only. This setting has been deprecated
                   and has no effect on the type of service field in the IP Header).
    -r count       Record route for count hops (IPv4-only).
    -s count       Timestamp for count hops (IPv4-only).
    -j host-list   Loose source route along host-list (IPv4-only).
    -k host-list   Strict source route along host-list (IPv4-only).
    -w timeout     Timeout in milliseconds to wait for each reply.
    -R             Use routing header to test reverse route also (IPv6-only).
    -S srcaddr     Source address to use.
    -4             Force using IPv4.
    -6             Force using IPv6.

placeholder for select tag

Try this

HTML

<select class="form-control"name="country">
<option class="servce_pro_disabled">Select Country</option>
<option class="servce_pro_disabled" value="Aruba" id="cl_country_option">Aruba</option>
</select>

CSS

.form-control option:first-child {
    display: none;
}

Size of character ('a') in C/C++

As Paul stated, it's because 'a' is an int in C but a char in C++.

I cover that specific difference between C and C++ in something I wrote a few years ago, at: http://david.tribble.com/text/cdiffs.htm

Recommended way to get hostname in Java

If you're not against using an external dependency from maven central, I wrote gethostname4j to solve this problem for myself. It just uses JNA to call libc's gethostname function (or gets the ComputerName on Windows) and returns it to you as a string.

https://github.com/mattsheppard/gethostname4j

How to add not null constraint to existing column in MySQL

Try this, you will know the difference between change and modify,

ALTER TABLE table_name CHANGE curr_column_name new_column_name new_column_datatype [constraints]

ALTER TABLE table_name MODIFY column_name new_column_datatype [constraints]
  • You can change name and datatype of the particular column using CHANGE.
  • You can modify the particular column datatype using MODIFY. You cannot change the name of the column using this statement.

Hope, I explained well in detail.

Sort array of objects by single key with date value

I face with same thing, so i handle this with a generic why and i build a function for this:

//example:
//array: [{name: 'idan', workerType: '3'}, {name: 'stas', workerType: '5'}, {name: 'kirill', workerType: '2'}]
//keyField: 'workerType'
// keysArray: ['4', '3', '2', '5', '6']
sortByArrayOfKeys = (array, keyField, keysArray) => {
    array.sort((a, b) => {
        const aIndex = keysArray.indexOf(a[keyField])
        const bIndex = keysArray.indexOf(b[keyField])
        if (aIndex < bIndex) return -1;
        if (aIndex > bIndex) return 1;
        return 0;
    })
}

How do you fade in/out a background color using jquery?

javascript fade to white without jQuery or other library:

<div id="x" style="background-color:rgb(255,255,105)">hello world</div>
<script type="text/javascript">
var gEvent=setInterval("toWhite();", 100);
function toWhite(){
    var obj=document.getElementById("x");
    var unBlue=10+parseInt(obj.style.backgroundColor.split(",")[2].replace(/\D/g,""));
    if(unBlue>245) unBlue=255;
    if(unBlue<256) obj.style.backgroundColor="rgb(255,255,"+unBlue+")";
    else clearInterval(gEvent)
}
</script>

In printing, yellow is minus blue, so starting with the 3rd rgb element (blue) at less than 255 starts out with a yellow highlight. Then the 10+ in setting the var unBlue value increments the minus blue until it reaches 255.

How to make an android app to always run in background?

On some mobiles like mine (MIUI Redmi 3) you can just add specific Application on list where application doesnt stop when you terminate applactions in Task Manager (It will stop but it will start again)

Just go to Settings>PermissionsAutostart

How do you remove an array element in a foreach loop?

If you also get the key, you can delete that item like this:

foreach ($display_related_tags as $key => $tag_name) {
    if($tag_name == $found_tag['name']) {
        unset($display_related_tags[$key]);
    }
}

How to make all controls resize accordingly proportionally when window is maximized?

In WPF there are certain 'container' controls that automatically resize their contents and there are some that don't.

Here are some that do not resize their contents (I'm guessing that you are using one or more of these):

StackPanel
WrapPanel
Canvas
TabControl

Here are some that do resize their contents:

Grid
UniformGrid
DockPanel

Therefore, it is almost always preferable to use a Grid instead of a StackPanel unless you do not want automatic resizing to occur. Please note that it is still possible for a Grid to not size its inner controls... it all depends on your Grid.RowDefinition and Grid.ColumnDefinition settings:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="100" /> <!--<<< Exact Height... won't resize -->
        <RowDefinition Height="Auto" /> <!--<<< Will resize to the size of contents -->
        <RowDefinition Height="*" /> <!--<<< Will resize taking all remaining space -->
    </Grid.RowDefinitions>
</Grid>

You can find out more about the Grid control from the Grid Class page on MSDN. You can also find out more about these container controls from the WPF Container Controls Overview page on MSDN.

Further resizing can be achieved using the FrameworkElement.HorizontalAlignment and FrameworkElement.VerticalAlignment properties. The default value of these properties is Stretch which will stretch elements to fit the size of their containing controls. However, when they are set to any other value, the elements will not stretch.

UPDATE >>>

In response to the questions in your comment:

Use the Grid.RowDefinition and Grid.ColumnDefinition settings to organise a basic structure first... it is common to add Grid controls into the cells of outer Grid controls if need be. You can also use the Grid.ColumnSpan and Grid.RowSpan properties to enable controls to span multiple columns and/or rows of a Grid.

It is most common to have at least one row/column with a Height/Width of "*" which will fill all remaining space, but you can have two or more with this setting, in which case the remaining space will be split between the two (or more) rows/columns. 'Auto' is a good setting to use for the rows/columns that are not set to '"*"', but it really depends on how you want the layout to be.

There is no Auto setting that you can use on the controls in the cells, but this is just as well, because we want the Grid to size the controls for us... therefore, we don't want to set the Height or Width of these controls at all.

The point that I made about the FrameworkElement.HorizontalAlignment and FrameworkElement.VerticalAlignment properties was just to let you know of their existence... as their default value is already Stretch, you don't generally need to set them explicitly.

The Margin property is generally just used to space your controls out evenly... if you drag and drop controls from the Visual Studio Toolbox, VS will set the Margin property to place your control exactly where you dropped it but generally, this is not what we want as it will mess with the auto sizing of controls. If you do this, then just delete or edit the Margin property to suit your needs.

PHP: get the value of TEXTBOX then pass it to a VARIABLE

I think you should need to check for isset and not empty value, like form was submitted without input data so isset will be true This will prevent you to have any error or notice.

if((isset($_POST['name'])) && !empty($_POST['name']))
{
    $name = $_POST['name']; //note i used $_POST since you have a post form **method='post'**
    echo $name;
}

Entity Framework: table without primary key

From a practical standpoint, every table--even a denormalized table like a warehouse table--should have a primary key. Or, failing that, it should at least have a unique, non-nullable index.

Without some kind of unique key, duplicate records can (and will) appear in the table, which is very problematic both for ORM layers and also for basic comprehension of the data. A table that has duplicate records is probably a symptom of bad design.

At the very least, the table should at least have an identity column. Adding an auto-generating ID column takes about 2 minutes in SQL Server and 5 minutes in Oracle. For that extra bit of effort, many, many problems will be avoided.

MySQL SELECT AS combine two columns into one

You don't need to list ContactPhoneAreaCode1 and ContactPhoneNumber1

SELECT FirstName AS First_Name, 
LastName AS Last_Name, 
COALESCE(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
FROM TABLE1

Make 2 functions run at the same time

Try this

from threading import Thread

def fun1():
    print("Working1")
def fun2():
    print("Working2")

t1 = Thread(target=fun1)
t2 = Thread(target=fun2)

t1.start()
t2.start()

List distinct values in a vector in R

You can also use the sqldf package in R.

Z <- sqldf('SELECT DISTINCT tablename.columnname FROM tablename ')

How to display div after click the button in Javascript?

HTML

<div id="myDiv" style="display:none;" class="answer_list" >WELCOME</div>
<input type="button" name="answer" onclick="ShowDiv()" />

JavaScript

function ShowDiv() {
    document.getElementById("myDiv").style.display = "";
}

Or if you wanted to use jQuery with a nice little animation:

<input id="myButton" type="button" name="answer" />

$('#myButton').click(function() {
  $('#myDiv').toggle('slow', function() {
    // Animation complete.
  });
});

throwing an exception in objective-c/cocoa

@throw([NSException exceptionWith…])

Xcode recognizes @throw statements as function exit points, like return statements. Using the @throw syntax avoids erroneous "Control may reach end of non-void function" warnings that you may get from [NSException raise:…].

Also, @throw can be used to throw objects that are not of class NSException.

How do I get a value of datetime.today() in Python that is "timezone aware"?

In Python 3.2+: datetime.timezone.utc:

The standard library makes it much easier to specify UTC as the time zone:

>>> import datetime
>>> datetime.datetime.now(datetime.timezone.utc)
datetime.datetime(2020, 11, 27, 14, 34, 34, 74823, tzinfo=datetime.timezone.utc)

You can also get a datetime that includes the local time offset using astimezone:

>>> datetime.datetime.now(datetime.timezone.utc).astimezone()
datetime.datetime(2020, 11, 27, 15, 34, 34, 74823, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600), 'CET'))

(In Python 3.6+, you can shorten the last line to: datetime.datetime.now().astimezone())

If you want a solution that uses only the standard library and that works in both Python 2 and Python 3, see jfs' answer.

In Python 3.9+: zoneinfo to use the IANA time zone database:

In Python 3.9, you can specify particular time zones using the standard library, using zoneinfo, like this:

>>> from zoneinfo import ZoneInfo
>>> datetime.datetime.now(ZoneInfo("America/Los_Angeles"))
datetime.datetime(2020, 11, 27, 6, 34, 34, 74823, tzinfo=zoneinfo.ZoneInfo(key='America/Los_Angeles'))

zoneinfo gets its database of time zones from the operating system, or from the first-party PyPI package tzdata if available.

Installing a local module using npm?

Neither of these approaches (npm link or package.json file dependency) work if the local module has peer dependencies that you only want to install in your project's scope.

For example:

/local/mymodule/package.json:
  "name": "mymodule",
  "peerDependencies":
  {
    "foo": "^2.5"
  }

/dev/myproject/package.json:
  "dependencies":
  {
    "mymodule": "file:/local/mymodule",
    "foo": "^2.5"
  }

In this scenario, npm sets up myproject's node_modules/ like this:

/dev/myproject/node_modules/
  foo/
  mymodule -> /local/mymodule

When node loads mymodule and it does require('foo'), node resolves the mymodule symlink, and then only looks in /local/mymodule/node_modules/ (and its ancestors) for foo, which it doen't find. Instead, we want node to look in /local/myproject/node_modules/, since that's where were running our project from, and where foo is installed.

So, we either need a way to tell node to not resolve this symlink when looking for foo, or we need a way to tell npm to install a copy of mymodule when the file dependency syntax is used in package.json. I haven't found a way to do either, unfortunately :(

Download image from the site in .NET/C#

I have used Fredrik's code above in a project with some slight modifications, thought I'd share:

private static bool DownloadRemoteImageFile(string uri, string fileName)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    HttpWebResponse response;
    try
    {
        response = (HttpWebResponse)request.GetResponse();
    }
    catch (Exception)
    {
        return false;
    }

    // Check that the remote file was found. The ContentType
    // check is performed since a request for a non-existent
    // image file might be redirected to a 404-page, which would
    // yield the StatusCode "OK", even though the image was not
    // found.
    if ((response.StatusCode == HttpStatusCode.OK ||
        response.StatusCode == HttpStatusCode.Moved ||
        response.StatusCode == HttpStatusCode.Redirect) &&
        response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
    {

        // if the remote file was found, download it
        using (Stream inputStream = response.GetResponseStream())
        using (Stream outputStream = File.OpenWrite(fileName))
        {
            byte[] buffer = new byte[4096];
            int bytesRead;
            do
            {
                bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                outputStream.Write(buffer, 0, bytesRead);
            } while (bytesRead != 0);
        }
        return true;
    }
    else
        return false;
}

Main changes are:

  • using a try/catch for the GetResponse() as I was running into an exception when the remote file returned 404
  • returning a boolean

Make WPF Application Fullscreen (Cover startmenu)

<Window x:Class="HTA.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    mc:Ignorable="d" 
    ResizeMode="NoResize"
    WindowStartupLocation="CenterScreen" 
    Width="1024" Height="768"
    WindowState="Maximized" WindowStyle="None">

Window state to Maximized and window style to None

How to make a deep copy of Java ArrayList

Cloning the objects before adding them. For example, instead of newList.addAll(oldList);

for(Person p : oldList) {
    newList.add(p.clone());
}

Assuming clone is correctly overriden inPerson.

How to update column with null value

On insert we can use

$arrEntity=$entity->toArray();        
    foreach ($arrEntity as $key => $value) {    
        if (trim($entity->$key) == '' && !is_null($entity->$key) && !is_bool($entity->$key)){
        unset($entity->$key);
        }
    }

On update we can use

$fields=array();
foreach ($fields as $key => $value) {
        if (trim($value) == '' && !is_null($value) && !is_bool($value)){
            $fields[$key] = null;
        }
    }

Get PostGIS version

As the above people stated, select PostGIS_full_version(); will answer your question. On my machine, where I'm running PostGIS 2.0 from trunk, I get the following output:

postgres=# select PostGIS_full_version();
postgis_full_version                                                                  
-------------------------------------------------------------------------------------------------------------------------------------------------------
POSTGIS="2.0.0alpha4SVN" GEOS="3.3.2-CAPI-1.7.2" PROJ="Rel. 4.7.1, 23 September 2009" GDAL="GDAL 1.8.1, released 2011/07/09" LIBXML="2.7.3" USE_STATS
(1 row)

You do need to care about the versions of PROJ and GEOS that are included if you didn't install an all-inclusive package - in particular, there's some brokenness in GEOS prior to 3.3.2 (as noted in the postgis 2.0 manual) in dealing with geometry validity.

How to get SQL from Hibernate Criteria API (*not* for logging)

This answer is based on user3715338's answer (with a small spelling error corrected) and mixed with Michael's answer for Hibernate 3.6 - based on the accepted answer from Brian Deterling. I then extended it (for PostgreSQL) with a couple more types replacing the questionmarks:

public static String toSql(Criteria criteria)
{
    String sql = "";
    Object[] parameters = null;
    try
    {
        CriteriaImpl criteriaImpl = (CriteriaImpl) criteria;
        SessionImpl sessionImpl = (SessionImpl) criteriaImpl.getSession();
        SessionFactoryImplementor factory = sessionImpl.getSessionFactory();
        String[] implementors = factory.getImplementors(criteriaImpl.getEntityOrClassName());
        OuterJoinLoadable persister = (OuterJoinLoadable) factory.getEntityPersister(implementors[0]);
        LoadQueryInfluencers loadQueryInfluencers = new LoadQueryInfluencers();
        CriteriaLoader loader = new CriteriaLoader(persister, factory,
            criteriaImpl, implementors[0].toString(), loadQueryInfluencers);
        Field f = OuterJoinLoader.class.getDeclaredField("sql");
        f.setAccessible(true);
        sql = (String) f.get(loader);
        Field fp = CriteriaLoader.class.getDeclaredField("translator");
        fp.setAccessible(true);
        CriteriaQueryTranslator translator = (CriteriaQueryTranslator) fp.get(loader);
        parameters = translator.getQueryParameters().getPositionalParameterValues();
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
    if (sql != null)
    {
        int fromPosition = sql.indexOf(" from ");
        sql = "\nSELECT * " + sql.substring(fromPosition);

        if (parameters != null && parameters.length > 0)
        {
            for (Object val : parameters)
            {
                String value = "%";
                if (val instanceof Boolean)
                {
                    value = ((Boolean) val) ? "1" : "0";
                }
                else if (val instanceof String)
                {
                    value = "'" + val + "'";
                }
                else if (val instanceof Number)
                {
                    value = val.toString();
                }
                else if (val instanceof Class)
                {
                    value = "'" + ((Class) val).getCanonicalName() + "'";
                }
                else if (val instanceof Date)
                {
                    SimpleDateFormat sdf = new SimpleDateFormat(
                        "yyyy-MM-dd HH:mm:ss.SSS");
                    value = "'" + sdf.format((Date) val) + "'";
                }
                else if (val instanceof Enum)
                {
                    value = "" + ((Enum) val).ordinal();
                }
                else
                {
                    value = val.toString();
                }
                sql = sql.replaceFirst("\\?", value);
            }
        }
    }
    return sql.replaceAll("left outer join", "\nleft outer join").replaceAll(
        " and ", "\nand ").replaceAll(" on ", "\non ").replaceAll("<>",
        "!=").replaceAll("<", " < ").replaceAll(">", " > ");
}

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified

Go to resources folder where the application.properties is present, update the below code in that.

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

JavaScript and getElementById for multiple elements with the same ID

The HTML spec required the ID attribute to be unique in a page:

This attribute assigns a name to an element. This name must be unique in a document.

If you have several elements with the same ID, your HTML is not valid.

So, getElementById() should only ever return one element. You can't make it return multiple elements.

There are a couple of related functions that will return an array of elements - getElementsByName, or getElementsByClassName that may be more suited to your requirements, though getElementsByClassName is new to HTML 5, which is still in draft.

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

You need to add a new service for DBcontext in the startup

Default

services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

Add this

services.AddDbContext<NewDBContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("NewConnection")));

Explain why constructor inject is better than other options

To make it simple, let us say that we can use constructor based dependency injection for mandatory dependencies and setter based injection for optional dependencies. It is a rule of thumb!!

Let's say for example.

If you want to instantiate a class you always do it with its constructor. So if you are using constructor based injection, the only way to instantiate the class is through that constructor. If you pass the dependency through constructor it becomes evident that it is a mandatory dependency.

On the other hand, if you have a setter method in a POJO class, you may or may not set value for your class variable using that setter method. It is completely based on your need. i.e. it is optional. So if you pass the dependency through setter method of a class it implicitly means that it is an optional dependency. Hope this is clear!!

Why is Maven downloading the maven-metadata.xml every time?

I haven't studied yet, when Maven does which look-up, but to get stable and reproducible builds, I strongly recommend not to access Maven Respositories directly but to use a Maven Repository Manager such as Nexus.

Here is the tutorial how to set up your settings file:

http://books.sonatype.com/nexus-book/reference/maven-sect-single-group.html

http://maven.apache.org/repository-management.html

Git add and commit in one command

I use this git alias:

git config --global alias.cam '!git commit -a -m '

So, instead of call

git add -A && git commit -m "this is a great commit"

I just do:

git cam "this is a great commit"

How do I use Assert to verify that an exception has been thrown?

For "Visual Studio Team Test" it appears you apply the ExpectedException attribute to the test's method.

Sample from the documentation here: A Unit Testing Walkthrough with Visual Studio Team Test

[TestMethod]
[ExpectedException(typeof(ArgumentException),
    "A userId of null was inappropriately allowed.")]
public void NullUserIdInConstructor()
{
   LogonInfo logonInfo = new LogonInfo(null, "P@ss0word");
}

How to link a folder with an existing Heroku app

for existing repository

type in terminal

$ heroku git:remote -a example

enter image description here

Connection pooling options with JDBC: DBCP vs C3P0

Another alternative, Proxool, is mentioned in this article.

You might be able to find out why Hibernate bundles c3p0 for its default connection pool implementation?

How do I pass parameters to a jar file at the time of execution?

To pass arguments to the jar:

java -jar myjar.jar one two

You can access them in the main() method of "Main-Class" (mentioned in the manifest.mf file of a JAR).

String one = args[0];  
String two = args[1];  

Passing ArrayList from servlet to JSP

public class myActorServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private String name;
    private String user;
    private String pass;
    private String given_table;
    private String tid;
    private String firstname;
    private String lastname;
    private String action;

    @Override
    public void doPost(HttpServletRequest request,
            HttpServletResponse response)
            throws IOException, ServletException {

        response.setContentType("text/html");

        // connecting to database
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;

        PrintWriter out = response.getWriter();
        name = request.getParameter("screenName");
        user = request.getParameter("username");
        pass = request.getParameter("password");
        tid = request.getParameter("tid");
        firstname = request.getParameter("firstname");
        lastname = request.getParameter("lastname");
        action = request.getParameter("action");
        given_table = request.getParameter("tableName");

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet JDBC</title>");
        out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Hello, " + name + " </h1>");
        out.println("<h1>Servlet JDBC</h1>");

        /////////////////////////
        // init connection object
        String sqlSelect = "SELECT * FROM `" + given_table + "`";
        String sqlInsert = "INSERT INTO `" + given_table + "`(`firstName`, `lastName`) VALUES ('" + firstname + "', '" + lastname + "')";
        String sqlUpdate = "UPDATE `" + given_table + "` SET `firstName`='" + firstname + "',`lastName`='" + lastname + "' WHERE `id`=" + tid + "";
        String sqlDelete = "DELETE FROM `" + given_table + "` WHERE `id` = '" + tid + "'";

        //////////////////////////////////////////////////////////
        out.println(
                "<p>Reading Table Data...Pass to JSP File...Okay<p>");

        ArrayList<Actor> list = new ArrayList<Actor>();
        // connecting to database
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/javabase", user, pass);
            stmt = con.createStatement();
            rs = stmt.executeQuery(sqlSelect);
            // displaying records

            while (rs.next()) {
                Actor actor = new Actor();
                actor.setId(rs.getInt("id"));
                actor.setLastname(rs.getString("lastname"));
                actor.setFirstname(rs.getString("firstname"));
                list.add(actor);
            }
            request.setAttribute("actors", list);
            RequestDispatcher view = request.getRequestDispatcher("myActors_1.jsp");
            view.forward(request, response);

        } catch (SQLException e) {
            throw new ServletException("Servlet Could not display records.", e);
        } catch (ClassNotFoundException e) {
            throw new ServletException("JDBC Driver not found.", e);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                    rs = null;
                }
                if (stmt != null) {
                    stmt.close();
                    stmt = null;
                }
                if (con != null) {
                    con.close();
                    con = null;
                }
            } catch (SQLException e) {
            }
        }
        out.println("</body></html>");

        out.close();
    }

}

Oracle Add 1 hour in SQL

To add/subtract from a DATE, you have 2 options :

Method #1 : The easiest way is to use + and - to add/subtract days, hours, minutes, seconds, etc.. from a DATE, and ADD_MONTHS() function to add/subtract months and years from a DATE. Why ? That's because from days, you can get hours and any smaller unit (1 hour = 1/24 days), (1 minute = 1/1440 days), etc... But you cannot get months and years, as that depends on the month and year themselves, hence ADD_MONTHS() and no add_years(), because from months, you can get years (1 year = 12 months).

Let's try them :

SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS')             FROM dual;        -- prints current date:    19-OCT-2019 20:42:02 
SELECT TO_CHAR((SYSDATE + 1/24), 'DD-MON-YYYY HH24:MI:SS')    FROM dual;        -- prints date + 1 hour:   19-OCT-2019 21:42:02
SELECT TO_CHAR((SYSDATE + 1/1440), 'DD-MON-YYYY HH24:MI:SS')  FROM dual;        -- prints date + 1 minute: 19-OCT-2019 20:43:02 
SELECT TO_CHAR((SYSDATE + 1/86400), 'DD-MON-YYYY HH24:MI:SS') FROM dual;        -- prints date + 1 second: 19-OCT-2019 20:42:03 
-- Same goes for subtraction.

SELECT SYSDATE                  FROM dual;       -- prints current date:     19-OCT-19
SELECT ADD_MONTHS(SYSDATE, 1)   FROM dual;       -- prints date + 1 month:   19-NOV-19
SELECT ADD_MONTHS(SYSDATE, 12)  FROM dual;       -- prints date + 1 year:    19-OCT-20
SELECT ADD_MONTHS(SYSDATE, -3)  FROM dual;       -- prints date - 3 months:  19-JUL-19

Method #2 : Using INTERVALs, you can or subtract an interval (duration) from a date easily. More than that, you can combine to add or subtract multiple units at once (e.g 5 hours and 6 minutes, etc..) Examples :

SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS')                                        FROM dual;        -- prints current date:                 19-OCT-2019 21:34:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' HOUR), 'DD-MON-YYYY HH24:MI:SS')                  FROM dual;        -- prints date + 1 hour:                19-OCT-2019 22:34:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' MINUTE), 'DD-MON-YYYY HH24:MI:SS')                FROM dual;        -- prints date + 1 minute:              19-OCT-2019 21:35:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' SECOND), 'DD-MON-YYYY HH24:MI:SS')                FROM dual;        -- prints date + 1 second:              19-OCT-2019 21:34:16
SELECT TO_CHAR((SYSDATE + INTERVAL '01:05:00' HOUR TO SECOND), 'DD-MON-YYYY HH24:MI:SS') FROM dual;        -- prints date + 1 hour and 5 minutes:  19-OCT-2019 22:39:15
SELECT TO_CHAR((SYSDATE + INTERVAL '3 01' DAY TO HOUR), 'DD-MON-YYYY HH24:MI:SS')        FROM dual;        -- prints date + 3 days and 1 hour:     22-OCT-2019 22:34:15
SELECT TO_CHAR((SYSDATE - INTERVAL '10-3' YEAR TO MONTH), 'DD-MON-YYYY HH24:MI:SS')      FROM dual;        -- prints date - 10 years and 3 months: 19-JUL-2009 21:34:15

Using only CSS, show div on hover over <a>

You can do something like this:

_x000D_
_x000D_
div {_x000D_
    display: none;_x000D_
}_x000D_
    _x000D_
a:hover + div {_x000D_
    display: block;_x000D_
}
_x000D_
<a>Hover over me!</a>_x000D_
<div>Stuff shown on hover</div>
_x000D_
_x000D_
_x000D_

This uses the adjacent sibling selector, and is the basis of the suckerfish dropdown menu.

HTML5 allows anchor elements to wrap almost anything, so in that case the div element can be made a child of the anchor. Otherwise the principle is the same - use the :hover pseudo-class to change the display property of another element.

Why does Boolean.ToString output "True" and not "true"

How is it not compatible with C#? Boolean.Parse and Boolean.TryParse is case insensitive and the parsing is done by comparing the value to Boolean.TrueString or Boolean.FalseString which are "True" and "False".

EDIT: When looking at the Boolean.ToString method in reflector it turns out that the strings are hard coded so the ToString method is as follows:

public override string ToString()
{
    if (!this)
    {
        return "False";
    }
    return "True";
}

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

Basically the error was because I was using old version of aws-sdk and I updated the version so this error occured.

in my case with node js i was using signatureVersion in parmas object like this :

const AWS_S3 = new AWS.S3({
  params: {
    Bucket: process.env.AWS_S3_BUCKET,
    signatureVersion: 'v4',
    region: process.env.AWS_S3_REGION
  }
});

Then I put signature out of params object and worked like charm :

const AWS_S3 = new AWS.S3({
  params: {
    Bucket: process.env.AWS_S3_BUCKET,
    region: process.env.AWS_S3_REGION
  },
  signatureVersion: 'v4'
});

How to select following sibling/xml tag using xpath

How would I accomplish the nextsibling and is there an easier way of doing this?

You may use:

tr/td[@class='name']/following-sibling::td

but I'd rather use directly:

tr[td[@class='name'] ='Brand']/td[@class='desc']

This assumes that:

  1. The context node, against which the XPath expression is evaluated is the parent of all tr elements -- not shown in your question.

  2. Each tr element has only one td with class attribute valued 'name' and only one td with class attribute valued 'desc'.

Save results to csv file with Python

You can save it as follow if you have Pandas Dataframe

   df.to_csv(r'/dir/filename.csv')

"unmappable character for encoding" warning in Java

Use the "\uxxxx" escape format.

According to Wikipedia, the copyright symbol is unicode U+00A9 so your line should read:

String copyright = "\u00a9 2003-2008 My Company. All rights reserved.";

Javascript: How to pass a function with string parameters as a parameter to another function

Try this:

onclick="myfunction(
    '/myController/myAction',
    function(){myfuncionOnOK('/myController2/myAction2','myParameter2');},
    function(){myfuncionOnCancel('/myController3/myAction3','myParameter3');}
);"

Then you just need to call these two functions passed to myfunction:

function myfunction(url, f1, f2) {
    // …
    f1();
    f2();
}

WARNING in budgets, maximum exceeded for initial

What is Angular CLI Budgets? Budgets is one of the less known features of the Angular CLI. It’s a rather small but a very neat feature!

As applications grow in functionality, they also grow in size. Budgets is a feature in the Angular CLI which allows you to set budget thresholds in your configuration to ensure parts of your application stay within boundaries which you setOfficial Documentation

Or in other words, we can describe our Angular application as a set of compiled JavaScript files called bundles which are produced by the build process. Angular budgets allows us to configure expected sizes of these bundles. More so, we can configure thresholds for conditions when we want to receive a warning or even fail build with an error if the bundle size gets too out of control!

How To Define A Budget? Angular budgets are defined in the angular.json file. Budgets are defined per project which makes sense because every app in a workspace has different needs.

Thinking pragmatically, it only makes sense to define budgets for the production builds. Prod build creates bundles with “true size” after applying all optimizations like tree-shaking and code minimization.

Oops, a build error! The maximum bundle size was exceeded. This is a great signal that tells us that something went wrong…

  1. We might have experimented in our feature and didn’t clean up properly
  2. Our tooling can go wrong and perform a bad auto-import, or we pick bad item from the suggested list of imports
  3. We might import stuff from lazy modules in inappropriate locations
  4. Our new feature is just really big and doesn’t fit into existing budgets

First Approach: Are your files gzipped?

Generally speaking, gzipped file has only about 20% the size of the original file, which can drastically decrease the initial load time of your app. To check if you have gzipped your files, just open the network tab of developer console. In the “Response Headers”, if you should see “Content-Encoding: gzip”, you are good to go.

How to gzip? If you host your Angular app in most of the cloud platforms or CDN, you should not worry about this issue as they probably have handled this for you. However, if you have your own server (such as NodeJS + expressJS) serving your Angular app, definitely check if the files are gzipped. The following is an example to gzip your static assets in a NodeJS + expressJS app. You can hardly imagine this dead simple middleware “compression” would reduce your bundle size from 2.21MB to 495.13KB.

const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())

Second Approach:: Analyze your Angular bundle

If your bundle size does get too big you may want to analyze your bundle because you may have used an inappropriate large-sized third party package or you forgot to remove some package if you are not using it anymore. Webpack has an amazing feature to give us a visual idea of the composition of a webpack bundle.

enter image description here

It’s super easy to get this graph.

  1. npm install -g webpack-bundle-analyzer
  2. In your Angular app, run ng build --stats-json (don’t use flag --prod). By enabling --stats-json you will get an additional file stats.json
  3. Finally, run webpack-bundle-analyzer ./dist/stats.json and your browser will pop up the page at localhost:8888. Have fun with it.

ref 1: How Did Angular CLI Budgets Save My Day And How They Can Save Yours

ref 2: Optimize Angular bundle size in 4 steps

c# foreach (property in object)... Is there a simple way of doing this?

Use Reflection to do this

SomeClass A = SomeClass(...)
PropertyInfo[] properties = A.GetType().GetProperties();

npm check and update package if needed

To check if any module in a project is 'old':

npm outdated

'outdated' will check every module defined in package.json and see if there is a newer version in the NPM registry.

For example, say xml2js 0.2.6 (located in node_modules in the current project) is outdated because a newer version exists (0.2.7). You would see:

[email protected] node_modules/xml2js current=0.2.6

To update all dependencies, if you are confident this is desirable:

npm update

Or, to update a single dependency such as xml2js:

npm update xml2js

How to find longest string in the table column data

SELECT CITY,LENGTH(CITY) FROM STATION GROUP BY CITY ORDER BY LENGTH(CITY) ASC LIMIT 1;
SELECT CITY,LENGTH(CITY) FROM STATION GROUP BY CITY ORDER BY LENGTH(CITY) DESC LIMIT 1;

Flattening a shallow list in Python

If you're just looking to iterate over a flattened version of the data structure and don't need an indexable sequence, consider itertools.chain and company.

>>> list_of_menuitems = [['image00', 'image01'], ['image10'], []]
>>> import itertools
>>> chain = itertools.chain(*list_of_menuitems)
>>> print(list(chain))
['image00', 'image01', 'image10']

It will work on anything that's iterable, which should include Django's iterable QuerySets, which it appears that you're using in the question.

Edit: This is probably as good as a reduce anyway, because reduce will have the same overhead copying the items into the list that's being extended. chain will only incur this (same) overhead if you run list(chain) at the end.

Meta-Edit: Actually, it's less overhead than the question's proposed solution, because you throw away the temporary lists you create when you extend the original with the temporary.

Edit: As J.F. Sebastian says itertools.chain.from_iterable avoids the unpacking and you should use that to avoid * magic, but the timeit app shows negligible performance difference.

How is using "<%=request.getContextPath()%>" better than "../"

request.getContextPath()- returns root path of your application, while ../ - returns parent directory of a file.

You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.

Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.

<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>

PS- This is the one reason I can figure out. Don't know if there is any more significance to it.

How to make <input type="file"/> accept only these types?

Use accept attribute with the MIME_type as values

<input type="file" accept="image/gif, image/jpeg" />

Random number in range [min - max] using PHP

<?php
  $min=1;
  $max=20;
  echo rand($min,$max);
?>

How to open a Bootstrap modal window using jQuery?

Try This

myModal1 is the id of modal

$('#myModal1').modal({ show: true });

Redraw datatables after using ajax to refresh the table content?

This works for me

var dataTable = $('#HelpdeskOverview').dataTable();

var oSettings = dataTable.fnSettings();
dataTable.fnClearTable(this);
for (var i=0; i<json.aaData.length; i++)
{
   dataTable.oApi._fnAddData(oSettings, json.aaData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
dataTable.fnDraw();

How to run a Command Prompt command with Visual Basic code?

You need to use CreateProcess [ http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx ]

For ex:

LPTSTR szCmdline[] = _tcsdup(TEXT("\"C:\Program Files\MyApp\" -L -S")); CreateProcess(NULL, szCmdline, /.../);

Relay access denied on sending mail, Other domain outside of network

If it is giving you relay access denied when you are trying to send an email from outside your network to a domain that your server is not authoritative for then it means your receive connector does not grant you the permissions for sending/relaying. Most likely what you need to do is to authenticate to the server to be granted the permissions for relaying but that does depend upon the configuration of your receive connector. In Exchange 2007/2010/2013 you would need to enable ExchangeUsers permission group as well as an authentication mechanism such as Basic authentication.

Once you're sure your receive connector is configured make sure your email client is configured for authentication as well for the SMTP server. It depends upon your server setup but normally for Exchange you would configure the username by itself, no need for the domain to appended or prefixed to it.

To test things out with authentication via telnet you can go over my post here for directions: https://jefferyland.wordpress.com/2013/05/28/essential-exchange-troubleshooting-send-email-via-telnet/

javascript toISOString() ignores timezone offset

This date function below achieves the desired effect without an additional script library. Basically it's just a simple date component concatenation in the right format, and augmenting of the Date object's prototype.

 Date.prototype.dateToISO8601String  = function() {
    var padDigits = function padDigits(number, digits) {
        return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
    }
    var offsetMinutes = this.getTimezoneOffset();
    var offsetHours = offsetMinutes / 60;
    var offset= "Z";    
    if (offsetHours < 0)
      offset = "-" + padDigits(offsetHours.replace("-","") + "00",4);
    else if (offsetHours > 0) 
      offset = "+" + padDigits(offsetHours  + "00", 4);

    return this.getFullYear() 
            + "-" + padDigits((this.getUTCMonth()+1),2) 
            + "-" + padDigits(this.getUTCDate(),2) 
            + "T" 
            + padDigits(this.getUTCHours(),2)
            + ":" + padDigits(this.getUTCMinutes(),2)
            + ":" + padDigits(this.getUTCSeconds(),2)
            + "." + padDigits(this.getUTCMilliseconds(),2)
            + offset;

}

Date.dateFromISO8601 = function(isoDateString) {
      var parts = isoDateString.match(/\d+/g);
      var isoTime = Date.UTC(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]);
      var isoDate = new Date(isoTime);
      return isoDate;       
}

function test() {
    var dIn = new Date();
    var isoDateString = dIn.dateToISO8601String();
    var dOut = Date.dateFromISO8601(isoDateString);
    var dInStr = dIn.toUTCString();
    var dOutStr = dOut.toUTCString();
    console.log("Dates are equal: " + (dInStr == dOutStr));
}

Usage:

var d = new Date();
console.log(d.dateToISO8601String());

Hopefully this helps someone else.

EDIT

Corrected UTC issue mentioned in comments, and credit to Alex for the dateFromISO8601 function.

Creating a segue programmatically

For controllers that are in the storyboard.

jhilgert00 is this what you were looking for?

-(IBAction)nav_goHome:(id)sender {
UIViewController *myController = [self.storyboard instantiateViewControllerWithIdentifier:@"HomeController"];
[self.navigationController pushViewController: myController animated:YES];

}

OR...

[self performSegueWithIdentifier:@"loginMainSegue" sender:self];

How to build splash screen in windows forms application?

I ended up doing slightly different, since I was not happy with the other solutions. Basically I did not get them working as intended for some reason.

I did not want the splash to show for a fixed period of time, but rather as long as the MainForm was loading, and load time vary depending on how fast the connection toward the DB was.

In short my MainForm constructor spawn a thread that show my SplashForm, and on the event OnShown the splash thread is aborted. At first this did not work, and the SplashForm would at some times hang (hidden), and when closing the MainForm it would wait on the splash thread to exit. The solution was to catch the ThreadAbortException and call Dispose on the form.

Example code

private readonly Thread _splashThread = null;

public MainForm() {
    InitializeComponent();
    _splashThread = new Thread(new ThreadStart(DoSplash));
    _splashThread.Start();
}

private void DoSplash()
{
    var splashForm = new SplashForm();
    try
    {
        splashForm.ShowDialog();
    }
    catch (ThreadAbortException)
    {
        splashForm.Dispose();
    }
}

protected override void OnShown(EventArgs e)
{
    if (_splashThread != null && _splashThread.IsAlive)
    {
       _splashThread.Abort();
    }
    base.OnShown(e);
}

How do I set up the database.yml file in Rails?

The database.yml is the file where you set up all the information to connect to the database. It differs depending on the kind of DB you use. You can find more information about this in the Rails Guide or any tutorial explaining how to setup a rails project.

The information in the database.yml file is scoped by environment, allowing you to get a different setting for testing, development or production. It is important that you keep those distinct if you don't want the data you use for development deleted by mistake while running your test suite.

Regarding source control, you should not commit this file but instead create a template file for other developers (called database.yml.template). When deploying, the convention is to create this database.yml file in /shared/config directly on the server.

With SVN: svn propset svn:ignore config "database.yml"

With Git: Add config/database.yml to the .gitignore file or with git-extra git ignore config/database.yml


... and now, some examples:

SQLite

adapter: sqlite3
database: db/db_dev_db.sqlite3
pool: 5
timeout: 5000

MYSQL

adapter: mysql
database: my_db
hostname: 127.0.0.1
username: root
password: 
socket: /tmp/mysql.sock
pool: 5
timeout: 5000

MongoDB with MongoID (called mongoid.yml, but basically the same thing)

host: <%= ENV['MONGOID_HOST'] %>
port: <%= ENV['MONGOID_PORT'] %>
username: <%= ENV['MONGOID_USERNAME'] %>
password: <%= ENV['MONGOID_PASSWORD'] %>
database: <%= ENV['MONGOID_DATABASE'] %>
# slaves:
#   - host: slave1.local
#     port: 27018
#   - host: slave2.local
#     port: 27019

How to check if a directory containing a file exist?

EDIT: as of Java8 you'd better use Files class:

Path resultingPath = Files.createDirectories('A/B');

I don't know if this ultimately fixes your problem but class File has method mkdirs() which fully creates the path specified by the file.

File f = new File("/A/B/");
f.mkdirs();

Advantages of using display:inline-block vs float:left in CSS

There is one characteristic about inline-block which may not be straight-forward though. That is that the default value for vertical-align in CSS is baseline. This may cause some unexpected alignment behavior. Look at this article.

http://www.brunildo.org/test/inline-block.html

Instead, when you do a float:left, the divs are independent of each other and you can align them using margin easily.

How do you get the length of a string?

jQuery is a JavaScript library.

You don't need to use jQuery to get the length of a string because it is a basic JavaScript string object property.

somestring.length;

SQL Server: convert ((int)year,(int)month,(int)day) to Datetime

You could convert your values into a 'Decimal' datetime and convert it then to a real datetime column:

select cast(rtrim(year *10000+ month *100+ day) as datetime) as Date from DateTable

See here as well for more info.

Set the maximum character length of a UITextField

I give a supplementary answer based on @Frouo. I think his answer is the most beautiful way. Becuase it's a common control we can reuse.

private var kAssociationKeyMaxLength: Int = 0

extension UITextField {

    @IBInspectable var maxLength: Int {
        get {
            if let length = objc_getAssociatedObject(self, &kAssociationKeyMaxLength) as? Int {
                return length
            } else {
                return Int.max
            }
        }
        set {
            objc_setAssociatedObject(self, &kAssociationKeyMaxLength, newValue, .OBJC_ASSOCIATION_RETAIN)
            self.addTarget(self, action: #selector(checkMaxLength), for: .editingChanged)
        }
    }

    func checkMaxLength(textField: UITextField) {

        guard !self.isInputMethod(), let prospectiveText = self.text,
            prospectiveText.count > maxLength
            else {
                return
        }

        let selection = selectedTextRange
        let maxCharIndex = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
        text = prospectiveText.substring(to: maxCharIndex)
        selectedTextRange = selection
    }

    //The method is used to cancel the check when use Chinese Pinyin input method.
    //Becuase the alphabet also appears in the textfield when inputting, we should cancel the check.
    func isInputMethod() -> Bool {
        if let positionRange = self.markedTextRange {
            if let _ = self.position(from: positionRange.start, offset: 0) {
                return true
            }
        }
        return false
    }

}

Getting the location from an IP address

Look at the API from hostip.info - it provides lots of information.
Example in PHP:

$data = file_get_contents("http://api.hostip.info/country.php?ip=12.215.42.19");
//$data contains: "US"

$data = file_get_contents("http://api.hostip.info/?ip=12.215.42.19");
//$data contains: XML with country, lat, long, city, etc...

If you trust hostip.info, it seems to be a very useful API.

How to style the parent element when hovering a child element?

A simple jquery solution for those who don't need a pure css solution:

_x000D_
_x000D_
    $(".letter").hover(function() {_x000D_
      $(this).closest("#word").toggleClass("hovered")_x000D_
    });
_x000D_
.hovered {_x000D_
  background-color: lightblue;_x000D_
}_x000D_
_x000D_
.letter {_x000D_
  margin: 20px;_x000D_
  background: lightgray;_x000D_
}_x000D_
_x000D_
.letter:hover {_x000D_
  background: grey;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="word">_x000D_
  <div class="letter">T</div>_x000D_
  <div class="letter">E</div>_x000D_
  <div class="letter">S</div>_x000D_
  <div class="letter">T</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Can Flask have optional URL parameters?

@app.route('/', defaults={'path': ''})
@app.route('/< path:path >')
def catch_all(path):
    return 'You want path: %s' % path

http://flask.pocoo.org/snippets/57/

Best way to initialize (empty) array in PHP

$myArray = []; 

Creates empty array.

You can push values onto the array later, like so:

$myArray[] = "tree";
$myArray[] = "house";
$myArray[] = "dog";

At this point, $myArray contains "tree", "house" and "dog". Each of the above commands appends to the array, preserving the items that were already there.

Having come from other languages, this way of appending to an array seemed strange to me. I expected to have to do something like $myArray += "dog" or something... or maybe an "add()" method like Visual Basic collections have. But this direct append syntax certainly is short and convenient.

You actually have to use the unset() function to remove items:

unset($myArray[1]); 

... would remove "house" from the array (arrays are zero-based).

unset($myArray); 

... would destroy the entire array.

To be clear, the empty square brackets syntax for appending to an array is simply a way of telling PHP to assign the indexes to each value automatically, rather than YOU assigning the indexes. Under the covers, PHP is actually doing this:

$myArray[0] = "tree";
$myArray[1] = "house";
$myArray[2] = "dog";

You can assign indexes yourself if you want, and you can use any numbers you want. You can also assign index numbers to some items and not others. If you do that, PHP will fill in the missing index numbers, incrementing from the largest index number assigned as it goes.

So if you do this:

$myArray[10] = "tree";
$myArray[20] = "house";
$myArray[] = "dog";

... the item "dog" will be given an index number of 21. PHP does not do intelligent pattern matching for incremental index assignment, so it won't know that you might have wanted it to assign an index of 30 to "dog". You can use other functions to specify the increment pattern for an array. I won't go into that here, but its all in the PHP docs.

Cheers,

-=Cameron

How can I escape latex code received through user input?

I spent a lot of time trying different answers all around the internet, and I suspect the reasons why one thing works for some people and not for others is due to very small weird differences in application. For context, I needed to read in file names from a csv file that had strange and/or unmappable unicode characters and write them to a new csv file. For what it's worth, here's what worked for me:

s = '\u00e7\u00a3\u0085\u00e5\u008d\u0095' # csv freaks if you try to write this
s = repr(s.encode('utf-8', 'ignore'))[2:-1]

Chrome's remote debugging (USB debugging) not working for Samsung Galaxy S3 running android 4.3

I had success after using ade.exe as explained above, plus using the latest version of Chrome Canary. Apparently your desktop version of Chrome has to be higher than the version running on your Android device.

Swapping pointers in C (char, int)

In C, a string, as you know, is a character pointer (char *). If you want to swap two strings, you're swapping two char pointers, i.e. just two addresses. In order to do any swap in a function, you need to give it the addresses of the two things you're swapping. So in the case of swapping two pointers, you need a pointer to a pointer. Much like to swap an int, you just need a pointer to an int.

The reason your last code snippet doesn't work is because you're expecting it to swap two char pointers -- it's actually written to swap two characters!

Edit: In your example above, you're trying to swap two int pointers incorrectly, as R. Martinho Fernandes points out. That will swap the two ints, if you had:

int a, b;
intSwap(&a, &b);

Add Foreign Key to existing table

i geted through the same problem. I my case the table already have data and there were key in this table that was not present in the reference table. So i had to delete this rows that disrespect the constraints and everything worked.

How do you create a UIImage View Programmatically - Swift

First create UIImageView then add image in UIImageView .

    var imageView : UIImageView
    imageView  = UIImageView(frame:CGRectMake(10, 50, 100, 300));
    imageView.image = UIImage(named:"image.jpg")
    self.view.addSubview(imageView)

if A vs if A is not None:

Most guides I've seen suggest that you should use

if A:

unless you have a reason to be more specific.

There are some slight differences. There are values other than None that return False, for example empty lists, or 0, so have a think about what it is you're really testing for.

Get an object attribute

Use getattr if you have an attribute in string form:

>>> class User(object):
       name = 'John'

>>> u = User()
>>> param = 'name'
>>> getattr(u, param)
'John'

Otherwise use the dot .:

>>> class User(object):
       name = 'John'

>>> u = User()
>>> u.name
'John'

How to get a unique computer identifier in Java (like disk ID or motherboard ID)?

The problem with MAC address is that there can be many network adapters connected to the computer. Most of the newest ones have two by default (wi-fi + cable). In such situation one would have to know which adapter's MAC address should be used. I tested MAC solution on my system, but I have 4 adapters (cable, WiFi, TAP adapter for Virtual Box and one for Bluetooth) and I was not able to decide which MAC I should take... If one would decide to use adapter which is currently in use (has addresses assigned) then new problem appears since someone can take his/her laptop and switch from cable adapter to wi-fi. With such condition MAC stored when laptop was connected through cable will now be invalid.

For example those are adapters I found in my system:

lo MS TCP Loopback interface
eth0 Intel(R) Centrino(R) Advanced-N 6205
eth1 Intel(R) 82579LM Gigabit Network Connection
eth2 VirtualBox Host-Only Ethernet Adapter
eth3 Sterownik serwera dostepu do sieci LAN Bluetooth

Code I've used to list them:

Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
while (nis.hasMoreElements()) {
    NetworkInterface ni = nis.nextElement();
    System.out.println(ni.getName() + " " + ni.getDisplayName());
}

From the options listen on this page, the most acceptable for me, and the one I've used in my solution is the one by @Ozhan Duz, the other one, similar to @finnw answer where he used JACOB, and worth mentioning is com4j - sample which makes use of WMI is available here:

ISWbemLocator wbemLocator = ClassFactory.createSWbemLocator();
ISWbemServices wbemServices = wbemLocator.connectServer("localhost","Root\\CIMv2","","","","",0,null);
ISWbemObjectSet result = wbemServices.execQuery("Select * from Win32_SystemEnclosure","WQL",16,null);
for(Com4jObject obj : result) {
    ISWbemObject wo = obj.queryInterface(ISWbemObject.class);
    System.out.println(wo.getObjectText_(0));
}

This will print some computer information together with computer Serial Number. Please note that all classes required by this example has to be generated by maven-com4j-plugin. Example configuration for maven-com4j-plugin:

<plugin>
    <groupId>org.jvnet.com4j</groupId>
    <artifactId>maven-com4j-plugin</artifactId>
    <version>1.0</version>
    <configuration>
        <libId>565783C6-CB41-11D1-8B02-00600806D9B6</libId>
        <package>win.wmi</package>
        <outputDirectory>${project.build.directory}/generated-sources/com4j</outputDirectory>
    </configuration>
    <executions>
        <execution>
            <id>generate-wmi-bridge</id>
            <goals>
                <goal>gen</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Above's configuration will tell plugin to generate classes in target/generated-sources/com4j directory in the project folder.

For those who would like to see ready-to-use solution, I'm including links to the three classes I wrote to get machine SN on Windows, Linux and Mac OS:

What does a Status of "Suspended" and high DiskIO means from sp_who2?

This is a very broad question, so I am going to give a broad answer.

  1. A query gets suspended when it is requesting access to a resource that is currently not available. This can be a logical resource like a locked row or a physical resource like a memory data page. The query starts running again, once the resource becomes available. 
  2. High disk IO means that a lot of data pages need to be accessed to fulfill the request.

That is all that I can tell from the above screenshot. However, if I were to speculate, you probably have an IO subsystem that is too slow to keep up with the demand. This could be caused by missing indexes or an actually too slow disk. Keep in mind, that 15000 reads for a single OLTP query is slightly high but not uncommon.

python: after installing anaconda, how to import pandas

I'm using python 3.4 and Anaconda3 4.2.

I had the same problem, but it worked (the import pandas works now anyway) for me to install pandas with pip by writing:

python -m pip install pandas

Good luck!

Html.BeginForm and adding properties

I know this is old but you could create a custom extension if you needed to create that form over and over:

public static MvcForm BeginMultipartForm(this HtmlHelper htmlHelper)
{
    return htmlHelper.BeginForm(null, null, FormMethod.Post, 
     new Dictionary<string, object>() { { "enctype", "multipart/form-data" } });
}

Usage then just becomes

<% using(Html.BeginMultipartForm()) { %>

C/C++ line number

C++20 offers a new way to achieve this by using std::source_location. This is currently accessible in gcc an clang as std::experimental::source_location with #include <experimental/source_location>.

The problem with macros like __LINE__ is that if you want to create for example a logging function that outputs the current line number along with a message, you always have to pass __LINE__ as a function argument, because it is expanded at the call site. Something like this:

void log(const std::string msg) {
    std::cout << __LINE__ << " " << msg << std::endl;
}

Will always output the line of the function declaration and not the line where log was actually called from. On the other hand, with std::source_location you can write something like this:

#include <experimental/source_location>
using std::experimental::source_location;

void log(const std::string msg, const source_location loc = source_location::current())
{
    std::cout << loc.line() << " " << msg << std::endl;
}

Here, loc is initialized with the line number pointing to the location where log was called. You can try it online here.

How to check if array element is null to avoid NullPointerException in Java

You can do it on one line of code (without array declaration):

object[] someArray = new object[] 
{
    "aaaa",
    3,
    null
};
bool containsSomeNull = someArray.Any(x => x == null);

angularjs make a simple countdown

It might help to "How to write the code for countdown watch in AngularJS"

Step 1 : HTML Code-sample

<div ng-app ng-controller="ExampleCtrl">
    <div ng-show="countDown_text > 0">Your password is expired in 180 Seconds.</div>
    <div ng-show="countDown_text > 0">Seconds left {{countDown_text}}</div>
    <div ng-show="countDown_text == 0">Your password is expired!.</div>
</div>

Step 2 : The AngulaJs code-sample

function ExampleCtrl($scope, $timeout) {
  var countDowner, countDown = 10;
  countDowner = function() {
    if (countDown < 0) {
      $("#warning").fadeOut(2000);
      countDown = 0;
      return; // quit
    } else {
      $scope.countDown_text = countDown; // update scope
      countDown--; // -1
      $timeout(countDowner, 1000); // loop it again
    }
  };

  $scope.countDown_text = countDown;
  countDowner()
}

The full example over countdown watch in AngularJs as given below.

<!DOCTYPE html>
<html>

<head>
  <title>AngularJS Example - Single Timer Example</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
  <script>
    function ExampleCtrl($scope, $timeout) {
      var countDowner, countDown = 10;
      countDowner = function() {
        if (countDown < 0) {
          $("#warning").fadeOut(2000);
          countDown = 0;
          return; // quit
        } else {
          $scope.countDown_text = countDown; // update scope
          countDown--; // -1
          $timeout(countDowner, 1000); // loop it again
        }
      };

      $scope.countDown_text = countDown;
      countDowner()
    }
  </script>
</head>

<body>
  <div ng-app ng-controller="ExampleCtrl">
    <div ng-show="countDown_text > 0">Your password is expired in 180 Seconds.</div>
    <div ng-show="countDown_text > 0">Seconds left {{countDown_text}}</div>
    <div ng-show="countDown_text == 0">Your password is expired!.</div>
  </div>
</body>

</html>

z-index issue with twitter bootstrap dropdown menu

Still the issue with Bootstrap v3, navbar and dropdown have same z-index ;-( I just increased .dropdown-menu z-index to 1001.

IIS7 - The request filtering module is configured to deny a request that exceeds the request content length

I had similar issue, I resolved by changing the requestlimits maxAllowedContentLength ="40000000" section of applicationhost.config file, located in "C:\Windows\System32\inetsrv\config" directory

Look for security Section and add the sectionGroup.

<sectionGroup name="requestfiltering">
    <section name="requestlimits" maxAllowedContentLength ="40000000" />
</sectionGroup>

*NOTE delete;

<section name="requestfiltering" overrideModeDefault="Deny" />

Is there a way to rollback my last push to Git?

First you need to determine the revision ID of the last known commit. You can use HEAD^ or HEAD~{1} if you know you need to reverse exactly one commit.

git reset --hard <revision_id_of_last_known_good_commit>
git push --force

Cannot find firefox binary in PATH. Make sure firefox is installed

I didn't see the C# anwer to this question here. The trick is to set the BrowserExecutableLocation property on a FirefoxOptions instance, and pass that into the driver constructor:

        var opt = new FirefoxOptions
        {
            BrowserExecutableLocation = @"c:\program files\mozilla firefox\firefox.exe"
        };
        var driver = new FirefoxDriver(opt);

Handling data in a PHP JSON Object

You mean something like this?

<?php

$jsonurl = "http://search.twitter.com/trends.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);

foreach ( $json_output->trends as $trend )
{
    echo "{$trend->name}\n";
}

How to Customize a Progress Bar In Android

If you want to do this in code, here is a sample:

pd = new ProgressDialog(MainActivity.this);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
pd.getWindow().setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
TextView tv = new TextView(this);
tv.setTextColor(Color.WHITE);
tv.setTextSize(20);
tv.setText("Waiting...");
pd.setCustomTitle(tv);
pd.setIndeterminate(true);
pd.show();

Using TextView gives you an option to change color, size, and font of your text. Otherwise you can just call setMessage(), as usual.

Changing :hover to touch/click for mobile devices

I am a CSS noob but I have noticed that hover will work for touch screens so long as it's a "hoverable" element: image, link, button. You can do it all with CSS using the following trick.

Change your div background to an actual image tag within the div or create a dummy link around the entire div, it will then register as a hover when you touch the image.

Doing this will mean that you need the rest of your page to also be "hoverable" so when you touch outside of the image it recognizes that info-slide:hover has ended. My trick is to make all of my other content dummy links.

It's not very elegant but it works.

Pandas Merge - How to avoid duplicating columns

I use the suffixes option in .merge():

dfNew = df.merge(df2, left_index=True, right_index=True,
                 how='outer', suffixes=('', '_y'))
dfNew.drop(dfNew.filter(regex='_y$').columns.tolist(),axis=1, inplace=True)

Thanks @ijoseph

How do I include a newline character in a string in Delphi?

Here's an even shorter approach:

my_string := 'Hello,'#13#10' world!';

Volley - POST/GET parameters

Dealing with GET parameters I iterated on Andrea Motto' solution. The problem was that Volley called GetUrl several times and his solution, using an Iterator, destroyed original Map object. The subsequent Volley internal calls had an empty params object.

I added also the encode of parameters.

This is an inline usage (no subclass).

public void GET(String url, Map<String, String> params, Response.Listener<String> response_listener, Response.ErrorListener error_listener, String API_KEY, String stringRequestTag) {
    final Map<String, String> mParams = params;
    final String mAPI_KEY = API_KEY;
    final String mUrl = url;

    StringRequest stringRequest = new StringRequest(
            Request.Method.GET,
            mUrl,
            response_listener,
            error_listener
    ) {
        @Override
        protected Map<String, String> getParams() {
            return mParams;
        }

        @Override
        public String getUrl() {
            StringBuilder stringBuilder = new StringBuilder(mUrl);
            int i = 1;
            for (Map.Entry<String,String> entry: mParams.entrySet()) {
                String key;
                String value;
                try {
                    key = URLEncoder.encode(entry.getKey(), "UTF-8");
                    value = URLEncoder.encode(entry.getValue(), "UTF-8");
                    if(i == 1) {
                        stringBuilder.append("?" + key + "=" + value);
                    } else {
                        stringBuilder.append("&" + key + "=" + value);
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                i++;

            }
            String url = stringBuilder.toString();

            return url;
        }

        @Override
        public Map<String, String> getHeaders() {
            Map<String, String> headers = new HashMap<>();
            if (!(mAPI_KEY.equals(""))) {
                headers.put("X-API-KEY", mAPI_KEY);
            }
            return headers;
        }
    };

    if (stringRequestTag != null) {
        stringRequest.setTag(stringRequestTag);
    }

    mRequestQueue.add(stringRequest);
}

This function uses headers to pass an APIKEY and sets a TAG to the request useful to cancel it before its completion.

Hope this helps.

app-release-unsigned.apk is not signed

i also appear this problem,and my code below

        storeFile file(properties.getProperty("filepath"))
        storePassword properties.getProperty("keypassword")
        keyAlias properties.getProperty("keyAlias")
        keyPassword properties.getProperty("keypassword")

the reason is property name error,it should be keyPassword not keypassword

AngularJS event on window innerWidth size change

I found a jfiddle that might help here: http://jsfiddle.net/jaredwilli/SfJ8c/

Ive refactored the code to make it simpler for this.

// In your controller
var w = angular.element($window);
$scope.$watch(
  function () {
    return $window.innerWidth;
  },
  function (value) {
    $scope.windowWidth = value;
  },
  true
);

w.bind('resize', function(){
  $scope.$apply();
});

You can then reference to windowWidth from the html

<span ng-bind="windowWidth"></span>

How do I create test and train samples from one dataframe with pandas?

There are many valid answers. Adding one more to the bunch. from sklearn.cross_validation import train_test_split

#gets a random 80% of the entire set
X_train = X.sample(frac=0.8, random_state=1)
#gets the left out portion of the dataset
X_test = X.loc[~df_model.index.isin(X_train.index)]

Catching nullpointerexception in Java

I think your problem is inside CheckCircular, in the while condition:

Assume you have 2 nodes, first N1 and N2 point to the same node, then N1 points to the second node (last) and N2 points to null (because it's N2.next.next). In the next loop, you try to call the 'next' method on N2, but N2 is null. There you have it, NullPointerException

Creating files and directories via Python

import os

path = chap_name

if not os.path.exists(path):
    os.makedirs(path)

filename = img_alt + '.jpg'
with open(os.path.join(path, filename), 'wb') as temp_file:
    temp_file.write(buff)

Key point is to use os.makedirs in place of os.mkdir. It is recursive, i.e. it generates all intermediate directories. See http://docs.python.org/library/os.html

Open the file in binary mode as you are storing binary (jpeg) data.

In response to Edit 2, if img_alt sometimes has '/' in it:

img_alt = os.path.basename(img_alt)

On duplicate key ignore?

Would suggest NOT using INSERT IGNORE as it ignores ALL errors (ie its a sloppy global ignore). Instead, since in your example tag is the unique key, use:

INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c') ON DUPLICATE KEY UPDATE tag=tag;

on duplicate key produces:

Query OK, 0 rows affected (0.07 sec)

print highest value in dict with key

just :

 mydict = {'A':4,'B':10,'C':0,'D':87}
 max(mydict.items(), key=lambda x: x[1])

Adding days to $Date in PHP

Here has an easy way to solve this.

<?php
   $date = "2015-11-17";
   echo date('Y-m-d', strtotime($date. ' + 5 days'));
?>

Output will be:

2015-11-22

Solution has found from here - How to Add Days to Date in PHP

SQL query to select distinct row with minimum value

This alternative approach uses SQL Server's OUTER APPLY clause. This way, it

  1. creates the distinct list of games, and
  2. fetches and outputs the record with the lowest point number for that game.

The OUTER APPLY clause can be imagined as a LEFT JOIN, but with the advantage that you can use values of the main query as parameters in the subquery (here: game).

SELECT colMinPointID
FROM (
  SELECT game
  FROM table
  GROUP BY game
) As rstOuter
OUTER APPLY (
  SELECT TOP 1 id As colMinPointID
  FROM table As rstInner
  WHERE rstInner.game = rstOuter.game
  ORDER BY points
) AS rstMinPoints

Run local python script on remote server

ssh user@machine python < script.py - arg1 arg2

Because cat | is usually not necessary

Getting the error "Java.lang.IllegalStateException Activity has been destroyed" when using tabs with ViewPager

I know this is an old post, but the suggested answers didn't work on my end. I want to leave this here just in case someone will find it useful.

What i did is:

@Override
public void onResume() {
    super.onResume();
    // add all fragments
    FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
    for(Fragment fragment : fragmentPages){
        String tag = fragment.getClass().getSimpleName();
        fragmentTransaction.add(R.id.contentPanel, fragment, tag);
        if(fragmentPages.indexOf(fragment) != currentPosition){
            fragmentTransaction.hide(fragment);
        } else {
            lastTag = tag;
        }
    }
    fragmentTransaction.commit();
}

Then in:

@Override
public void onPause() {
    super.onPause();
    // remove all attached fragments
    for(Fragment fragment: fragmentPages){
        getChildFragmentManager().beginTransaction().remove(fragment).commit();
    }
}

Can't install laravel installer via composer

For macOs users you can use Homebrew instead :

# For php v7.0
brew install [email protected]

# For php v7.1
brew install [email protected]

# For php v7.2
brew install [email protected]

# For php v7.3
brew install [email protected]

# For php v7.4
brew install [email protected]

Passing an array/list into a Python function

You can pass lists just like other types:

l = [1,2,3]

def stuff(a):
   for x in a:
      print a


stuff(l)

This prints the list l. Keep in mind lists are passed as references not as a deep copy.

How do you develop Java Servlets using Eclipse?

You need to install a plugin, There is a free one from the eclipse foundation called the Web Tools Platform. It has all the development functionality that you'll need.

You can get the Java EE Edition of eclipse with has it pre-installed.

To create and run your first servlet:

  1. New... Project... Dynamic Web Project.
  2. Right click the project... New Servlet.
  3. Write some code in the doGet() method.
  4. Find the servers view in the Java EE perspective, it's usually one of the tabs at the bottom.
  5. Right click in there and select new Server.
  6. Select Tomcat X.X and a wizard will point you to finding the installation.
  7. Right click the server you just created and select Add and Remove... and add your created web project.
  8. Right click your servlet and select Run > Run on Server...

That should do it for you. You can use ant to build here if that's what you'd like but eclipse will actually do the build and automatically deploy the changes to the server. With Tomcat you might have to restart it every now and again depending on the change.

How to insert a new key value pair in array in php?

If you are creating new array then try this :

$arr = ['key' => 'value'];

And if array is already created then try this :

$arr['key'] = 'value';

Change keystore password from no password to a non blank password

this way worked better for me:

echo y | keytool -storepasswd -storepass 123456 -keystore /tmp/IT-Root-CA.keystore -import -alias IT-Root-CA -file /etc/pki/ca-trust/source/anchors/IT-Root-CA.crt

machine running:

[root@rhel80-68]# cat /etc/redhat-release 
Red Hat Enterprise Linux release 8.1 (Ootpa)

SQLAlchemy: What's the difference between flush() and commit()?

commit () records these changes in the database. flush () is always called as part of the commit () (1) call. When you use a Session object to query a database, the query returns results from both the database and the reddened parts of the unrecorded transaction it is performing.

How can I make SQL case sensitive string comparison on MySQL?

Instead of using the = operator, you may want to use LIKE or LIKE BINARY

// this returns 1 (true)
select 'A' like 'a'

// this returns 0 (false)
select 'A' like binary 'a'


select * from user where username like binary 'a'

It will take 'a' and not 'A' in its condition

JavaScript equivalent of PHP's in_array()

Array.indexOf was introduced in JavaScript 1.6, but it is not supported in older browsers. Thankfully the chaps over at Mozilla have done all the hard work for you, and provided you with this for compatibility:

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

There are even some handy usage snippets for your scripting pleasure.

How to set the title text color of UIButton?

Example in setting button title color

btnDone.setTitleColor(.black, for: .normal)

How to see log files in MySQL?

shell> mysqladmin flush-logs


shell> mv host_name.err-old backup-directory

"While .. End While" doesn't work in VBA?

VBA is not VB/VB.NET

The correct reference to use is Do..Loop Statement (VBA). Also see the article Excel VBA For, Do While, and Do Until. One way to write this is:

Do While counter < 20
    counter = counter + 1
Loop

(But a For..Next might be more appropriate here.)

Happy coding.

React.createElement: type is invalid -- expected a string

In my case I just had to upgrade from react-router-redux to react-router-redux@next. I'm assuming it must have been some sort of compatibility issue.

How to place div side by side

There are many ways to do what you're asking for:

  1. Using CSS float property:

_x000D_
_x000D_
 <div style="width: 100%; overflow: hidden;">
     <div style="width: 600px; float: left;"> Left </div>
     <div style="margin-left: 620px;"> Right </div>
</div>
_x000D_
_x000D_
_x000D_

  1. Using CSS display property - which can be used to make divs act like a table:

_x000D_
_x000D_
<div style="width: 100%; display: table;">
    <div style="display: table-row">
        <div style="width: 600px; display: table-cell;"> Left </div>
        <div style="display: table-cell;"> Right </div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

There are more methods, but those two are the most popular.

How to check if a String contains only ASCII?

commons-lang3 from Apache contains valuable utility/convenience methods for all kinds of 'problems', including this one.

System.out.println(StringUtils.isAsciiPrintable("!@£$%^&!@£$%^"));

Is there a way to get element by XPath using JavaScript in Selenium WebDriver?

You can use document.evaluate:

Evaluates an XPath expression string and returns a result of the specified type if possible.

It is w3-standardized and whole documented: https://developer.mozilla.org/en-US/docs/Web/API/Document.evaluate

_x000D_
_x000D_
function getElementByXpath(path) {_x000D_
  return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;_x000D_
}_x000D_
_x000D_
console.log( getElementByXpath("//html[1]/body[1]/div[1]") );
_x000D_
<div>foo</div>
_x000D_
_x000D_
_x000D_

https://gist.github.com/yckart/6351935

There's also a great introduction on mozilla developer network: https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript#document.evaluate


Alternative version, using XPathEvaluator:

_x000D_
_x000D_
function getElementByXPath(xpath) {_x000D_
  return new XPathEvaluator()_x000D_
    .createExpression(xpath)_x000D_
    .evaluate(document, XPathResult.FIRST_ORDERED_NODE_TYPE)_x000D_
    .singleNodeValue_x000D_
}_x000D_
_x000D_
console.log( getElementByXPath("//html[1]/body[1]/div[1]") );
_x000D_
<div>foo/bar</div>
_x000D_
_x000D_
_x000D_

How to suppress warnings globally in an R Script

You want options(warn=-1). However, note that warn=0 is not the safest warning level and it should not be assumed as the current one, particularly within scripts or functions. Thus the safest way to temporary turn off warnings is:

oldw <- getOption("warn")
options(warn = -1)

[your "silenced" code]

options(warn = oldw)

Variables declared outside function

Unlike languages that employ 'true' lexical scoping, Python opts to have specific 'namespaces' for variables, whether it be global, nonlocal, or local. It could be argued that making developers consciously code with such namespaces in mind is more explicit, thus more understandable. I would argue that such complexities make the language more unwieldy, but I guess it's all down to personal preference.

Here are some examples regarding global:-

>>> global_var = 5
>>> def fn():
...     print(global_var)
... 
>>> fn()
5
>>> def fn_2():
...     global_var += 2
...     print(global_var)
... 
>>> fn_2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in fn_2
UnboundLocalError: local variable 'global_var' referenced before assignment
>>> def fn_3():
...     global global_var
...     global_var += 2
...     print(global_var)
... 
>>> fn_3()
7

The same patterns can be applied to nonlocal variables too, but this keyword is only available to the latter Python versions.

In case you're wondering, nonlocal is used where a variable isn't global, but isn't within the function definition it's being used. For example, a def within a def, which is a common occurrence partially due to a lack of multi-statement lambdas. There's a hack to bypass the lack of this feature in the earlier Pythons though, I vaguely remember it involving the use of a single-element list...

Note that writing to variables is where these keywords are needed. Just reading from them isn't ambiguous, thus not needed. Unless you have inner defs using the same variable names as the outer ones, which just should just be avoided to be honest.

OnItemCLickListener not working in listview

private AdapterView.OnItemClickListener onItemClickListener;

@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
 .......

final View view = convertView;
convertView.setOnClickListener(new View.OnClickListener() {
    @Override
     public void onClick(View v) {
         if (onItemClickListener != null) {
             onItemClickListener.onItemClick(null, view, position, -1);
         }
      }
 });

return convertView;
}

public void setOnItemClickListener(AdapterView.OnItemClickListener onItemClickListener) {
    this.onItemClickListener = onItemClickListener;
}

Then in your activity, use adapter.setOnItemClickListener() before attaching it to the listview.

Copied from github its worked for me

Rounded table corners CSS only

Add a <div> wrapper around the table, and apply the following CSS

border-radius: x px;
overflow: hidden;
display: inline-block;

to this wrapper.

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

Found this by searching for "linux output formatted columns".

http://www.unix.com/shell-programming-scripting/117543-formatting-output-columns.html

For your needs, it's like:

awk '{ printf "%-20s %-40s\n", $1, $2}'

installing vmware tools: location of GCC binary?

Install prerequisites VMware Tools for LinuxOS:

If you have RHEL/CentOS:

yum install perl gcc make kernel-headers kernel-devel -y

If you have Ubuntu/Debian:

sudo apt-get -y install linux-headers-server build-essential
  • build-essential, also install: dpkg-dev, g++, gcc, lib6-dev, libc-dev, make

Extracted from: http://www.sysadmit.com/2016/01/vmware-tools-linux-instalar-requisitos.html

Convert an ISO date to the date format yyyy-mm-dd in JavaScript

Moment.js will handle date formatting for you. Here is how to include it via a JavaScript tag, and then an example of how to use Moment.js to format a date.

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
moment("2013-03-10T02:00:00Z").format("YYYY-MM-DD") // "2013-03-10"

ASP.NET Web API : Correct way to return a 401/unauthorised response

you can use follow code in asp.net core 2.0:

public IActionResult index()
{
     return new ContentResult() { Content = "My error message", StatusCode = (int)HttpStatusCode.Unauthorized };
}

read word by word from file in C++

First of all, don't loop while (!eof()), it will not work as you expect it to because the eofbit will not be set until after a failed read due to end of file.

Secondly, the normal input operator >> separates on whitespace and so can be used to read "words":

std::string word;
while (file >> word)
{
    ...
}

How do I (or can I) SELECT DISTINCT on multiple columns?

SELECT DISTINCT a,b,c FROM t

is roughly equivalent to:

SELECT a,b,c FROM t GROUP BY a,b,c

It's a good idea to get used to the GROUP BY syntax, as it's more powerful.

For your query, I'd do it like this:

UPDATE sales
SET status='ACTIVE'
WHERE id IN
(
    SELECT id
    FROM sales S
    INNER JOIN
    (
        SELECT saleprice, saledate
        FROM sales
        GROUP BY saleprice, saledate
        HAVING COUNT(*) = 1 
    ) T
    ON S.saleprice=T.saleprice AND s.saledate=T.saledate
 )

How to stop a function

This will end the function, and you can even customize the "Error" message:

import sys

def end():
    if condition:
        # the player wants to play again:
        main()
    elif not condition:
        sys.exit("The player doesn't want to play again") #Right here 

Excel telling me my blank cells aren't blank

A revelation: Some blank cells are not actually blank! As I will show cells can have spaces, newlines and true empty:

example

To find these cells quickly you can do a few things.

  1. The =CODE(A1) formula will return a #VALUE! if the cell is truly empty, otherwise a number will return. This number is the ASCII number used in =CHAR(32).
  2. If you select the cell and click in the formula bar and use the cursor to select all. newline selection example

Removing these:

If you only have a space in the cells these can be removed easily using:

  1. Press ctrl + h to open find and replace.
  2. Enter one space in the find what, leave replace with empty and ensure you have match entire cell contents is ticked in the options.
  3. Press replace all.

If you have newlines this is more difficult and requires VBA:

  1. Right click on the sheet tab > view code.
  2. Then enter the following code. Remember the Chr(10) is a newline only replace this as required, e.g. " " & Char(10) is a space and a newline:

    Sub find_newlines()
        With Me.Cells
            Set c = .Find(Chr(10), LookIn:=xlValues, LookAt:=xlWhole)
            If Not c Is Nothing Then
                firstAddress = c.Address
                Do
                    c.Value = ""
                    Set c = .FindNext(c)
                    If c Is Nothing Then Exit Do
                Loop While c.Address <> firstAddress
            End If
        End With
    End Sub
    
  3. Now run your code pressing F5.


After file supplied: Select the range of interest for improved performance, then run the following:

Sub find_newlines()
    With Selection
        Set c = .Find("", LookIn:=xlValues, LookAt:=xlWhole)
        If Not c Is Nothing Then
            firstAddress = c.Address
            Do
                c.Value = ""
                Set c = .FindNext(c)
                If c Is Nothing Then Exit Do
            Loop While c.Address <> firstAddress
        End If
    End With
End Sub

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

This happened to me because i deleted one of the resources files inside the .metadata folder in my workspace.

After trying all methods, deleting the .metadata folder in my workspace worked.

Infact, this nuke option seems to work when there are a lot of issues related to eclipse bugs. One such example is working-sets. Working-sets are extremely buggy(but useful) and it is there that most of my eclipse problems start.

Hope this helps someone.

Pattern matching using a wildcard

If you really do want to use wildcards to identify specific variables, then you can use a combination of ls() and grep() as follows:

l = ls()
vars.with.result <- l[grep("result", l)]

How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

Using Abizern code for swift 2.2

let objectData = responseString!.dataUsingEncoding(NSUTF8StringEncoding)
let json = try NSJSONSerialization.JSONObjectWithData(objectData!, options: NSJSONReadingOptions.MutableContainers)

Setting and getting localStorage with jQuery

You said you are attempting to get the text from a div and store it on local storage.

Please Note: Text and Html are different. In the question you mentioned text. html() will return Html content like <a>example</a>. if you want to get Text content then you have to use text() instead of html() then the result will be example instead of <a>example<a>. Anyway, I am using your terminology let it be Text.

Step 1: get the text from div.

what you did is not get the text from div but set the text to a div.

$('#test').html("Test"); 

is actually setting text to div and the output will be a jQuery object. That is why it sets it as [object Object].

To get the text you have to write like this
$('#test').html();

This will return a string not an object so the result will be Test in your case.

Step 2: set it to local storage.

Your approach is correct and you can write it as

localStorage.key=value

But the preferred approach is

localStorage.setItem(key,value); to set

localStorage.getItem(key); to get.

key and value must be strings.

so in your context code will become

$('#test').html("Test");
localStorage.content = $('#test').html();
$('#test').html(localStorage.content);

But I don't find any meaning in your code. Because you want to get the text from div and store it on local storage. And again you are reading the same from local storage and set to div. just like a=10; b=a; a=b;

If you are facing any other problems please update your question accordingly.

Javascript Equivalent to C# LINQ Select

I know it is a late answer but it was useful to me! Just to complete, using the $.grep function you can emulate the linq where().

Linq:

var maleNames = people
.Where(p => p.Sex == "M")
.Select(p => p.Name)

Javascript:

// replace where  with $.grep
//         select with $.map
var maleNames = $.grep(people, function (p) { return p.Sex == 'M'; })
            .map(function (p) { return p.Name; });

Add string in a certain position in Python

I think the above answers are fine, but I would explain that there are some unexpected-but-good side effects to them...

def insert(string_s, insert_s, pos_i=0):
    return string_s[:pos_i] + insert_s + string_s[pos_i:]

If the index pos_i is very small (too negative), the insert string gets prepended. If too long, the insert string gets appended. If pos_i is between -len(string_s) and +len(string_s) - 1, the insert string gets inserted into the correct place.

Add column in dataframe from list

Just assign the list directly:

df['new_col'] = mylist

Alternative
Convert the list to a series or array and then assign:

se = pd.Series(mylist)
df['new_col'] = se.values

or

df['new_col'] = np.array(mylist)

Sort list in C# with LINQ

I assume that you want them sorted by something else also, to get a consistent ordering between all items where AVC is the same. For example by name:

var sortedList = list.OrderBy(x => c.AVC).ThenBy(x => x.Name).ToList();

Showing all errors and warnings

I was able to get all errors via the below code:

ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);

Alert handling in Selenium WebDriver (selenium 2) with Java

This is what worked for me using Explicit Wait from here WebDriver: Advanced Usage

public void checkAlert() {
    try {
        WebDriverWait wait = new WebDriverWait(driver, 2);
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        alert.accept();
    } catch (Exception e) {
        //exception handling
    }
}

How to get UTC value for SYSDATE on Oracle

If you want a timestamp instead of just a date with sysdate, you can specify a timezone using systimestamp:

select systimestamp at time zone 'UTC' from dual

outputs: 29-AUG-17 06.51.14.781998000 PM UTC

Can Console.Clear be used to only clear a line instead of whole console?

My preferred method is to use PadRight. Instead of clearing the line first, this clears the remainder of the line after the new text is displayed, saving a step:

Console.CursorTop = 0;
Console.CursorLeft = 0;
Console.Write("Whatever...".PadRight(Console.BufferWidth));

How to initialize a static array?

Nope, no difference. It's just syntactic sugar. Arrays.asList(..) creates an additional list.

How to convert string into float in JavaScript?

Replace the comma with a dot.

This will only return 554:

var value = parseFloat("554,20")

This will return 554.20:

var value = parseFloat("554.20")

So in the end, you can simply use:

var fValue = parseFloat(document.getElementById("textfield").value.replace(",","."))

Don't forget that parseInt() should only be used to parse integers (no floating points). In your case it will only return 554. Additionally, calling parseInt() on a float will not round the number: it will take its floor (closest lower integer).


Extended example to answer Pedro Ferreira's question from the comments:

If the textfield contains thousands separator dots like in 1.234.567,99 those could be eliminated beforehand with another replace:

var fValue = parseFloat(document.getElementById("textfield").value.replace(/\./g,"").replace(",","."))

Excel formula to display ONLY month and year?

Very easy, trial and error. Go to the cell you want the month in. Type the Month, go to the next cell and type the year, something weird will come up but then go to your number section click on the little arrow in the right bottom and highlight text and it will change to the year you originally typed

What does "opt" mean (as in the "opt" directory)? Is it an abbreviation?

It's usually describes as for optional add-on software packagessource, or anything that isn't part of the base system. Only some distributions use it, others simply use /usr/local.

How to change the color of a button?

If you are trying to set the background as some other resource file in your drawable folder, say, a custom-button.xml, then try this:

button_name.setBackgroundResource(R.drawable.custom_button_file_name);

eg. Say, you have a custom-button.xml file. Then,

button_name.setBackgroundResource(R.drawable.custom_button);

Will set the button background as the custom-button.xml file.

Python Requests throwing SSLError

As mentioned by @Rafael Almeida, the problem you are having is caused by an untrusted SSL certificate. In my case, the SSL certificate was untrusted by my server. To get around this without compromising security, I downloaded the certificate, and installed it on the server (by simply double clicking on the .crt file and then Install Certificate...).

CSS3 background image transition

You can transition background-image. Use the CSS below on the img element:

-webkit-transition: background-image 0.2s ease-in-out;
transition: background-image 0.2s ease-in-out;

This is supported natively by Chrome, Opera and Safari. Firefox hasn't implemented it yet (bugzil.la). Not sure about IE.

Prevent content from expanding grid items

The previous answer is pretty good, but I also wanted to mention that there is a fixed layout equivalent for grids, you just need to write minmax(0, 1fr) instead of 1fr as your track size.

Forcing Internet Explorer 9 to use standards document mode

Make sure you use the right doctype.

eg.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

or just

<!doctype html>

and also read and understand how compatibility modes and developer toolbar for IE work and set modes for IE:

find if an integer exists in a list of integers

The best of code and complete is here:

NumbersList.Exists(p => p.Equals(Input)

Use:

List<int> NumbersList = new List<int>();
private void button1_Click(object sender, EventArgs e)
{
    int Input = Convert.ToInt32(textBox1.Text);
    if (!NumbersList.Exists(p => p.Equals(Input)))
    {
       NumbersList.Add(Input);
    }
    else
    {
        MessageBox.Show("The number entered is in the list","Error");
    }
}

Debugging with Android Studio stuck at "Waiting For Debugger" forever

Restarting Testing device fix the issue for me.

How to check whether a str(variable) is empty or not?

{
test_str1 = "" 
test_str2 = "  "
  
# checking if string is empty 
print ("The zero length string without spaces is empty ? : ", end = "") 
if(len(test_str1) == 0): 
    print ("Yes") 
else : 
    print ("No") 
  
# prints No  
print ("The zero length string with just spaces is empty ? : ", end = "") 
if(len(test_str2) == 0): 
    print ("Yes") 
else : 
    print ("No") 
}

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

Request.Redirect(url,false);

false indicates whether execution of current page should terminate.

Convert array of JSON object strings to array of JS objects

var json = jQuery.parseJSON(s); //If you have jQuery.

Since the comment looks cluttered, please use the parse function after enclosing those square brackets inside the quotes.

var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];

Change the above code to

var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

Eg:

$(document).ready(function() {
    var s= '[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

    s = jQuery.parseJSON(s);

    alert( s[0]["Select"] );
});

And then use the parse function. It'll surely work.

EDIT :Extremely sorry that I gave the wrong function name. it's jQuery.parseJSON

Jquery

The json api

Edit (30 April 2020):

Editing since I got an upvote for this answer. There's a browser native function available instead of JQuery (for nonJQuery users), JSON.parse("<json string here>")

Javascript Regex: How to put a variable inside a regular expression?

const regex = new RegExp(`ReGeX${testVar}ReGeX`);
...
string.replace(regex, "replacement");

Update

Per some of the comments, it's important to note that you may want to escape the variable if there is potential for malicious content (e.g. the variable comes from user input)

ES6 Update

In 2019, this would usually be written using a template string, and the above code has been updated. The original answer was:

var regex = new RegExp("ReGeX" + testVar + "ReGeX");
...
string.replace(regex, "replacement");