Programs & Examples On #Non admin

PowerShell on Windows 7: Set-ExecutionPolicy for regular users

Set-ExecutionPolicy Unrestricted -Scope CurrentUser

This will set the execution policy for the current user (stored in HKEY_CURRENT_USER) rather than the local machine (HKEY_LOCAL_MACHINE). This is useful if you don't have administrative control over the computer.

Start / Stop a Windows Service from a non-Administrator user account

I use the SubInACL utility for this. For example, if I wanted to give the user job on the computer VMX001 the ability to start and stop the World Wide Web Publishing Service (also know as w3svc), I would issue the following command as an Administrator:

subinacl.exe /service w3svc /grant=VMX001\job=PTO

The permissions you can grant are defined as follows (list taken from here):

F : Full Control
R : Generic Read
W : Generic Write
X : Generic eXecute
L : Read controL
Q : Query Service Configuration
S : Query Service Status
E : Enumerate Dependent Services
C : Service Change Configuration
T : Start Service
O : Stop Service
P : Pause/Continue Service
I : Interrogate Service 
U : Service User-Defined Control Commands

So, by specifying PTO, I am entitling the job user to Pause/Continue, Start, and Stop the w3svc service.

Authorize a non-admin developer in Xcode / Mac OS

I am on Snow Leopard and this one didn't quite work for me. But the following procedure worked:

  1. First added another account with admin privileges by ticking "Allow user to administer this computer" under Accounts, for example an account with username test
  2. Logged into the test account
  3. Launched Xcode, compiled and ran my iPhone project. All ok, no errors were thrown related to permissions
  4. Logged out of the test account
  5. Logged in with the another account having admin privileges
  6. Took away the admin priviliges from the test account by removing the tick from "Allow user to administer this computer" under Accounts
  7. Logged back into the test account
  8. Deleted the iPhone project directory and again checked out from the repository (in my case svn)
  9. Launched Xcode, compiled and ran the project. I didn't get any errors and the App ran well in the iPhone Simulator.

Convert utf8-characters to iso-88591 and back in PHP

You need to use the iconv package, specifically its iconv function.

Create folder in Android

Add this permission in Manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

File folder = new File(Environment.getExternalStorageDirectory() + 
                             File.separator + "TollCulator");
boolean success = true;
if (!folder.exists()) {
    success = folder.mkdirs();
}
if (success) {
    // Do something on success
} else {
    // Do something else on failure 
}

when u run the application go too DDMS->File Explorer->mnt folder->sdcard folder->toll-creation folder

When do I need to do "git pull", before or after "git add, git commit"?

I think git pull --rebase is the cleanest way to set your locally recent commits on top of the remote commits which you don't have at a certain point.

So this way you don't have to pull every time you want to start making changes.

How to get different colored lines for different plots in a single figure?

Matplotlib does this by default.

E.g.:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)
plt.show()

Basic plot demonstrating color cycling

And, as you may already know, you can easily add a legend:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)

plt.legend(['y = x', 'y = 2x', 'y = 3x', 'y = 4x'], loc='upper left')

plt.show()

Basic plot with legend

If you want to control the colors that will be cycled through:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

plt.gca().set_color_cycle(['red', 'green', 'blue', 'yellow'])

plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)

plt.legend(['y = x', 'y = 2x', 'y = 3x', 'y = 4x'], loc='upper left')

plt.show()

Plot showing control over default color cycling

If you're unfamiliar with matplotlib, the tutorial is a good place to start.

Edit:

First off, if you have a lot (>5) of things you want to plot on one figure, either:

  1. Put them on different plots (consider using a few subplots on one figure), or
  2. Use something other than color (i.e. marker styles or line thickness) to distinguish between them.

Otherwise, you're going to wind up with a very messy plot! Be nice to who ever is going to read whatever you're doing and don't try to cram 15 different things onto one figure!!

Beyond that, many people are colorblind to varying degrees, and distinguishing between numerous subtly different colors is difficult for more people than you may realize.

That having been said, if you really want to put 20 lines on one axis with 20 relatively distinct colors, here's one way to do it:

import matplotlib.pyplot as plt
import numpy as np

num_plots = 20

# Have a look at the colormaps here and decide which one you'd like:
# http://matplotlib.org/1.2.1/examples/pylab_examples/show_colormaps.html
colormap = plt.cm.gist_ncar
plt.gca().set_prop_cycle(plt.cycler('color', plt.cm.jet(np.linspace(0, 1, num_plots))))

# Plot several different functions...
x = np.arange(10)
labels = []
for i in range(1, num_plots + 1):
    plt.plot(x, i * x + 5 * i)
    labels.append(r'$y = %ix + %i$' % (i, 5*i))

# I'm basically just demonstrating several different legend options here...
plt.legend(labels, ncol=4, loc='upper center', 
           bbox_to_anchor=[0.5, 1.1], 
           columnspacing=1.0, labelspacing=0.0,
           handletextpad=0.0, handlelength=1.5,
           fancybox=True, shadow=True)

plt.show()

Unique colors for 20 lines based on a given colormap

Make columns of equal width in <table>

Found this on HTML table: keep the same width for columns

If you set the style table-layout: fixed; on your table, you can override the browser's automatic column resizing. The browser will then set column widths based on the width of cells in the first row of the table. Change your to and remove the inside of it, and then set fixed widths for the cells in .

Where is Python language used?

Many websites uses Django or Zope/Plone web framework, these are written in Python.

Python is used a lot for writing system administration software, usually when bash scripts (shell script) isn't up to the job, but going C/C++ is an overkill. This is also the spectrum where perl, awk, etc stands. Gentoo's emerge/portage is one example. Mercurial/HG is a distributed version control system (DVCS) written in python.

Many desktop applications are also written in Python. The original Bittorrent was written in python.

Python is also used as the scripting languages for GIMP, Inkscape, Blender, OpenOffice, etc. Python allows advanced users to write plugins and access advanced functionalities that cannot typically be used through a GUI.

How to send email attachments?

Other answers are excellent, though I still wanted to share a different approach in case someone is looking for alternatives.

Main difference here is that using this approach you can use HTML/CSS to format your message, so you can get creative and give some styling to your email. Though you aren't enforced to use HTML, you can also still use only plain text.

Notice that this function accepts sending the email to multiple recipients and also allows to attach multiple files.

I've only tried this on Python 2, but I think it should work fine on 3 as well:

import os.path
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

def send_email(subject, message, from_email, to_email=[], attachment=[]):
    """
    :param subject: email subject
    :param message: Body content of the email (string), can be HTML/CSS or plain text
    :param from_email: Email address from where the email is sent
    :param to_email: List of email recipients, example: ["[email protected]", "[email protected]"]
    :param attachment: List of attachments, exmaple: ["file1.txt", "file2.txt"]
    """
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = ", ".join(to_email)
    msg.attach(MIMEText(message, 'html'))

    for f in attachment:
        with open(f, 'rb') as a_file:
            basename = os.path.basename(f)
            part = MIMEApplication(a_file.read(), Name=basename)

        part['Content-Disposition'] = 'attachment; filename="%s"' % basename
        msg.attach(part)

    email = smtplib.SMTP('your-smtp-host-name.com')
    email.sendmail(from_email, to_email, msg.as_string())

I hope this helps! :-)

Hadoop cluster setup - java.net.ConnectException: Connection refused

I had the similar prolem with OP. As the terminal output suggested, I went to http://wiki.apache.org/hadoop/ConnectionRefused

I tried to change my /etc/hosts file as suggested here, i.e. remove 127.0.1.1 as OP suggested it will create another error.

So in the end, I leave it as is. The following is my /etc/hosts

127.0.0.1       localhost.localdomain   localhost
127.0.1.1       linux
# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

In the end, I found that my namenode did not started correctly, i.e. When you type sudo netstat -lpten | grep java in the terminal, there will not be any JVM process running(listening) on port 9000.

So I made two directories for namenode and datanode respectively(if you have not done so). You don't have to put where I put it, please replace it based on your hadoop directory. i.e.

mkdir -p /home/hadoopuser/hadoop-2.6.2/hdfs/namenode
mkdir -p /home/hadoopuser/hadoop-2.6.2/hdfs/datanode

I reconfigured my hdfs-site.xml.

<configuration>
    <property>
        <name>dfs.replication</name>
        <value>1</value>
    </property>
   <property>
        <name>dfs.namenode.name.dir</name>
        <value>file:/home/hadoopuser/hadoop-2.6.2/hdfs/namenode</value>
    </property>
    <property>
        <name>dfs.datanode.data.dir</name>
        <value>file:/home/hadoopuser/hadoop-2.6.2/hdfs/datanode</value>
    </property>
</configuration>

In terminal, stop your hdfs and yarn with script stop-dfs.sh and stop-yarn.sh. They are located in your hadoop directory/sbin. In my case, it's /home/hadoopuser/hadoop-2.6.2/sbin/.

Then start your hdfs and yarn with script start-dfs.sh and start-yarn.sh After it is started, type jps in your terminal to see if your JVM processes are running correctly. It should show the following.

15678 NodeManager
14982 NameNode
15347 SecondaryNameNode
23814 Jps
15119 DataNode
15548 ResourceManager

Then try to use netstat again to see if your namenode is listening to port 9000

sudo netstat -lpten | grep java

If you successfully set up the namenode, you should see the following in your terminal output.

tcp 0 0 127.0.0.1:9000 0.0.0.0:* LISTEN 1001 175157 14982/java

Then try to type the command hdfs dfs -mkdir /user/hadoopuser If this command executes sucessfully, now you can list your directory in the HDFS user directory by hdfs dfs -ls /user

Func delegate with no return type

All Func delegates return something; all the Action delegates return void.

Func<TResult> takes no arguments and returns TResult:

public delegate TResult Func<TResult>()

Action<T> takes one argument and does not return a value:

public delegate void Action<T>(T obj)

Action is the simplest, 'bare' delegate:

public delegate void Action()

There's also Func<TArg1, TResult> and Action<TArg1, TArg2> (and others up to 16 arguments). All of these (except for Action<T>) are new to .NET 3.5 (defined in System.Core).

Solution to INSTALL_FAILED_INSUFFICIENT_STORAGE error on Android

I have solved it by including android:installLocation="auto" inside <manifest> tag in AndroidManifest.xml file.

MySQL server has gone away - in exactly 60 seconds

I noticed something perhaps relevant.

I had two scripts running, both doing rather slow queries. One of them locked a table and the other had to wait. The one that was waiting had default_socket_timeout = 300. Eventually it quit with "MySQL server has gone away". However, the mysql process list continued to show both query, the slow one still running and the other locked and waiting.

So I don't think mysqld is the culprit. Something has changed in the php mysql client. Quite possibly the default_socket_timeout which I will now set to -1 to see if that changes anything.

How do I list the symbols in a .so file

Try adding -l to the nm flags in order to get the source of each symbol. If the library is compiled with debugging info (gcc -g) this should be the source file and line number. As Konrad said, the object file / static library is probably unknown at this point.

What is the best way to prevent session hijacking?

Have you considered reading a book on PHP security? Highly recommended.

I have had much success with the following method for non SSL certified sites.

  1. Dis-allow multiple sessions under the same account, making sure you aren't checking this solely by IP address. Rather check by token generated upon login which is stored with the users session in the database, as well as IP address, HTTP_USER_AGENT and so forth

  2. Using Relation based hyperlinks Generates a link ( eg. http://example.com/secure.php?token=2349df98sdf98a9asdf8fas98df8 ) The link is appended with a x-BYTE ( preferred size ) random salted MD5 string, upon page redirection the randomly generated token corresponds to a requested page.

    • Upon reload, several checks are done.
    • Originating IP Address
    • HTTP_USER_AGENT
    • Session Token
    • you get the point.
  3. Short Life-span session authentication cookie. as posted above, a cookie containing a secure string, which is one of the direct references to the sessions validity is a good idea. Make it expire every x Minutes, reissuing that token, and re-syncing the session with the new Data. If any mis-matches in the data, either log the user out, or having them re-authenticate their session.

I am in no means an expert on the subject, I'v had a bit of experience in this particular topic, hope some of this helps anyone out there.

Fixed width buttons with Bootstrap

You can also use the .btn-block class on the button, so that it expands to the parent's width.

If the parent is a fixed width element the button will expand to take all width. You can apply existing markup to the container to ensure fixed/fluid buttons take up only the required space.

<div class="span2">
<p><button class="btn btn-primary btn-block">Save</button></p>
<p><button class="btn btn-success btn-block">Download</button></p>
</div>

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
_x000D_
<div class="span2">_x000D_
  <p><button class="btn btn-primary btn-block">Save</button></p>_x000D_
  <p><button class="btn btn-success btn-block">Download</button></p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to set ChartJS Y axis title?

chart.js supports this by defaul check the link. chartjs

you can set the label in the options attribute.

options object looks like this.

options = {
            scales: {
                yAxes: [
                    {
                        id: 'y-axis-1',
                        display: true,
                        position: 'left',
                        ticks: {
                            callback: function(value, index, values) {
                                return value + "%";
                            }
                        },
                        scaleLabel:{
                            display: true,
                            labelString: 'Average Personal Income',
                            fontColor: "#546372"
                        }
                    }   
                ]
            }
        };

regex match any whitespace

Your regex should work 'as-is'. Assuming that it is doing what you want it to.

wordA(\s*)wordB(?! wordc)

This means match wordA followed by 0 or more spaces followed by wordB, but do not match if followed by wordc. Note the single space between ?! and wordc which means that wordA wordB wordc will not match, but wordA wordB wordc will.

Here are some example matches and the associated replacement output:

enter image description here

Note that all matches are replaced no matter how many spaces. There are a couple of other points: -

  • (?! wordc) is a negative lookahead, so you wont match lines wordA wordB wordc which is assume is intended (and is why the last line is not matched). Currently you are relying on the space after ?! to match the whitespace. You may want to be more precise and use (?!\swordc). If you want to match against more than one space before wordc you can use (?!\s*wordc) for 0 or more spaces or (?!\s*+wordc) for 1 or more spaces depending on what your intention is. Of course, if you do want to match lines with wordc after wordB then you shouldn't use a negative lookahead.

  • * will match 0 or more spaces so it will match wordAwordB. You may want to consider + if you want at least one space.

  • (\s*) - the brackets indicate a capturing group. Are you capturing the whitespace to a group for a reason? If not you could just remove the brackets, i.e. just use \s.

Update based on comment

Hello the problem is not the expression but the HTML out put   that are not considered as whitespace. it's a Joomla website.

Preserving your original regex you can use:

wordA((?:\s|&nbsp;)*)wordB(?!(?:\s|&nbsp;)wordc)

The only difference is that not the regex matches whitespace OR &nbsp;. I replaced wordc with \swordc since that is more explicit. Note as I have already pointed out that the negative lookahead ?! will not match when wordB is followed by a single whitespace and wordc. If you want to match multiple whitespaces then see my comments above. I also preserved the capture group around the whitespace, if you don't want this then remove the brackets as already described above.

Example matches:

enter image description here

Find position of a node using xpath

You can do this with XSLT but I'm not sure about straight XPath.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" encoding="utf-8" indent="yes" 
              omit-xml-declaration="yes"/>
  <xsl:template match="a/*[text()='tsr']">
    <xsl:number value-of="position()"/>
  </xsl:template>
  <xsl:template match="text()"/>
</xsl:stylesheet>

How do I check if a property exists on a dynamic anonymous type in c#?

if you can control creating/passing the settings object, i'd recommend using an ExpandoObject instead.

dynamic settings = new ExpandoObject();
settings.Filename = "asdf.txt";
settings.Size = 10;
...

function void Settings(dynamic settings)
{
    if ( ((IDictionary<string, object>)settings).ContainsKey("Filename") )
        .... do something ....
}

Python: How to use RegEx in an if statement?

if re.search(r'pattern', string):

Simple if-test:

if re.search(r'ing\b', "seeking a great perhaps"):     # any words end with ing?
    print("yes")

Pattern check, extract a substring, case insensitive:

match_object = re.search(r'^OUGHT (.*) BE$', "ought to be", flags=re.IGNORECASE)
if match_object:
    assert "to" == match_object.group(1)     # what's between ought and be?

Notes:

  • Use re.search() not re.match. Match restricts to the start of strings, a confusing convention if you ask me. If you do want a string-starting match, use caret or \A instead, re.search(r'^...', ...)

  • Use raw string syntax r'pattern' for the first parameter. Otherwise you would need to double up backslashes, as in re.search('ing\\b', ...)

  • In this example, \b is a special sequence meaning word-boundary in regex. Not to be confused with backspace.

  • re.search() returns None if it doesn't find anything, which is always falsy.

  • re.search() returns a Match object if it finds anything, which is always truthy.

  • a group is what matched inside parentheses

  • group numbering starts at 1

  • Specs

  • Tutorial

Initializing default values in a struct

You don't even need to define a constructor

struct foo {
    bool a = true;
    bool b = true;
    bool c;
 } bar;

To clarify: these are called brace-or-equal-initializers (because you may also use brace initialization instead of equal sign). This is not only for aggregates: you can use this in normal class definitions. This was added in C++11.

macro run-time error '9': subscript out of range

When you get the error message, you have the option to click on "Debug": this will lead you to the line where the error occurred. The Dark Canuck seems to be right, and I guess the error occurs on the line:

Sheets("Sheet1").protect Password:="btfd"

because most probably the "Sheet1" does not exist. However, if you say "It works fine, but when I save the file I get the message: run-time error '9': subscription out of range" it makes me think the error occurs on the second line:

ActiveWorkbook.Save

Could you please check this by pressing the Debug button first? And most important, as Gordon Bell says, why are you using a macro to protect a workbook?

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

I realise that it's been a very long time but thought I'd add anyway. If you just want the table, and not the create table statement you could use

select into x from db.schema.y where 1=0

to copy the table to a new DB

Run a single test method with maven

What I do with my TestNG, (sorry, JUnit doesn't support this) test cases is I can assign a group to the test I want to run

@Test(groups="broken")

And then simply run 'mvn -Dgroups=broken'.

What's the fastest way to convert String to Number in JavaScript?

I find that num * 1 is simple, clear, and works for integers and floats...

How is "mvn clean install" different from "mvn install"?

Maven lets you specify either goals or lifecycle phases on the command line (or both).

clean and install are two different phases of two different lifecycles, to which different plugin goals are bound (either per default or explicitly in your pom.xml)

The clean phase, per convention, is meant to make a build reproducible, i.e. it cleans up anything that was created by previous builds. In most cases it does that by calling clean:clean, which deletes the directory bound to ${project.build.directory} (usually called "target")

How to select an element inside "this" in jQuery?

I use this to get the Parent, similarly for child

$( this ).children( 'li.target' ).css("border", "3px double red");

Good Luck

Responsive table handling in Twitter Bootstrap

One option that is available is fooTable. Works great on a Responsive website and allows you to set multiple breakpoints... fooTable Link

Initialize/reset struct to zero/null

Better than all above is ever to use Standard C specification for struct initialization:

struct StructType structVar = {0};

Here are all bits zero (ever).

How to retrieve the dimensions of a view?

Use the View's post method like this

post(new Runnable() {   
    @Override
    public void run() {
        Log.d(TAG, "width " + MyView.this.getMeasuredWidth());
        }
    });

How to get the home directory in Python?

You want to use os.path.expanduser.
This will ensure it works on all platforms:

from os.path import expanduser
home = expanduser("~")

If you're on Python 3.5+ you can use pathlib.Path.home():

from pathlib import Path
home = str(Path.home())

ASP.NET MVC Custom Error Handling Application_Error Global.asax?

I found a solution for ajax issue noted by Lion_cl.

global.asax:

protected void Application_Error()
    {           
        if (HttpContext.Current.Request.IsAjaxRequest())
        {
            HttpContext ctx = HttpContext.Current;
            ctx.Response.Clear();
            RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;
            rc.RouteData.Values["action"] = "AjaxGlobalError";

            // TODO: distinguish between 404 and other errors if needed
            rc.RouteData.Values["newActionName"] = "WrongRequest";

            rc.RouteData.Values["controller"] = "ErrorPages";
            IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
            IController controller = factory.CreateController(rc, "ErrorPages");
            controller.Execute(rc);
            ctx.Server.ClearError();
        }
    }

ErrorPagesController

public ActionResult AjaxGlobalError(string newActionName)
    {
        return new AjaxRedirectResult(Url.Action(newActionName), this.ControllerContext);
    }

AjaxRedirectResult

public class AjaxRedirectResult : RedirectResult
{
    public AjaxRedirectResult(string url, ControllerContext controllerContext)
        : base(url)
    {
        ExecuteResult(controllerContext);
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context.RequestContext.HttpContext.Request.IsAjaxRequest())
        {
            JavaScriptResult result = new JavaScriptResult()
            {
                Script = "try{history.pushState(null,null,window.location.href);}catch(err){}window.location.replace('" + UrlHelper.GenerateContentUrl(this.Url, context.HttpContext) + "');"
            };

            result.ExecuteResult(context);
        }
        else
        {
            base.ExecuteResult(context);
        }
    }
}

AjaxRequestExtension

public static class AjaxRequestExtension
{
    public static bool IsAjaxRequest(this HttpRequest request)
    {
        return (request.Headers["X-Requested-With"] != null && request.Headers["X-Requested-With"] == "XMLHttpRequest");
    }
}

How to call a JavaScript function within an HTML body

First include the file in head tag of html , then call the function in script tags under body tags e.g.

Js file function to be called

function tryMe(arg) {
    document.write(arg);
}

HTML FILE

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src='object.js'> </script>
    <title>abc</title><meta charset="utf-8"/>
</head>
<body>
    <script>
    tryMe('This is me vishal bhasin signing in');
    </script>
</body>
</html>

finish

Adding minutes to date time in PHP

One more example of a function to do this: (changing the time and interval formats however you like them according to this for function.date, and this for DateInterval):

(I've also written an alternate form of the below function.)

// Return adjusted time.

function addMinutesToTime( $dateTime, $plusMinutes ) {

    $dateTime = DateTime::createFromFormat( 'Y-m-d H:i', $dateTime );
    $dateTime->add( new DateInterval( 'PT' . ( (integer) $plusMinutes ) . 'M' ) );
    $newTime = $dateTime->format( 'Y-m-d H:i' );

    return $newTime;
}

$adjustedTime = addMinutesToTime( '2011-11-17 05:05', 59 );

echo '<h1>Adjusted Time: ' . $adjustedTime . '</h1>' . PHP_EOL . PHP_EOL;

no debugging symbols found when using gdb

Some Linux distributions don't use the gdb style debugging symbols. (IIRC they prefer dwarf2.)

In general, gcc and gdb will be in sync as to what kind of debugging symbols they use, and forcing a particular style will just cause problems; unless you know that you need something else, use just -g.

How to compare two object variables in EL expression language?

In Expression Language you can just use the == or eq operator to compare object values. Behind the scenes they will actually use the Object#equals(). This way is done so, because until with the current EL 2.1 version you cannot invoke methods with other signatures than standard getter (and setter) methods (in the upcoming EL 2.2 it would be possible).

So the particular line

<c:when test="${lang}.equals(${pageLang})">

should be written as (note that the whole expression is inside the { and })

<c:when test="${lang == pageLang}">

or, equivalently

<c:when test="${lang eq pageLang}">

Both are behind the scenes roughly interpreted as

jspContext.findAttribute("lang").equals(jspContext.findAttribute("pageLang"))

If you want to compare constant String values, then you need to quote it

<c:when test="${lang == 'en'}">

or, equivalently

<c:when test="${lang eq 'en'}">

which is behind the scenes roughly interpreted as

jspContext.findAttribute("lang").equals("en")

C++ multiline string literal

Well ... Sort of. The easiest is to just use the fact that adjacent string literals are concatenated by the compiler:

const char *text =
  "This text is pretty long, but will be "
  "concatenated into just a single string. "
  "The disadvantage is that you have to quote "
  "each part, and newlines must be literal as "
  "usual.";

The indentation doesn't matter, since it's not inside the quotes.

You can also do this, as long as you take care to escape the embedded newline. Failure to do so, like my first answer did, will not compile:

const char *text2 =
  "Here, on the other hand, I've gone crazy \
and really let the literal span several lines, \
without bothering with quoting each line's \
content. This works, but you can't indent.";

Again, note those backslashes at the end of each line, they must be immediately before the line ends, they are escaping the newline in the source, so that everything acts as if the newline wasn't there. You don't get newlines in the string at the locations where you had backslashes. With this form, you obviously can't indent the text since the indentation would then become part of the string, garbling it with random spaces.

Trim spaces from start and end of string

Here, this should do all that you need

function doSomething(input) {
    return input
              .replace(/^\s\s*/, '')     // Remove Preceding white space
              .replace(/\s\s*$/, '')     // Remove Trailing white space
              .replace(/([\s]+)/g, '-'); // Replace remaining white space with dashes
}

alert(doSomething("  something with  some       whitespace   "));

What is the 'dynamic' type in C# 4.0 used for?

It makes it easier for static typed languages (CLR) to interoperate with dynamic ones (python, ruby ...) running on the DLR (dynamic language runtime), see MSDN:

For example, you might use the following code to increment a counter in XML in C#.

Scriptobj.SetProperty("Count", ((int)GetProperty("Count")) + 1);

By using the DLR, you could use the following code instead for the same operation.

scriptobj.Count += 1;

MSDN lists these advantages:

  • Simplifies Porting Dynamic Languages to the .NET Framework
  • Enables Dynamic Features in Statically Typed Languages
  • Provides Future Benefits of the DLR and .NET Framework
  • Enables Sharing of Libraries and Objects
  • Provides Fast Dynamic Dispatch and Invocation

See MSDN for more details.

how to put image in center of html page?

Hey now you can give to body background image

and set the background-position:center center;

as like this

body{
background:url('../img/some.jpg') no-repeat center center;
min-height:100%;
}

'if' statement in jinja2 template

Why the loop?

You could simply do this:

{% if 'priority' in data %}
    <p>Priority: {{ data['priority'] }}</p>
{% endif %}

When you were originally doing your string comparison, you should have used == instead.

Bootstrap 3 .img-responsive images are not responsive inside fieldset in FireFox

This looks like a Bootstrap issue...

Currently, here's a workaround : add .col-xs-12 to your responsive image.

Bootply

How to decrease prod bundle size?

Another way to reduce bundle, is to serve GZIP instead of JS. We went from 2.6mb to 543ko.

https://httpd.apache.org/docs/2.4/mod/mod_deflate.html

Macro to Auto Fill Down to last adjacent cell

Untested....but should work.

Dim lastrow as long

lastrow = range("D65000").end(xlup).Row

ActiveCell.FormulaR1C1 = _
        "=IF(MONTH(RC[-1])>3,"" ""&YEAR(RC[-1])&""-""&RIGHT(YEAR(RC[-1])+1,2),"" ""&YEAR(RC[-1])-1&""-""&RIGHT(YEAR(RC[-1]),2))"
    Selection.AutoFill Destination:=Range("E2:E" & lastrow)
    'Selection.AutoFill Destination:=Range("E2:E"& lastrow)
    Range("E2:E1344").Select

Only exception being are you sure your Autofill code is perfect...

Creating a div element in jQuery

How about this? Here, pElement refers to the element you want this div inside (to be a child of! :).

$("pElement").append("<div></div");

You can easily add anything more to that div in the string - Attributes, Content, you name it. Do note, for attribute values, you need to use the right quotation marks.

How to read/process command line arguments?

The canonical solution in the standard library is argparse (docs):

Here is an example:

from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument("-f", "--file", dest="filename",
                    help="write report to FILE", metavar="FILE")
parser.add_argument("-q", "--quiet",
                    action="store_false", dest="verbose", default=True,
                    help="don't print status messages to stdout")

args = parser.parse_args()

argparse supports (among other things):

  • Multiple options in any order.
  • Short and long options.
  • Default values.
  • Generation of a usage help message.

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

Today I faced the same issue consistently, whenever I exit the eclipse. While trying the above solution provided by TS.xy, the below steps got rid of this issue for now.

  1. Switch to new workspace and close the Eclipse.
  2. Open the Eclipse with new workspace and after that switch to the actual workspace(in which exception occurs).
  3. Actual workspace loaded with all my previous projects.
  4. Now exiting the Eclipse, does not result in that exception.

Hope that this step may work for someone.

Convert String to int array in java

    String str = "1,2,3,4,5,6,7,8,9,0";
    String items[] = str.split(",");
    int ent[] = new int[items.length];
    for(i=0;i<items.length;i++){
        try{
            ent[i] = Integer.parseInt(items[i]);
            System.out.println("#"+i+": "+ent[i]);//Para probar
        }catch(NumberFormatException e){
            //Error
        }
    }

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm

After upgrading lots of packages (Spyder 3 to 4, Keras and Tensorflow and lots of their dependencies), I had the same problem today! I cannot figure out what happened; but the (conda-based) virtual environment that kept using Spyder 3 did not have the problem. Although installing tkinter or changing the backend, via matplotlib.use('TkAgg) as shown above, or this nice post on how to change the backend, might well resolve the problem, I don't see these as rigid solutions. For me, uninstalling matplotlib and reinstalling it was magic and the problem was solved.

pip uninstall matplotlib

... then, install

pip install matplotlib

From all the above, this could be a package management problem, and BTW, I use both conda and pip, whenever feasible.

Spool Command: Do not output SQL statement to file

My shell script calls the sql file and executes it. The spool output had the SQL query at the beginning followed by the query result.

This did not resolve my problem:

set echo off

This resolved my problem:

set verify off

How to read numbers from file in Python?

Not sure why do you need w,h. If these values are actually required and mean that only specified number of rows and cols should be read than you can try the following:

output = []
with open(r'c:\file.txt', 'r') as f:
    w, h  = map(int, f.readline().split())
    tmp = []
    for i, line in enumerate(f):
        if i == h:
            break
        tmp.append(map(int, line.split()[:w]))
    output.append(tmp)

How to use phpexcel to read data and insert into database?

Using the PHPExcel library, the following code will do.

require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';    
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true); //optional

$objPHPExcel = $objReader->load(__DIR__.'/YourExcelFile.xlsx');
$objWorksheet = $objPHPExcel->getActiveSheet();

$i=1;
foreach ($objWorksheet->getRowIterator() as $row) {

    $column_A_Value = $objPHPExcel->getActiveSheet()->getCell("A$i")->getValue();//column A
    //you can add your own columns B, C, D etc.

    //inset $column_A_Value value in DB query here

    $i++;
}

Change Git repository directory location.

Report from the future: April 2018.

I wanted to normalize my local repos on my Mac and my Windows, which had ended up in different local folders.

The Windows 10 client made me go through the "Can't Find" > "Locate" routine, tedious but not terrible. Also need to update the local "Clone path" in Options for future use.

When I consolidated the mac folders, the Github client just found them again - I had to do nothing!

Exporting functions from a DLL with dllexport

If you want plain C exports, use a C project not C++. C++ DLLs rely on name-mangling for all the C++isms (namespaces etc...). You can compile your code as C by going into your project settings under C/C++->Advanced, there is an option "Compile As" which corresponds to the compiler switches /TP and /TC.

If you still want to use C++ to write the internals of your lib but export some functions unmangled for use outside C++, see the second section below.

Exporting/Importing DLL Libs in VC++

What you really want to do is define a conditional macro in a header that will be included in all of the source files in your DLL project:

#ifdef LIBRARY_EXPORTS
#    define LIBRARY_API __declspec(dllexport)
#else
#    define LIBRARY_API __declspec(dllimport)
#endif

Then on a function that you want to be exported you use LIBRARY_API:

LIBRARY_API int GetCoolInteger();

In your library build project create a define LIBRARY_EXPORTS this will cause your functions to be exported for your DLL build.

Since LIBRARY_EXPORTS will not be defined in a project consuming the DLL, when that project includes the header file of your library all of the functions will be imported instead.

If your library is to be cross-platform you can define LIBRARY_API as nothing when not on Windows:

#ifdef _WIN32
#    ifdef LIBRARY_EXPORTS
#        define LIBRARY_API __declspec(dllexport)
#    else
#        define LIBRARY_API __declspec(dllimport)
#    endif
#elif
#    define LIBRARY_API
#endif

When using dllexport/dllimport you do not need to use DEF files, if you use DEF files you do not need to use dllexport/dllimport. The two methods accomplish the same task different ways, I believe that dllexport/dllimport is the recommended method out of the two.

Exporting unmangled functions from a C++ DLL for LoadLibrary/PInvoke

If you need this to use LoadLibrary and GetProcAddress, or maybe importing from another language (i.e PInvoke from .NET, or FFI in Python/R etc) you can use extern "C" inline with your dllexport to tell the C++ compiler not to mangle the names. And since we are using GetProcAddress instead of dllimport we don't need to do the ifdef dance from above, just a simple dllexport:

The Code:

#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)

EXTERN_DLL_EXPORT int getEngineVersion() {
  return 1;
}

EXTERN_DLL_EXPORT void registerPlugin(Kernel &K) {
  K.getGraphicsServer().addGraphicsDriver(
    auto_ptr<GraphicsServer::GraphicsDriver>(new OpenGLGraphicsDriver())
  );
}

And here's what the exports look like with Dumpbin /exports:

  Dump of file opengl_plugin.dll

  File Type: DLL

  Section contains the following exports for opengl_plugin.dll

    00000000 characteristics
    49866068 time date stamp Sun Feb 01 19:54:32 2009
        0.00 version
           1 ordinal base
           2 number of functions
           2 number of names

    ordinal hint RVA      name

          1    0 0001110E getEngineVersion = @ILT+265(_getEngineVersion)
          2    1 00011028 registerPlugin = @ILT+35(_registerPlugin)

So this code works fine:

m_hDLL = ::LoadLibrary(T"opengl_plugin.dll");

m_pfnGetEngineVersion = reinterpret_cast<fnGetEngineVersion *>(
  ::GetProcAddress(m_hDLL, "getEngineVersion")
);
m_pfnRegisterPlugin = reinterpret_cast<fnRegisterPlugin *>(
  ::GetProcAddress(m_hDLL, "registerPlugin")
);

How to Create a Form Dynamically Via Javascript

some thing as follows ::

Add this After the body tag

This is a rough sketch, you will need to modify it according to your needs.

<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");

var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");

var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");

f.appendChild(i);
f.appendChild(s);

//and some more input elements here
//and dont forget to add a submit button

document.getElementsByTagName('body')[0].appendChild(f);

</script>

Converting a String to Object

A Java String is an Object. (String extends Object.)

So you can get an Object reference via assignment/initialisation:

String a = "abc";
Object b = a;

@Media min-width & max-width

If website on small devices behavior like desktop screen then you have to put this meta tag into header before

<meta name="viewport" content="width=device-width, initial-scale=1">

For media queries you can set this as

this will cover your all mobile/cellphone widths

 @media only screen and (min-width: 200px) and (max-width: 767px)  {
    //Put your CSS here for 200px to 767px width devices (cover all width between 200px to 767px //
   
    }

For iPad and iPad pro you have to use

  @media only screen and (min-width: 768px) and (max-width: 1024px)  {
        //Put your CSS here for 768px to 1024px width devices(covers all width between 768px to 1024px //   
  }

If you want to add css for Landscape mode you can add this

and (orientation : landscape)

  @media only screen and (min-width: 200px) and (max-width: 767px) and (orientation : portrait) {
        //Put your CSS here for 200px to 767px width devices (cover all mobile portrait width //        
  }

Error: cannot open display: localhost:0.0 - trying to open Firefox from CentOS 6.2 64bit and display on Win7

In my case the issue was caused due to mismatch in .Xauthority file. Which initially showed up with "Invalid MIT-MAGIC-COOKIE-1" error and then "Error: cannot open display: :0.0" afterwards

Regenerating the .Xauthorityfile from the user under which I am running the vncserver and resetting the password with a restart of the vnc service and dbus service fixed the issue for me.

Check if a string is palindrome

bool IsPalindrome(const char* psz)
{
    int i = 0;
    int j;

    if ((psz == NULL) || (psz[0] == '\0'))
    {
        return false;
    }

    j = strlen(psz) - 1;
    while (i < j)
    {
        if (psz[i] != psz[j])
        {
            return false;
        }
        i++;
        j--;
    }
    return true;

}

// STL string version:

bool IsPalindrome(const string& str)
{
    if (str.empty())
        return false;

    int i = 0;                // first characters
    int j = str.length() - 1; // last character

    while (i < j)
    {
        if (str[i] != str[j])
        {
            return false;
        }
        i++;
        j--;
    }
    return true;
}

Programmatically center TextView text

Try adding the following code for applying the layout params to the TextView

LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(LinearLayout.CENTER_IN_PARENT);
textView.setLayoutParams(lp);

ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)

Try localhost instead of 127.0.0.1 to connect or in your connection-config. Worked for me on a Debian Squeeze Server

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

As another option, you can do look ups like:

class UserAdmin(admin.ModelAdmin):
    list_display = (..., 'get_author')

    def get_author(self, obj):
        return obj.book.author
    get_author.short_description = 'Author'
    get_author.admin_order_field = 'book__author'

How do I autoindent in Netbeans?

If you want auto-indent just like Emacs does it on TAB, i.e. indent the current line and move the cursor to the first non-whitespace character, do this:

  1. Go to Tools -> Options -> Editor -> Macros
  2. Create a new macro and call it something like "tabindent"
  3. Insert the following macro code:

    reindent-line caret-line-first-column caret-begin-line

  4. Click "Set Shortcut" and press TAB

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

FYI this turned out to be an issue for me where I had two tables in a statement like the following:

SELECT * FROM table1
UNION ALL
SELECT * FROM table2

It worked, but then somewhere along the line the order of columns in one of the table definitions got changed. Changing the * to SELECT column1, column2 fixed the issue. No idea how that happened, but lesson learned!

How to get the current date and time

If you create a new Date object, by default it will be set to the current time:

import java.util.Date;
Date now = new Date();

jQuery iframe load() event?

use iframe onload event

$('#theiframe').on("load", function() {
    alert(1);
});

How to convert Milliseconds to "X mins, x seconds" in Java?

Shortest solution:

Here's probably the shortest which also deals with time zones.

System.out.printf("%tT", millis-TimeZone.getDefault().getRawOffset());

Which outputs for example:

00:18:32

Explanation:

%tT is the time formatted for the 24-hour clock as %tH:%tM:%tS.

%tT also accepts longs as input, so no need to create a Date. printf() will simply print the time specified in milliseconds, but in the current time zone therefore we have to subtract the raw offset of the current time zone so that 0 milliseconds will be 0 hours and not the time offset value of the current time zone.

Note #1: If you need the result as a String, you can get it like this:

String t = String.format("%tT", millis-TimeZone.getDefault().getRawOffset());

Note #2: This only gives correct result if millis is less than a day because the day part is not included in the output.

Cannot retrieve string(s) from preferences (settings)

All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if to bind them all together in the way I believe you intend.

Daylight saving time and time zone best practices

For those struggling with this on .NET, see if using DateTimeOffset and/or TimeZoneInfo are worth your while.

If you want to use IANA/Olson time zones, or find the built in types are insufficient for your needs, check out Noda Time, which offers a much smarter date and time API for .NET.

Single quotes vs. double quotes in C or C++

Single quotes are for a single character. Double quotes are for a string (array of characters). You can use single quotes to build up a string one character at a time, if you like.

char myChar     = 'A';
char myString[] = "Hello Mum";
char myOtherString[] = { 'H','e','l','l','o','\0' };

Protecting cells in Excel but allow these to be modified by VBA script

Try using

Worksheet.Protect "Password", UserInterfaceOnly := True

If the UserInterfaceOnly parameter is set to true, VBA code can modify protected cells.

DNS problem, nslookup works, ping doesn't

I think this behavior can be turned off, but Window's online help wasn't extremely clear:

If you disable NetBIOS over TCP/IP, you cannot use broadcast-based NetBIOS name resolution to resolve computer names to IP addresses for computers on the same network segment. If your computers are on the same network segment, and NetBIOS over TCP/IP is disabled, you must install a DNS server and either have the computers register with DNS (or manually configure DNS records) or configure entries in the local Hosts file for each computer.

In Windows XP, there is a checkbox:

Advanced TCP/IP Settings

[ ] Enable LMHOSTS lookup

There is also a book that covers this at length, "Networking Personal Computers with TCP/IP: Building TCP/IP Networks (old O'Reilly book)". Unfortunately, I cannot look it up because I disposed of my copy a while ago.

MySQL 'create schema' and 'create database' - Is there any difference

Database is a collection of schemas and schema is a collection of tables. But in MySQL they use it the same way.

Setting width to wrap_content for TextView through code

There is another way to achieve same result. In case you need to set only one parameter, for example 'height':

TextView textView = (TextView)findViewById(R.id.text_view);
ViewGroup.LayoutParams params = textView.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.setLayoutParams(params);

INFO: No Spring WebApplicationInitializer types detected on classpath

I found the error: I have a library that it was built using jdk 1.6. The Spring main controller and components are in this library. And how I use jdk 1.7, It does not find the classes built in 1.6.

The solution was built all using "compiler compliance level: 1.7" and "Generated .class files compatibility: 1.6", "Source compatibility: 1.6".

I setup this option in Eclipse: Preferences\Java\Compiler.

Thanks everybody.

MySQL: Get column name or alias from query

You could also use MySQLdb.cursors.DictCursor. This turns your result set into a python list of python dictionaries, although it uses a special cursor, thus technically less portable than the accepted answer. Not sure about speed. Here's the edited original code that uses this.

#!/usr/bin/python -u

import MySQLdb
import MySQLdb.cursors

#===================================================================
# connect to mysql
#===================================================================

try:
    db = MySQLdb.connect(host='myhost', user='myuser', passwd='mypass', db='mydb', cursorclass=MySQLdb.cursors.DictCursor)
except MySQLdb.Error, e:
    print 'Error %d: %s' % (e.args[0], e.args[1])
    sys.exit(1)

#===================================================================
# query select from table
#===================================================================

cursor = db.cursor()

sql = 'SELECT ext, SUM(size) AS totalsize, COUNT(*) AS filecount FROM fileindex GROUP BY ext ORDER BY totalsize DESC;'

cursor.execute(sql)
all_rows = cursor.fetchall()

print len(all_rows) # How many rows are returned.
for row in all_rows: # While loops always make me shudder!
    print '%s %s %s\n' % (row['ext'], row['totalsize'], row['filecount'])

cursor.close()
db.close()  

Standard dictionary functions apply, for example, len(row[0]) to count the number of columns for the first row, list(row[0]) for a list of column names (for the first row), etc. Hope this helps!

Object array initialization without default constructor

Nope.

But lo! If you use std::vector<Car>, like you should be (never ever use new[]), then you can specify exactly how elements should be constructed*.

*Well sort of. You can specify the value of which to make copies of.


Like this:

#include <iostream>
#include <vector>

class Car
{
private:
    Car(); // if you don't use it, you can just declare it to make it private
    int _no;
public:
    Car(int no) :
    _no(no)
    {
        // use an initialization list to initialize members,
        // not the constructor body to assign them
    }

    void printNo()
    {
        // use whitespace, itmakesthingseasiertoread
        std::cout << _no << std::endl;
    }
};

int main()
{
    int userInput = 10;

    // first method: userInput copies of Car(5)
    std::vector<Car> mycars(userInput, Car(5)); 

    // second method:
    std::vector<Car> mycars; // empty
    mycars.reserve(userInput); // optional: reserve the memory upfront

    for (int i = 0; i < userInput; ++i)
        mycars.push_back(Car(i)); // ith element is a copy of this

    // return 0 is implicit on main's with no return statement,
    // useful for snippets and short code samples
} 

With the additional function:

void printCarNumbers(Car *cars, int length)
{
    for(int i = 0; i < length; i++) // whitespace! :)
         std::cout << cars[i].printNo();
}

int main()
{
    // ...

    printCarNumbers(&mycars[0], mycars.size());
} 

Note printCarNumbers really should be designed differently, to accept two iterators denoting a range.

Password Protect a SQLite DB. Is it possible?

If you use FluentNHibernate you can use following configuration code:

private ISessionFactory createSessionFactory()
{
    return Fluently.Configure()
            .Database(SQLiteConfiguration.Standard.UsingFileWithPassword(filename, password))
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<DBManager>())
            .ExposeConfiguration(this.buildSchema)
            .BuildSessionFactory();    
}

private void buildSchema(Configuration config)
{
        if (filename_not_exists == true)
        {
            new SchemaExport(config).Create(false, true);
        }
}    

Method UsingFileWithPassword(filename, password) encrypts a database file and sets password.
It runs only if the new database file is created. The old one not encrypted fails when is opened with this method.

Using Excel VBA to export data to MS Access table

@Ahmed

Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".

Sub test()
    dbWb = Application.ActiveWorkbook.FullName
    dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2"  'Data2 is a named range


sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh

Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command

dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon

dbCommand.CommandText = sCommand
dbCommand.Execute

dbCon.Close


End Sub

get UTC timestamp in python with datetime

Another possibility is:

d = datetime.datetime.utcnow()
epoch = datetime.datetime(1970,1,1)
t = (d - epoch).total_seconds()

This works as both "d" and "epoch" are naive datetimes, making the "-" operator valid, and returning an interval. total_seconds() turns the interval into seconds. Note that total_seconds() returns a float, even d.microsecond == 0

error: (-215) !empty() in function detectMultiScale

The error occurs due to missing of xml files or incorrect path of xml file.

Please try the following code,

import numpy as np
import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

cap = cv2.VideoCapture(0)

while 1:
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    for (x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]

        eyes = eye_cascade.detectMultiScale(roi_gray)
        for (ex,ey,ew,eh) in eyes:
            cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

    cv2.imshow('img',img)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()

SVN Repository Search

I do like TRAC - this plugin might be helpful for your task: http://trac-hacks.org/wiki/RepoSearchPlugin

How to tell Maven to disregard SSL errors (and trusting all certs)?

An alternative that worked for me is to tell Maven to use http: instead of https: when using Maven Central by adding the following to settings.xml:

<settings>
   .
   .
   .
  <mirrors>
    <mirror>
        <id>central-no-ssl</id>
        <name>Central without ssl</name>
        <url>http://repo.maven.apache.org/maven2</url>
        <mirrorOf>central</mirrorOf>
    </mirror>
  </mirrors>
   .
   .
   .
</settings>

Your mileage may vary of course.

How to remove all CSS classes using jQuery/JavaScript?

I had similar issue. In my case on disabled elements was applied that aspNetDisabled class and all disabled controls had wrong colors. So, I used jquery to remove this class on every element/control I wont and everything works and looks great now.

This is my code for removing aspNetDisabled class:

$(document).ready(function () {

    $("span").removeClass("aspNetDisabled");
    $("select").removeClass("aspNetDisabled");
    $("input").removeClass("aspNetDisabled");

}); 

Max retries exceeded with URL in requests

When I was writing a selenium browser test script, I encountered this error when calling driver.quit() before a usage of a JS api call.Remember that quiting webdriver is last thing to do!

How do I create a constant in Python?

In Python instead of language enforcing something, people use naming conventions e.g __method for private methods and using _method for protected methods.

So in same manner you can simply declare the constant as all caps e.g.

MY_CONSTANT = "one"

If you want that this constant never changes, you can hook into attribute access and do tricks, but a simpler approach is to declare a function

def MY_CONSTANT():
    return "one"

Only problem is everywhere you will have to do MY_CONSTANT(), but again MY_CONSTANT = "one" is the correct way in python(usually).

You can also use namedtuple to create constants:

>>> from collections import namedtuple
>>> Constants = namedtuple('Constants', ['pi', 'e'])
>>> constants = Constants(3.14, 2.718)
>>> constants.pi
3.14
>>> constants.pi = 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

Reload nginx configuration

Maybe you're not doing it as root?

Try sudo nginx -s reload, if it still doesn't work, you might want to try sudo pkill -HUP nginx.

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

Agreed, i had the same issues and this is what worked and what did not:

WORKED: <img src="Docs/pinoutDOIT32devkitv1.png" width="800"/>
*DOES NOT WORK: <img src="/Docs/pinoutDOIT32devkitv1.png" width="800"/>
DOES NOT WORK: <img src="./Docs/pinoutDOIT32devkitv1.png" width="800"/>*

fatal error LNK1104: cannot open file 'libboost_system-vc110-mt-gd-1_51.lib'

I had same issue reported here. I solved the issue moving the mainTest.cpp from a subfolder src/mainTest/ to the main folder src/ I guess this was your problem too.

Set a default parameter value for a JavaScript function

Yeah this is referred to as a default parameter

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.

Syntax:

function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
   statements
}

Description:

Parameters of functions default to undefined However, in situations it might be useful to set a different default value. This is where default parameters can help.

In the past, the general strategy for setting defaults was to test parameter values in the body of the function and assign a value if they are undefined. If no value is provided in the call, its value would be undefined. You would have to set a conditional check to make sure the parameter is not undefined

With default parameters in ES2015, the check in the function body is no longer necessary. Now you can simply put a default value in the function head.

Example of the differences:

// OLD METHOD
function multiply(a, b) {
  b = (typeof b !== 'undefined') ?  b : 1;
  return a * b;
}

multiply(5, 2); // 10
multiply(5, 1); // 5
multiply(5);    // 5


// NEW METHOD
function multiply(a, b = 1) {
  return a * b;
}

multiply(5, 2); // 10
multiply(5, 1); // 5
multiply(5);    // 5

Different Syntax Examples:

Padding undefined vs other falsy values:

Even if the value is set explicitly when calling, the value of the num argument is the default one.

function test(num = 1) {
  console.log(typeof num);
}

test();          // 'number' (num is set to 1)
test(undefined); // 'number' (num is set to 1 too)

// test with other falsy values:
test('');        // 'string' (num is set to '')
test(null);      // 'object' (num is set to null)

Evaluated at call time:

The default argument gets evaluated at call time, so unlike some other languages, a new object is created each time the function is called.

function append(value, array = []) {
  array.push(value);
  return array;
}

append(1); //[1]
append(2); //[2], not [1, 2]


// This even applies to functions and variables
function callSomething(thing = something()) {
 return thing;
}

function something() {
  return 'sth';
}

callSomething();  //sth

Default parameters are available to later default parameters:

Params already encountered are available to later default parameters

function singularAutoPlural(singular, plural = singular + 's',
                        rallyingCry = plural + ' ATTACK!!!') {
  return [singular, plural, rallyingCry];
}

//["Gecko","Geckos", "Geckos ATTACK!!!"]
singularAutoPlural('Gecko');

//["Fox","Foxes", "Foxes ATTACK!!!"]
singularAutoPlural('Fox', 'Foxes');

//["Deer", "Deer", "Deer ... change."]
singularAutoPlural('Deer', 'Deer', 'Deer peaceably and respectfully \ petition the government for positive change.')

Functions defined inside function body:

Introduced in Gecko 33 (Firefox 33 / Thunderbird 33 / SeaMonkey 2.30). Functions declared in the function body cannot be referred inside default parameters and throw a ReferenceError (currently a TypeError in SpiderMonkey, see bug 1022967). Default parameters are always executed first, function declarations inside the function body evaluate afterwards.

// Doesn't work! Throws ReferenceError.
function f(a = go()) {
  function go() { return ':P'; }
}

Parameters without defaults after default parameters:

Prior to Gecko 26 (Firefox 26 / Thunderbird 26 / SeaMonkey 2.23 / Firefox OS 1.2), the following code resulted in a SyntaxError. This has been fixed in bug 777060 and works as expected in later versions. Parameters are still set left-to-right, overwriting default parameters even if there are later parameters without defaults.

function f(x = 1, y) {
  return [x, y];
}

f(); // [1, undefined]
f(2); // [2, undefined]

Destructured paramet with default value assignment:

You can use default value assignment with the destructuring assignment notation

function f([x, y] = [1, 2], {z: z} = {z: 3}) {
  return x + y + z;
}

f(); // 6

how to pass list as parameter in function

public void SomeMethod(List<DateTime> dates)
{
    // do something
}

JQuery Ajax - How to Detect Network Connection error when making Ajax call

If you are making cross domain call the Use Jsonp. else the error is not returned.

What does android:layout_weight mean?

Think it that way, will be simpler

If you have 3 buttons and their weights are 1,3,1 accordingly, it will work like table in HTML

Provide 5 portions for that line: 1 portion for button 1, 3 portion for button 2 and 1 portion for button 1

Regard,

What's HTML character code 8203?

If you're seeing these in a source be aware that it may be someone attempting to fingerprint text documents to reveal who is leaking information. It also may be an attempt to bypass a spam filter by making the same looking information different on a byte-by-byte level.

See my article on mitigating fingerprinting if you're interested in learning more.

Abstract Class:-Real Time Example

I use often abstract classes in conjuction with Template method pattern.
In main abstract class I wrote the skeleton of main algorithm and make abstract methods as hooks where suclasses can make a specific implementation; I used often when writing data parser (or processor) that need to read data from one different place (file, database or some other sources), have similar processing step (maybe small differences) and different output.
This pattern looks like Strategy pattern but it give you less granularity and can degradated to a difficult mantainable code if main code grow too much or too exceptions from main flow are required (this considerations came from my experience).
Just a small example:

abstract class MainProcess {
  public static class Metrics {
    int skipped;
    int processed;
    int stored;
    int error;
  }
  private Metrics metrics;
  protected abstract Iterator<Item> readObjectsFromSource();
  protected abstract boolean storeItem(Item item);
  protected Item processItem(Item item) {
    /* do something on item and return it to store, or null to skip */
    return item;
  }
  public Metrics getMetrics() {
    return metrics;
  }
  /* Main method */
  final public void process() {
    this.metrics = new Metrics();
    Iterator<Item> items = readObjectsFromSource();
    for(Item item : items) {
      metrics.processed++;
      item = processItem(item);
      if(null != item) {

        if(storeItem(item))
          metrics.stored++;
        else
          metrics.error++;
      }
      else {
        metrics.skipped++;
      }
    }
  } 
}

class ProcessFromDatabase extends MainProcess {
  ProcessFromDatabase(String query) {
    this.query = query;
  }
  protected Iterator<Item> readObjectsFromSource() {
    return sessionFactory.getCurrentSession().query(query).list();
  }
  protected boolean storeItem(Item item) {
    return sessionFactory.getCurrentSession().saveOrUpdate(item);
  }
}

Here another example.

MySQL equivalent of DECODE function in Oracle

Another MySQL option that may look more like Oracle's DECODE is a combination of FIELD and ELT. In the code that follows, FIELD() returns the argument list position of the string that matches Age. ELT() returns the string from ELTs argument list at the position provided by FIELD(). For example, if Age is 14, FIELD(Age, ...) returns 2 because 14 is the 2nd argument of FIELD (not counting Age). Then, ELT(2, ...) returns 'Fourteen', which is the 2nd argument of ELT (not counting the FIELD() argument). IFNULL returns the default AgeBracket if no match to Age is found in the list.

Select Name, IFNULL(ELT(FIELD(Age,
       13, 14, 15, 16, 17, 18, 19),'Thirteen','Fourteen','Fifteen','Sixteen',
       'Seventeen','Eighteen','Nineteen'),
       'Adult') AS AgeBracket
FROM Person

While I don't think this is the best solution to the question either in terms of performance or readability it is interesting as an exploration of MySQL's string functions. Keep in mind that FIELD's output does not seem to be case sensitive. I.e., FIELD('A','A') and FIELD('a','A') both return 1.

Change background position with jQuery

Here you go:

$(document).ready(function(){
    $('#submenu li').hover(function(){
        $('#carousel').css('background-position', '10px 10px');
    }, function(){
        $('#carousel').css('background-position', '');
    });
});

Read user input inside a loop

Try to change the loop like this:

for line in $(cat filename); do
    read input
    echo $input;
done

Unit test:

for line in $(cat /etc/passwd); do
    read input
    echo $input;
    echo "[$line]"
done

Key hash for Android-Facebook app

As answered on a similar issue i found this to be working for me:

  • Copy the apkname.apk file you want to know the hash of to the 'Java\jdk1.7.0_79\bin' folder
  • Run this command keytool -list -printcert -jarfile apkname.apk
  • Copy the SHA1 value and convert it using this site
  • Use the converted Keyhash value (ex. zaHqo1xcaPv6CmvlWnJk3SaNRIQ=)

Node Multer unexpected field

The <NAME> you use in multer's upload.single(<NAME>) function must be the same as the one you use in <input type="file" name="<NAME>" ...>.

So you need to change

var type = upload.single('file')

to

var type = upload.single('recfile')

in you app.js

Hope this helps.

Can I delete a git commit but keep the changes?

One more way to do it.

Add commit on the top of temporary commit and then do:

git rebase -i

To merge two commits into one (command will open text file with explicit instructions, edit it).

Getting the source HTML of the current page from chrome extension

Here is my solution:

chrome.runtime.onMessage.addListener(function(request, sender) {
        if (request.action == "getSource") {
            this.pageSource = request.source;
            var title = this.pageSource.match(/<title[^>]*>([^<]+)<\/title>/)[1];
            alert(title)
        }
    });

    chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
        chrome.tabs.executeScript(
            tabs[0].id,
            { code: 'var s = document.documentElement.outerHTML; chrome.runtime.sendMessage({action: "getSource", source: s});' }
        );
    });

git - Server host key not cached

I solved similar problem using this workaround.

You just have to switch to Embedded Git, push, press Yes button and then switch back to System Git.

You can find this option in

Tools -> Options -> Git

Autonumber value of last inserted row - MS Access / VBA

Private Function addInsert(Media As String, pagesOut As Integer) As Long


    Set rst = db.OpenRecordset("tblenccomponent")
    With rst
        .AddNew
        !LeafletCode = LeafletCode
        !LeafletName = LeafletName
        !UNCPath = "somePath\" + LeafletCode + ".xml"
        !Media = Media
        !CustomerID = cboCustomerID.Column(0)
        !PagesIn = PagesIn
        !pagesOut = pagesOut
        addInsert = CLng(rst!enclosureID) 'ID is passed back to calling routine
        .Update
    End With
    rst.Close

End Function

A python class that acts like dict

I really don't see the right answer to this anywhere

class MyClass(dict):
    
    def __init__(self, a_property):
        self[a_property] = a_property

All you are really having to do is define your own __init__ - that really is all that there is too it.

Another example (little more complex):

class MyClass(dict):

    def __init__(self, planet):
        self[planet] = planet
        info = self.do_something_that_returns_a_dict()
        if info:
            for k, v in info.items():
                self[k] = v

    def do_something_that_returns_a_dict(self):
        return {"mercury": "venus", "mars": "jupiter"}

This last example is handy when you want to embed some kind of logic.

Anyway... in short class GiveYourClassAName(dict) is enough to make your class act like a dict. Any dict operation you do on self will be just like a regular dict.

How to turn on front flash light programmatically in Android?

Complete Code for android Flashlight App

Manifest

  <?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.user.flashlight"
      android:versionCode="1"
      android:versionName="1.0">

      <uses-sdk
          android:minSdkVersion="8"
          android:targetSdkVersion="17"/>

      <uses-permission android:name="android.permission.CAMERA" />
      <uses-feature android:name="android.hardware.camera"/>

      <application
          android:allowBackup="true"
          android:icon="@mipmap/ic_launcher"
          android:label="@string/app_name"
          android:theme="@style/AppTheme" >
          <activity
              android:name=".MainActivity"
              android:label="@string/app_name" >
              <intent-filter>
                  <action android:name="android.intent.action.MAIN" />

                  <category android:name="android.intent.category.LAUNCHER" />
              </intent-filter>
          </activity>
      </application>

  </manifest>

XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="OFF"
        android:id="@+id/button"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:onClick="turnFlashOnOrOff" />
</RelativeLayout>

MainActivity.java

  import android.app.AlertDialog;
  import android.content.DialogInterface;
  import android.content.pm.PackageManager;
  import android.hardware.Camera;
  import android.hardware.Camera.Parameters;
  import android.support.v7.app.AppCompatActivity;
  import android.os.Bundle;
  import android.view.View;
  import android.widget.Button;

  import java.security.Policy;

  public class MainActivity extends AppCompatActivity {

      Button button;
      private Camera camera;
      private boolean isFlashOn;
      private boolean hasFlash;
      Parameters params;

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

          button = (Button) findViewById(R.id.button);

          hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

          if(!hasFlash) {

              AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
              alert.setTitle("Error");
              alert.setMessage("Sorry, your device doesn't support flash light!");
              alert.setButton("OK", new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                      finish();
                  }
              });
              alert.show();
              return;
          }

          getCamera();

          button.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {

                  if (isFlashOn) {
                      turnOffFlash();
                      button.setText("ON");
                  } else {
                      turnOnFlash();
                      button.setText("OFF");
                  }

              }
          });
      }

      private void getCamera() {

          if (camera == null) {
              try {
                  camera = Camera.open();
                  params = camera.getParameters();
              }catch (Exception e) {

              }
          }

      }

      private void turnOnFlash() {

          if(!isFlashOn) {
              if(camera == null || params == null) {
                  return;
              }

              params = camera.getParameters();
              params.setFlashMode(Parameters.FLASH_MODE_TORCH);
              camera.setParameters(params);
              camera.startPreview();
              isFlashOn = true;
          }

      }

      private void turnOffFlash() {

              if (isFlashOn) {
                  if (camera == null || params == null) {
                      return;
                  }

                  params = camera.getParameters();
                  params.setFlashMode(Parameters.FLASH_MODE_OFF);
                  camera.setParameters(params);
                  camera.stopPreview();
                  isFlashOn = false;
              }
      }

      @Override
      protected void onDestroy() {
          super.onDestroy();
      }

      @Override
      protected void onPause() {
          super.onPause();

          // on pause turn off the flash
          turnOffFlash();
      }

      @Override
      protected void onRestart() {
          super.onRestart();
      }

      @Override
      protected void onResume() {
          super.onResume();

          // on resume turn on the flash
          if(hasFlash)
              turnOnFlash();
      }

      @Override
      protected void onStart() {
          super.onStart();

          // on starting the app get the camera params
          getCamera();
      }

      @Override
      protected void onStop() {
          super.onStop();

          // on stop release the camera
          if (camera != null) {
              camera.release();
              camera = null;
          }
      }

  }

Put a Delay in Javascript

If you're okay with ES2017, await is good:

const DEF_DELAY = 1000;

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms || DEF_DELAY));
}

await sleep(100);

Note that the await part needs to be in an async function:

//IIAFE (immediately invoked async function expression)
(async()=>{
  //Do some stuff
  await sleep(100);
  //Do some more stuff
})()

When should I use UNSIGNED and SIGNED INT in MySQL?

For negative integer value, SIGNED is used and for non-negative integer value, UNSIGNED is used. It always suggested to use UNSIGNED for id as a PRIMARY KEY.

break/exit script

Not pretty, but here is a way to implement an exit() command in R which works for me.

exit <- function() {
  .Internal(.invokeRestart(list(NULL, NULL), NULL))
}

print("this is the last message")
exit()
print("you should not see this")

Only lightly tested, but when I run this, I see this is the last message and then the script aborts without any error message.

How to change package name in flutter?

According to the official flutter documentation you just need to change the ApplicationId in app/build.gradle directory. Then you have to just build your apk and the package name of the manifest file will be changed according to the ApplicationId you changed in build.gradle. Because of flutter while building an apk and google play both consider ApplicationId from build.gradle. This solution worked for me.

source: Official Documentation

What does "dereferencing" a pointer mean?

Code and explanation from Pointer Basics:

The dereference operation starts at the pointer and follows its arrow over to access its pointee. The goal may be to look at the pointee state or to change the pointee state. The dereference operation on a pointer only works if the pointer has a pointee -- the pointee must be allocated and the pointer must be set to point to it. The most common error in pointer code is forgetting to set up the pointee. The most common runtime crash because of that error in the code is a failed dereference operation. In Java the incorrect dereference will be flagged politely by the runtime system. In compiled languages such as C, C++, and Pascal, the incorrect dereference will sometimes crash, and other times corrupt memory in some subtle, random way. Pointer bugs in compiled languages can be difficult to track down for this reason.

void main() {   
    int*    x;  // Allocate the pointer x
    x = malloc(sizeof(int));    // Allocate an int pointee,
                            // and set x to point to it
    *x = 42;    // Dereference x to store 42 in its pointee   
}

How to get $HOME directory of different user in bash script?

This works in Linux. Not sure how it behaves in other *nixes.

  getent passwd "${OTHER_USER}"|cut -d\: -f 6

bootstrap 3 tabs not working properly

When I removed the smooth scroll script (https://github.com/cferdinandi/smooth-scroll), it worked.

What is ".NET Core"?

.NET Core is an open source and cross platform version of .NET. Microsoft products, besides the great abilities that they have, were always expensive for usual users, especially end users of products that has been made by .NET technologies.

Most of the low-level customers prefer to use Linux as their OS and before .NET Core they would not like to use Microsoft technologies, despite the great abilities of them. But after .NET Core production, this problem is solved completely and we can satisfy our customers without considering their OS, etc.

How can I wrap text in a label using WPF?

I used this to retrieve data from MySql Database:

AccessText a = new AccessText();    
a.Text=reader[1].ToString();       // MySql reader
a.Width = 70;
a.TextWrapping = TextWrapping.WrapWithOverflow;
labels[i].Content = a;

Convert an object to an XML string

This is my solution, for any list object you can use this code for convert to xml layout. KeyFather is your principal tag and KeySon is where start your Forech.

public string BuildXml<T>(ICollection<T> anyObject, string keyFather, string keySon)
    {
        var settings = new XmlWriterSettings
        {
            Indent = true
        };
        PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
        StringBuilder builder = new StringBuilder();
        using (XmlWriter writer = XmlWriter.Create(builder, settings))
        {
            writer.WriteStartDocument();
            writer.WriteStartElement(keyFather);
            foreach (var objeto in anyObject)
            {
                writer.WriteStartElement(keySon);
                foreach (PropertyDescriptor item in props)
                {
                    writer.WriteStartElement(item.DisplayName);
                    writer.WriteString(props[item.DisplayName].GetValue(objeto).ToString());
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
            }
            writer.WriteFullEndElement();
            writer.WriteEndDocument();
            writer.Flush();
            return builder.ToString();
        }
    }

Laravel Eloquent "WHERE NOT IN"

You can use WhereNotIn in following way also:

ModelName::whereNotIn('book_price', [100,200])->get(['field_name1','field_name2']);

This will return collection of Record with specific fields

image processing to improve tesseract OCR accuracy

  1. fix DPI (if needed) 300 DPI is minimum
  2. fix text size (e.g. 12 pt should be ok)
  3. try to fix text lines (deskew and dewarp text)
  4. try to fix illumination of image (e.g. no dark part of image)
  5. binarize and de-noise image

There is no universal command line that would fit to all cases (sometimes you need to blur and sharpen image). But you can give a try to TEXTCLEANER from Fred's ImageMagick Scripts.

If you are not fan of command line, maybe you can try to use opensource scantailor.sourceforge.net or commercial bookrestorer.

Javascript reduce() on Object

An object can be turned into an array with: Object.entries(), Object.keys(), Object.values(), and then be reduced as array. But you can also reduce an object without creating the intermediate array.

I've created a little helper library odict for working with objects.

npm install --save odict

It has reduce function that works very much like Array.prototype.reduce():

export const reduce = (dict, reducer, accumulator) => {
  for (const key in dict)
    accumulator = reducer(accumulator, dict[key], key, dict);
  return accumulator;
};

You could also assign it to:

Object.reduce = reduce;

as this method is very useful!

So the answer to your question would be:

const result = Object.reduce(
  {
    a: {value:1},
    b: {value:2},
    c: {value:3},
  },
  (accumulator, current) => (accumulator.value += current.value, accumulator), // reducer function must return accumulator
  {value: 0} // initial accumulator value
);

DateTime vs DateTimeOffset

This piece of code from Microsoft explains everything:

// Find difference between Date.Now and Date.UtcNow
  date1 = DateTime.Now;
  date2 = DateTime.UtcNow;
  difference = date1 - date2;
  Console.WriteLine("{0} - {1} = {2}", date1, date2, difference);

  // Find difference between Now and UtcNow using DateTimeOffset
  dateOffset1 = DateTimeOffset.Now;
  dateOffset2 = DateTimeOffset.UtcNow;
  difference = dateOffset1 - dateOffset2;
  Console.WriteLine("{0} - {1} = {2}", 
                    dateOffset1, dateOffset2, difference);
  // If run in the Pacific Standard time zone on 4/2/2007, the example
  // displays the following output to the console:
  //    4/2/2007 7:23:57 PM - 4/3/2007 2:23:57 AM = -07:00:00
  //    4/2/2007 7:23:57 PM -07:00 - 4/3/2007 2:23:57 AM +00:00 = 00:00:00

Get path of executable

There is no cross platform way that I know.

For Linux: readlink /proc/self/exe

Windows: GetModuleFileName

C# int to byte[]

If you want more general information about various methods of representing numbers including Two's Complement have a look at:

Two's Complement and Signed Number Representation on Wikipedia

Get Android shared preferences value in activity/normal class

You use uninstall the app and change the sharedPreferences name then run this application. I think it will resolve the issue.

A sample code to retrieve values from sharedPreferences you can use the following set of code,

SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String channel = (shared.getString(keyValue, ""));

jQuery: Get selected element tag name

As of jQuery 1.6 you should now call prop:

$target.prop("tagName")

See http://api.jquery.com/prop/

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

Is log(n!) = T(n·log(n))?

enter image description here

Sorry, I don't know how to use LaTeX syntax on stackoverflow..

How do I split a string, breaking at a particular character?

Something like:

var divided = str.split("/~/");
var name=divided[0];
var street = divided[1];

Is probably going to be easiest

How to find reason of failed Build without any error or warning

Delete .vs folder & restart VS, worked for me

enter image description here

How to calculate distance from Wifi router using Signal Strength?

In general, this is a really bad way of doing things due to multipath interference. This is definitely more of an RF engineering question than a coding one.

Tl;dr, the wifi RF energy gets scattered in different directions after bouncing off walls, people, the floor etc. There's no way of telling where you are by trianglation alone, unless you're in an empty room with the wifi beacons placed in exactly the right place.

Google is able to get away with this because they essentially can map where every wifi SSID is to a GPS location when any android user (who opts in to their service) walks into range. That way, the next time a user walks by there, even without a perfect GPS signal, the google mothership can tell where you are. Typically, they'll use that in conjunction with a crappy GPS signal.

What I have seen done is a grid of Zigbee or BTLE devices. If you know where these are laid out, you can used the combined RSS to figure out relatively which ones you're closest to, and go from there.

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

I actually found something that worked for me. It converts the text to binary and then to UTF8.

Source Text that has encoding issues: If ‘Yes’, what was your last

SELECT CONVERT(CAST(CONVERT(
    (SELECT CONVERT(CAST(CONVERT(english_text USING LATIN1) AS BINARY) USING UTF8) AS res FROM m_translation WHERE id = 865) 
USING LATIN1) AS BINARY) USING UTF8) AS 'result';

Corrected Result text: If ‘Yes’, what was your last

My source was wrongly encoded twice so I had two do it twice. For one time you can use:

SELECT CONVERT(CAST(CONVERT(column_name USING latin1) AS BINARY) USING UTF8) AS res FROM m_translation WHERE id = 865;

Please excuse me for any formatting mistakes

Passing references to pointers in C++

&s produces temporary pointer to string and you can't make reference to temporary object.

Troubleshooting BadImageFormatException

For .NET Core, there is a Visual Studio 2017 bug that can cause the project properties Build page to show the incorrect platform target. Once you discover that the problem is, the workarounds are pretty easy. You can change the target to some other value and then change it back.

Alternatively, you can add a runtime identifier to the .csproj. If you need your .exe to run as x86 so that it can load a x86 native DLL, add this element within a PropertyGroup:

<RuntimeIdentifier>win-x86</RuntimeIdentifier>

A good place to put this is right after the TargetFramework or TargetFrameworks element.

How to detect page zoom level in all modern browsers?

On Chrome

var ratio = (screen.availWidth / document.documentElement.clientWidth);
var zoomLevel = Number(ratio.toFixed(1).replace(".", "") + "0");

Jquery get input array field

I think the best way, is to use a Propper Form and to use jQuery.serializeArray.

<!-- a form with any type of input -->
<form class="a-form">
    <select name="field[something]">...</select>
    <input type="checkbox" name="field[somethingelse]" ... />
    <input type="radio" name="field[somethingelse2]" ... />
    <input type="text" name="field[somethingelse3]" ... />
</form>

<!-- sample ajax call -->
<script>
$(document).ready(function(){
    $.ajax({
        url: 'submit.php',
        type: 'post',
        data: $('form.a-form').serializeArray(),
        success: function(response){
            ...
        }
    });
});
</script>

The Values will be available in PHP as $_POST['field'][INDEX].

python pip: force install ignoring dependencies

pip has a --no-dependencies switch. You should use that.

For more information, run pip install -h, where you'll see this line:

--no-deps, --no-dependencies
                        Ignore package dependencies

How to make a rest post call from ReactJS code?

Another recently popular packages is : axios

Install : npm install axios --save

Simple Promise based requests


axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

How can I set multiple CSS styles in JavaScript?

See for .. in

Example:

var myStyle = {};
myStyle.fontsize = "12px";
myStyle.left= "200px";
myStyle.top= "100px";
var elem = document.getElementById("myElement");
var elemStyle = elem.style;
for(var prop in myStyle) {
  elemStyle[prop] = myStyle[prop];
}

How to pass an array to a function in VBA?

Your function worked for me after changing its declaration to this ...

Function processArr(Arr As Variant) As String

You could also consider a ParamArray like this ...

Function processArr(ParamArray Arr() As Variant) As String
    'Dim N As Variant
    Dim N As Long
    Dim finalStr As String
    For N = LBound(Arr) To UBound(Arr)
        finalStr = finalStr & Arr(N)
    Next N
    processArr = finalStr
End Function

And then call the function like this ...

processArr("foo", "bar")

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

Add this link:

/usr/local/lib/*.so.*

The total is:

g++ -o main.out main.cpp -I /usr/local/include -I /usr/local/include/opencv -I /usr/local/include/opencv2 -L /usr/local/lib /usr/local/lib/*.so /usr/local/lib/*.so.*

Can I run CUDA on Intel's integrated graphics processor?

Intel HD Graphics is usually the on-CPU graphics chip in newer Core i3/i5/i7 processors.

As far as I know it doesn't support CUDA (which is a proprietary NVidia technology), but OpenCL is supported by NVidia, ATi and Intel.

Elasticsearch difference between MUST and SHOULD bool query

must means: The clause (query) must appear in matching documents. These clauses must match, like logical AND.

should means: At least one of these clauses must match, like logical OR.

Basically they are used like logical operators AND and OR. See this.

Now in a bool query:

must means: Clauses that must match for the document to be included.

should means: If these clauses match, they increase the _score; otherwise, they have no effect. They are simply used to refine the relevance score for each document.


Yes you can use multiple filters inside must.

error: request for member '..' in '..' which is of non-class type

Foo foo2();

change to

Foo foo2;

You get the error because compiler thinks of

Foo foo2()

as of function declaration with name 'foo2' and the return type 'Foo'.

But in that case If we change to Foo foo2 , the compiler might show the error " call of overloaded ‘Foo()’ is ambiguous".

How do I use the Tensorboard callback of Keras?

You should check out Losswise (https://losswise.com), it has a plugin for Keras that's easier to use than Tensorboard and has some nice extra features. With Losswise you'd just use from losswise.libs import LosswiseKerasCallback and then callback = LosswiseKerasCallback(tag='my fancy convnet 1') and you're good to go (see https://docs.losswise.com/#keras-plugin).

How to generate and auto increment Id with Entity Framework

This is a guess :)

Is it because the ID is a string? What happens if you change it to int?

I mean:

 public int Id { get; set; }

SQL Statement using Where clause with multiple values

Try this:

select songName from t
where personName in ('Ryan', 'Holly')
group by songName
having count(distinct personName) = 2

The number in the having should match the amount of people. If you also need the Status to be Complete use this where clause instead of the previous one:

where personName in ('Ryan', 'Holly') and status = 'Complete'

Make 2 functions run at the same time

I think what you are trying to convey can be achieved through multiprocessing. However if you want to do it through threads you can do this. This might help

from threading import Thread
import time

def func1():
    print 'Working'
    time.sleep(2)

def func2():
    print 'Working'
    time.sleep(2)

th = Thread(target=func1)
th.start()
th1=Thread(target=func2)
th1.start()

Array functions in jQuery

An easy way to get the max and min value in an array is as follows. This has been explained at get max & min values in array

var myarray = [5,8,2,4,11,7,3];
// Function to get the Max value in Array
Array.max = function( array ){
return Math.max.apply( Math, array );
};

// Function to get the Min value in Array
Array.min = function( array ){
return Math.min.apply( Math, array );
};
// Usage 
alert(Array.max(myarray));
alert(Array.min(myarray));

get current date from [NSDate date] but set the time to 10:00 am

NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setHour:10];
NSDate *date = [gregorian dateByAddingComponents:comps toDate:currentDate  options:0];
[comps release];

Not tested in xcode though :)

Copy rows from one Datatable to another DataTable?

There is better way to do this.

DataTable targetDataTable = new DataTable(); targetDataTable = changedColumnMetadata.AsEnumerable().Where(dataRow => entityName.Equals(dataRow["EntityName"])).CopyToDataTable();

Please try this and let me know in case of any issues.

Find if value in column A contains value from column B?

You could try this

=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),FALSE, TRUE)

-or-

=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),"FALSE", "File found in row "   & MATCH(<single column I value>,<entire column E range>,0))

you could replace <single column I value> and <entire column E range> with named ranged. That'd probably be the easiest.

Just drag that formula all the way down the length of your I column in whatever column you want.

iptables LOG and DROP in one rule

At work, I needed to log and block SSLv3 connections on ports 993 (IMAPS) and 995 (POP3S) using iptables. So, I combined Gert van Dijk's How to take down SSLv3 in your network using iptables firewall? (POODLE) with Prevok's answer and came up with this:

iptables -N SSLv3
iptables -A SSLv3 -j LOG --log-prefix "SSLv3 Client Hello detected: "
iptables -A SSLv3 -j DROP
iptables -A INPUT \
  -p tcp \! -f -m multiport --dports 993,995 \
  -m state --state ESTABLISHED -m u32 --u32 \
  "0>>22&0x3C@ 12>>26&0x3C@ 0 & 0xFFFFFF00=0x16030000 && \
   0>>22&0x3C@ 12>>26&0x3C@ 2 & 0xFF=0x01 && \
   0>>22&0x3C@ 12>>26&0x3C@ 7 & 0xFFFF=0x0300" \
  -j SSLv3

Explanation

  1. To LOG and DROP, create a custom chain (e.g. SSLv3):

    iptables -N SSLv3
    iptables -A SSLv3 -j LOG --log-prefix "SSLv3 Client Hello detected: "
    iptables -A SSLv3 -j DROP
    
  2. Then, redirect what you want to LOG and DROP to that chain (see -j SSLv3):

    iptables -A INPUT \
      -p tcp \! -f -m multiport --dports 993,995 \
      -m state --state ESTABLISHED -m u32 --u32 \
      "0>>22&0x3C@ 12>>26&0x3C@ 0 & 0xFFFFFF00=0x16030000 && \
       0>>22&0x3C@ 12>>26&0x3C@ 2 & 0xFF=0x01 && \
       0>>22&0x3C@ 12>>26&0x3C@ 7 & 0xFFFF=0x0300" \
      -j SSLv3
    

Note: mind the order of the rules. Those rules did not work for me until I put them above this one I had on my firewall script:

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

Why do we assign a parent reference to the child object in Java?

If you assign parent type to a subclass it means that you agree with to use the common features of the parent class.

It gives you the freedom to abstract from different subclass implementations. As a result limits you with the parent features.

However, this type of assignment is called upcasting.

Parent parent = new Child();  

The opposite is downcasting.

Child child = (Child)parent;

So, if you create instance of Child and downcast it to Parent you can use that type attribute name. If you create instance of Parent you can do the same as with previous case but you can't use salary because there's not such attribute in the Parent. Return to the previous case that can use salary but only if downcasting to Child.

There's more detail explanation

Get current language in CultureInfo

Windows.System.UserProfile.GlobalizationPreferences.Languages[0]

This is the correct way to obtain the currently set system language. System language setting is completely different than culture setting from which you all want to get the language.

For example: User may use "en-GB" language along with "en-US" culture at the same time. Using CurrentCulture and other cultures you will get "en-US", hope you get the difference (that may be innoticable with GB-US, but with other languages?)

Make UINavigationBar transparent

The below code expands upon the top answer chosen for this thread, to get rid of the bottom border and set text color:

  1. The last two coded lines of this code set transparency. I borrowed that code from this thread and it worked perfectly!

  2. The "clipsToBounds" property was code I found which got rid of the bottom border line with OR without transparency set (so if you decide to go with a solid white/black/etc. background instead, there will still be no border line).

  3. The "tintColor" line (2nd coded line) set my back button to a light grey

  4. I kept barTintColor as a backup. I don't know why transparency would not work, but if it doesn't, I want my bg white as I used to have it

    let navigationBarAppearace = UINavigationBar.appearance()
    navigationBarAppearace.tintColor = UIColor.lightGray
    navigationBarAppearace.barTintColor = UIColor.white
    navigationBarAppearace.clipsToBounds = true
    navigationBarAppearace.isTranslucent = true
    navigationBarAppearace.setBackgroundImage(UIImage(), for: .default)
    navigationBarAppearace.shadowImage = UIImage()
    

Illegal character in path at index 16

There's an illegal character at index 16. I'd say it doesn't like the space in the path. You can percent encode special characters like spaces. Replace it with a %20 in this case.

The question I linked to above suggests using URLEncoder:

String thePath = "file://E:/Program Files/IBM/SDP/runtimes/base";
thePath = URLEncoder.encode(thePath, "UTF-8"); 

How to split page into 4 equal parts?

Some good answers here but just adding an approach that won't be affected by borders and padding:

<style type="text/css">
html, body{width: 100%; height: 100%; padding: 0; margin: 0}
div{position: absolute; padding: 1em; border: 1px solid #000}
#nw{background: #f09; top: 0; left: 0; right: 50%; bottom: 50%}
#ne{background: #f90; top: 0; left: 50%; right: 0; bottom: 50%}
#sw{background: #009; top: 50%; left: 0; right: 50%; bottom: 0}
#se{background: #090; top: 50%; left: 50%; right: 0; bottom: 0}
</style>

<div id="nw">test</div>
<div id="ne">test</div>
<div id="sw">test</div>
<div id="se">test</div>

Are strongly-typed functions as parameters possible in TypeScript?

Because you can't easily union a function definition and another data type, I find having these types around useful to strongly type them. Based on Drew's answer.

type Func<TArgs extends any[], TResult> = (...args: TArgs) => TResult; 
//Syntax sugar
type Action<TArgs extends any[]> = Func<TArgs, undefined>; 

Now you can strongly type every parameter and the return type! Here's an example with more parameters than what is above.

save(callback: Func<[string, Object, boolean], number>): number
{
    let str = "";
    let obj = {};
    let bool = true;
    let result: number = callback(str, obj, bool);
    return result;
}

Now you can write a union type, like an object or a function returning an object, without creating a brand new type that may need to be exported or consumed.

//THIS DOESN'T WORK
let myVar1: boolean | (parameters: object) => boolean;

//This works, but requires a type be defined each time
type myBoolFunc = (parameters: object) => boolean;
let myVar1: boolean | myBoolFunc;

//This works, with a generic type that can be used anywhere
let myVar2: boolean | Func<[object], boolean>;

How to check String in response body with mockMvc

Spring security's @WithMockUser and hamcrest's containsString matcher makes for a simple and elegant solution:

@Test
@WithMockUser(roles = "USER")
public void loginWithRoleUserThenExpectUserSpecificContent() throws Exception {
    mockMvc.perform(get("/index"))
            .andExpect(status().isOk())
            .andExpect(content().string(containsString("This content is only shown to users.")));
}

More examples on github

How to read XML response from a URL in java?

If you want to print XML directly onto the screen you can use TransformerFactory

URL url = new URL(urlString);
URLConnection conn = url.openConnection();

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());

TransformerFactory transformerFactory= TransformerFactory.newInstance();
Transformer xform = transformerFactory.newTransformer();

// that’s the default xform; use a stylesheet to get a real one
xform.transform(new DOMSource(doc), new StreamResult(System.out));

AVD Manager - No system image installed for this target

Open your Android SDK Manager and ensure that you download/install a system image for the API level you are developing with.

SQL query to make all data in a column UPPER CASE?

Permanent:

UPDATE
  MyTable
SET
  MyColumn = UPPER(MyColumn)

Temporary:

SELECT
  UPPER(MyColumn) AS MyColumn
FROM
  MyTable

Edit a commit message in SourceTree Windows (already pushed to remote)

On Version 1.9.6.1. For UnPushed commit.

  1. Click on previously committed description
  2. Click Commit icon
  3. Enter new commit message, and choose "Ammend latest commit" from the Commit options dropdown.
  4. Commit your message.

Load HTML file into WebView

probably this sample could help:

  WebView lWebView = (WebView)findViewById(R.id.webView);
  File lFile = new File(Environment.getExternalStorageDirectory() + "<FOLDER_PATH_TO_FILE>/<FILE_NAME>");
  lWebView.loadUrl("file:///" + lFile.getAbsolutePath());

How can I return pivot table output in MySQL?

Correct answer is:

select table_record_id,
group_concat(if(value_name='note', value_text, NULL)) as note
,group_concat(if(value_name='hire_date', value_text, NULL)) as hire_date
,group_concat(if(value_name='termination_date', value_text, NULL)) as termination_date
,group_concat(if(value_name='department', value_text, NULL)) as department
,group_concat(if(value_name='reporting_to', value_text, NULL)) as reporting_to
,group_concat(if(value_name='shift_start_time', value_text, NULL)) as shift_start_time
,group_concat(if(value_name='shift_end_time', value_text, NULL)) as shift_end_time
from other_value
where table_name = 'employee'
and is_active = 'y'
and is_deleted = 'n'
GROUP BY table_record_id

How to use global variable in node.js?

global.myNumber; //Delclaration of the global variable - undefined
global.myNumber = 5; //Global variable initialized to value 5. 
var myNumberSquared = global.myNumber * global.myNumber; //Using the global variable. 

Node.js is different from client Side JavaScript when it comes to global variables. Just because you use the word var at the top of your Node.js script does not mean the variable will be accessible by all objects you require such as your 'basic-logger' .

To make something global just put the word global and a dot in front of the variable's name. So if I want company_id to be global I call it global.company_id. But be careful, global.company_id and company_id are the same thing so don't name global variable the same thing as any other variable in any other script - any other script that will be running on your server or any other place within the same code.

Password masking console application

You could append your keys to an accumulating linked list.

When a backspace key is received, remove the last key from the list.

When you receive the enter key, collapse your list into a string and do the rest of your work.

Wildcard string comparison in Javascript

if(mas[i].indexOf("bird") == 0)
    //there is bird

You.can read about indexOf here: http://www.w3schools.com/jsref/jsref_indexof.asp

What is an instance variable in Java?

An instance variable is a variable that is a member of an instance of a class (i.e., associated with something created with a new), whereas a class variable is a member of the class itself.

Every instance of a class will have its own copy of an instance variable, whereas there is only one of each static (or class) variable, associated with the class itself.

What’s the difference between a class variable and an instance variable?

This test class illustrates the difference:

public class Test {
   
    public static String classVariable = "I am associated with the class";
    public String instanceVariable = "I am associated with the instance";
    
    public void setText(String string){
        this.instanceVariable = string;
    }
    
    public static void setClassText(String string){
        classVariable = string;
    }
    
    public static void main(String[] args) {
        Test test1 = new Test();
        Test test2 = new Test();
        
        // Change test1's instance variable
        test1.setText("Changed");
        System.out.println(test1.instanceVariable); // Prints "Changed"
        // test2 is unaffected
        System.out.println(test2.instanceVariable); // Prints "I am associated with the instance"
        
        // Change class variable (associated with the class itself)
        Test.setClassText("Changed class text");
        System.out.println(Test.classVariable); // Prints "Changed class text"
        
        // Can access static fields through an instance, but there still is only one
        // (not best practice to access static variables through instance)
        System.out.println(test1.classVariable); // Prints "Changed class text"
        System.out.println(test2.classVariable); // Prints "Changed class text"
    }
}

api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file

if anybody unable to update windows online, I suggest you go to http://download.wsusoffline.net/ and download Most recent version.

Then install update generator -> select your operating system. and hit START, just wait few minutes let him download updates and complete all it's process. hope this help.

Image of Offline update generator

How to install requests module in Python 3.4, instead of 2.7

You can specify a Python version for pip to use:

pip3.4 install requests

Python 3.4 has pip support built-in, so you can also use:

python3.4 -m pip install

If you're running Ubuntu (or probably Debian as well), you'll need to install the system pip3 separately:

sudo apt-get install python3-pip

This will install the pip3 executable, so you can use it, as well as the earlier mentioned python3.4 -m pip:

pip3 install requests

Add image in pdf using jspdf

if you have

ReferenceError: Base64 is not defined

you can upload your file here you will have something as :

data:image/jpeg;base64,/veryLongBase64Encode....

on your js do :

var imgData = 'data:image/jpeg;base64,/veryLongBase64Encode....'
var doc = new jsPDF()

doc.setFontSize(40)
doc.addImage(imgData, 'JPEG', 15, 40, 180, 160)

Can see example here

VNC viewer with multiple monitors

The free version of TightVnc viewer (I have TightVnc Viewer 1.5.4 8/3/2011) build does not support this. What you need is RealVNC but VNC Enterprise Edition 4.2 or the Personal Edition. Unfortunately this is not free and you have to pay for a license.

From the RealVNC website [releasenote] http://www.realvnc.com/products/enterprise/4.2/release-notes.html

VNC Viewer: Full-screen mode can span monitors on a multi-monitor system.

Using putty to scp from windows to Linux

Use scp priv_key.pem source user@host:target if you need to connect using a private key.

or if using pscp then use pscp -i priv_key.ppk source user@host:target

How to uncheck a checkbox in pure JavaScript?

You will need to assign an ID to the checkbox:

<input id="checkboxId" type="checkbox" checked="" name="copyNewAddrToBilling">

and then in JavaScript:

document.getElementById("checkboxId").checked = false;

Append text to input field

If you are planning to use appending more then once, you might want to write a function:

//Append text to input element
function jQ_append(id_of_input, text){
    var input_id = '#'+id_of_input;
    $(input_id).val($(input_id).val() + text);
}

After you can just call it:

jQ_append('my_input_id', 'add this text');

Angular ForEach in Angular4/Typescript?

In Typescript use the For Each like below.

selectChildren(data, $event) {
let parentChecked = data.checked;
for(var obj in this.hierarchicalData)
    {
        for (var childObj in obj )
        {
            value.checked = parentChecked;
        }
    }
}

scp from remote host to local host

There must be a user in the AllowUsers section, in the config file /etc/ssh/ssh_config, in the remote machine. You might have to restart sshd after editing the config file.

And then you can copy for example the file "test.txt" from a remote host to the local host

scp [email protected]:test.txt /local/dir


@cool_cs you can user ~ symbol ~/Users/djorge/Desktop if it's your home dir.

In UNIX, absolute paths must start with '/'.

How to URL encode a string in Ruby

str = "\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a"
require 'cgi'
CGI.escape(str)
# => "%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%9A"

Taken from @J-Rou's comment

Can't connect Nexus 4 to adb: unauthorized

I think it has an error when the device tries to display the screen asking for permission, so it does not appear.

This works for me (commands are given in the adb shell):

  1. rm /data/misc/adb/adb_keys;
  2. I sent the public key (adbkey.pub in ~/.android/) from my computer to my device via email;
  3. Invoke stop adbd;
  4. cat adbkey.pub >> /data/misc/adb/adb_keys (authorize myself);
  5. start adbd (restart adb with new keys).

How to write a caption under an image?

To be more semantically correct and answer the OPs orginal question about aligning them side by side I would use this:

HTML

<div class="items">
<figure>
    <img src="hello.png" width="100px" height="100px">
    <figcaption>Caption 1</figcaption>
</figure>
<figure>
    <img src="hi.png" width="100px" height="100px"> 
    <figcaption>Caption 2</figcaption>
</figure></div>

CSS

.items{
text-align:center;
margin:50px auto;}


.items figure{
margin:0px 20px;
display:inline-block;
text-decoration:none;
color:black;}

https://jsfiddle.net/c7borg/jLzc6h72/3/

Real world use of JMS/message queues?

Distributed (a)synchronous computing.
A real world example could be an application-wide notification framework, which sends mails to the stakeholders at various points during the course of application usage. So the application would act as a Producer by create a Message object, putting it on a particular Queue, and moving forward.
There would be a set of Consumers who would subscribe to the Queue in question, and would take care handling the Message sent across. Note that during the course of this transaction, the Producers are decoupled from the logic of how a given Message would be handled.
Messaging frameworks (ActiveMQ and the likes) act as a backbone to facilitate such Message transactions by providing MessageBrokers.

Mouseover or hover vue.js

To show child or sibling elements it's possible with CSS only. If you use :hover before combinators (+, ~, >, space). Then the style applies not to hovered element.

HTML

<body>
  <div class="trigger">
    Hover here.
  </div>
  <div class="hidden">
    This message shows up.
  </div>
</body>

CSS

.hidden { display: none; }
.trigger:hover + .hidden { display: inline; }

How to find GCD, LCM on a set of numbers

int gcf(int a, int b)
{
    while (a != b) // while the two numbers are not equal...
    { 
        // ...subtract the smaller one from the larger one

        if (a > b) a -= b; // if a is larger than b, subtract b from a
        else b -= a; // if b is larger than a, subtract a from b
    }

    return a; // or return b, a will be equal to b either way
}

int lcm(int a, int b)
{
    // the lcm is simply (a * b) divided by the gcf of the two

    return (a * b) / gcf(a, b);
}

upgade python version using pip

Basically, pip comes with python itself.Therefore it carries no meaning for using pip itself to install or upgrade python. Thus,try to install python through installer itself,visit the site "https://www.python.org/downloads/" for more help. Thank you.

Find out how much memory is being used by an object in Python

For big objects you may use a somewhat crude but effective method: check how much memory your Python process occupies in the system, then delete the object and compare.

This method has many drawbacks but it will give you a very fast estimate for very big objects.

What is the (function() { } )() construct in JavaScript?

It is a function expression, it stands for Immediately Invoked Function Expression (IIFE). IIFE is simply a function that is executed right after it is created. So insted of the function having to wait until it is called to be executed, IIFE is executed immediately. Let's construct the IIFE by example. Suppose we have an add function which takes two integers as args and returns the sum lets make the add function into an IIFE,

Step 1: Define the function

function add (a, b){
    return a+b;
}
add(5,5);

Step2: Call the function by wrap the entire functtion declaration into parentheses

(function add (a, b){
    return a+b;
})
//add(5,5);

Step 3: To invock the function immediatly just remove the 'add' text from the call.

(function add (a, b){
    return a+b;
})(5,5);

The main reason to use an IFFE is to preserve a private scope within your function. Inside your javascript code you want to make sure that, you are not overriding any global variable. Sometimes you may accidentaly define a variable that overrides a global variable. Let's try by example. suppose we have an html file called iffe.html and codes inside body tag are-

<body>
    <div id = 'demo'></div>
    <script>
        document.getElementById("demo").innerHTML = "Hello JavaScript!";
    </script> 
</body>

Well, above code will execute with out any question, now assume you decleard a variable named document accidentaly or intentional.

<body>
    <div id = 'demo'></div>
    <script>
        document.getElementById("demo").innerHTML = "Hello JavaScript!";
        const document = "hi there";
        console.log(document);
    </script> 
</body>

you will endup in a SyntaxError: redeclaration of non-configurable global property document.

But if your desire is to declear a variable name documet you can do it by using IFFE.

<body>
    <div id = 'demo'></div>
    <script>
        (function(){
            const document = "hi there";
            this.document.getElementById("demo").innerHTML = "Hello JavaScript!";
            console.log(document);
        })();
        document.getElementById("demo").innerHTML = "Hello JavaScript!";
    </script> 
</body>

Output:

enter image description here

Let's try by an another example, suppose we have an calculator object like bellow-

<body>
    <script>
        var calculator = {
            add:function(a,b){
                return a+b;
            },
            mul:function(a,b){
                return a*b;
            }
        }
        console.log(calculator.add(5,10));
    </script> 
</body>

Well it's working like a charm, what if we accidently re-assigne the value of calculator object.

<body>
    <script>
        var calculator = {
            add:function(a,b){
                return a+b;
            },
            mul:function(a,b){
                return a*b;
            }
        }
        console.log(calculator.add(5,10));
        calculator = "scientific calculator";
        console.log(calculator.mul(5,5));
    </script> 
</body>

yes you will endup with a TypeError: calculator.mul is not a function iffe.html

But with the help of IFFE we can create a private scope where we can create another variable name calculator and use it;

<body>
    <script>
        var calculator = {
            add:function(a,b){
                return a+b;
            },
            mul:function(a,b){
                return a*b;
            }
        }
        var cal = (function(){
            var calculator = {
                sub:function(a,b){
                    return a-b;
                },
                div:function(a,b){
                    return a/b;
                }
            }
            console.log(this.calculator.mul(5,10));
            console.log(calculator.sub(10,5));
            return calculator;
        })();
        console.log(calculator.add(5,10));
        console.log(cal.div(10,5));
    </script> 
</body>

Output: enter image description here

How can I get query parameters from a URL in Vue.js?

More detailed answer to help the newbies of VueJS:

  • First define your router object, select the mode you seem fit. You can declare your routes inside the routes list.
  • Next you would want your main app to know router exists, so declare it inside the main app declaration .
  • Lastly they $route instance holds all the information about the current route. The code will console log just the parameter passed in the url. (*Mounted is similar to document.ready , .ie its called as soon as the app is ready)

And the code itself:

<script src="https://unpkg.com/vue-router"></script>
var router = new VueRouter({
    mode: 'history',
    routes: []
});
var vm =  new Vue({
    router,
    el: '#app',
    mounted: function() {
        q = this.$route.query.q
        console.log(q)
    },
});

Switch on ranges of integers in JavaScript

Here is another way I figured it out:

const x = this.dealer;
switch (true) {
    case (x < 5):
        alert("less than five");
        break;
    case (x < 9):
        alert("between 5 and 8");
        break;
    case (x < 12):
        alert("between 9 and 11");
        break;
    default:
        alert("none");
        break;
}

ASP.NET MVC Global Variables

The steel is far from hot, but I combined @abatishchev's solution with the answer from this post and got to this result. Hope it's useful:

public static class GlobalVars
{
    private const string GlobalKey = "AllMyVars";

    static GlobalVars()
    {
        Hashtable table = HttpContext.Current.Application[GlobalKey] as Hashtable;

        if (table == null)
        {
            table = new Hashtable();
            HttpContext.Current.Application[GlobalKey] = table;
        }
    }

    public static Hashtable Vars
    {
        get { return HttpContext.Current.Application[GlobalKey] as Hashtable; }
    }

    public static IEnumerable<SomeClass> SomeCollection
    {
        get { return GetVar("SomeCollection") as IEnumerable<SomeClass>; }
        set { WriteVar("SomeCollection", value); }
    }

    internal static DateTime SomeDate
    {
        get { return (DateTime)GetVar("SomeDate"); }
        set { WriteVar("SomeDate", value); }
    }

    private static object GetVar(string varName)
    {
        if (Vars.ContainsKey(varName))
        {
            return Vars[varName];
        }

        return null;
    }

    private static void WriteVar(string varName, object value)
    {
        if (value == null)
        {
            if (Vars.ContainsKey(varName))
            {
                Vars.Remove(varName);
            }
            return;
        }

        if (Vars[varName] == null)
        {
            Vars.Add(varName, value);
        }
        else
        {
            Vars[varName] = value;
        }
    }
}

How to change facet labels?

If you have two facets hospital and room but want to rename just one, you can use:

facet_grid( hospital ~ room, labeller = labeller(hospital = as_labeller(hospital_names)))

For renaming two facets using the vector-based approach (as in naught101's answer), you can do:

facet_grid( hospital ~ room, labeller = labeller(hospital = as_labeller(hospital_names),
                                                 room = as_labeller(room_names)))

google-services.json for different productFlavors

Hey Friends also looks for name use only lowercase then u don't get this error

Spring: How to get parameters from POST body?

You can bind the json to a POJO using MappingJacksonHttpMessageConverter . Thus your controller signature can read :-

  public ResponseEntity<Boolean> saveData(@RequestBody RequestDTO req) 

Where RequestDTO needs to be a bean appropriately annotated to work with jackson serializing/deserializing. Your *-servlet.xml file should have the Jackson message converter registered in RequestMappingHandler as follows :-

  <list >
    <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>

  </list>
</property>
</bean>

Draggable div without jQuery UI

here's another way of making a draggable object that is centered to the click

http://jsfiddle.net/pixelass/fDcZS/

function endMove() {
    $(this).removeClass('movable');
}

function startMove() {
    $('.movable').on('mousemove', function(event) {
        var thisX = event.pageX - $(this).width() / 2,
            thisY = event.pageY - $(this).height() / 2;

        $('.movable').offset({
            left: thisX,
            top: thisY
        });
    });
}
$(document).ready(function() {
    $("#containerDiv").on('mousedown', function() {
        $(this).addClass('movable');
        startMove();
    }).on('mouseup', function() {
        $(this).removeClass('movable');
        endMove();
    });

});

CSS

#containerDiv {
    background:#333;
    position:absolute;
    width:200px;
    height:100px;
}

To get total number of columns in a table in sql

Correction to top query above, to allow to run from any database

SELECT COUNT(COLUMN_NAME) FROM [*database*].INFORMATION_SCHEMA.COLUMNS WHERE 
TABLE_CATALOG = 'database' AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'table'

How to get the sign, mantissa and exponent of a floating point number

On Linux package glibc-headers provides header #include <ieee754.h> with floating point types definitions, e.g.:

union ieee754_double
  {
    double d;

    /* This is the IEEE 754 double-precision format.  */
    struct
      {
#if __BYTE_ORDER == __BIG_ENDIAN
    unsigned int negative:1;
    unsigned int exponent:11;
    /* Together these comprise the mantissa.  */
    unsigned int mantissa0:20;
    unsigned int mantissa1:32;
#endif              /* Big endian.  */
#if __BYTE_ORDER == __LITTLE_ENDIAN
# if    __FLOAT_WORD_ORDER == __BIG_ENDIAN
    unsigned int mantissa0:20;
    unsigned int exponent:11;
    unsigned int negative:1;
    unsigned int mantissa1:32;
# else
    /* Together these comprise the mantissa.  */
    unsigned int mantissa1:32;
    unsigned int mantissa0:20;
    unsigned int exponent:11;
    unsigned int negative:1;
# endif
#endif              /* Little endian.  */
      } ieee;

    /* This format makes it easier to see if a NaN is a signalling NaN.  */
    struct
      {
#if __BYTE_ORDER == __BIG_ENDIAN
    unsigned int negative:1;
    unsigned int exponent:11;
    unsigned int quiet_nan:1;
    /* Together these comprise the mantissa.  */
    unsigned int mantissa0:19;
    unsigned int mantissa1:32;
#else
# if    __FLOAT_WORD_ORDER == __BIG_ENDIAN
    unsigned int mantissa0:19;
    unsigned int quiet_nan:1;
    unsigned int exponent:11;
    unsigned int negative:1;
    unsigned int mantissa1:32;
# else
    /* Together these comprise the mantissa.  */
    unsigned int mantissa1:32;
    unsigned int mantissa0:19;
    unsigned int quiet_nan:1;
    unsigned int exponent:11;
    unsigned int negative:1;
# endif
#endif
      } ieee_nan;
  };

#define IEEE754_DOUBLE_BIAS 0x3ff /* Added to exponent.  */

How to get a list of installed android applications and pick one to run

I had a requirement to filter out the system apps which user do not really use(eg. "com.qualcomm.service", "update services", etc). Ultimately I added another condition to filter down the app list. I just checked whether the app has 'launcher intent'.

So, the resultant code looks like...

PackageManager pm = getPackageManager();
        List<ApplicationInfo> apps = pm.getInstalledApplications(PackageManager.GET_GIDS);

        for (ApplicationInfo app : apps) {
            if(pm.getLaunchIntentForPackage(app.packageName) != null) {
                // apps with launcher intent
                if((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
                    // updated system apps

                } else if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                    // system apps

                } else {
                    // user installed apps

                }
                appsList.add(app);
            }

        }