Programs & Examples On #Ektron

This tag refers to the Ektron CMS400.NET content management system.

Select from one table where not in another

Expanding on Sjoerd's anti-join, you can also use the easy to understand SELECT WHERE X NOT IN (SELECT) pattern.

SELECT pm.id FROM r2r.partmaster pm
WHERE pm.id NOT IN (SELECT pd.part_num FROM wpsapi4.product_details pd)

Note that you only need to use ` backticks on reserved words, names with spaces and such, not with normal column names.

On MySQL 5+ this kind of query runs pretty fast.
On MySQL 3/4 it's slow.

Make sure you have indexes on the fields in question
You need to have an index on pm.id, pd.part_num.

C++ queue - simple example

Simply declare it as below if you want to us the STL queue container.

std::queue<myclass*> my_queue;

how to remove the first two columns in a file using shell (awk, sed, whatever)

Thanks for posting the question. I'd also like to add the script that helped me.

awk '{ $1=""; print $0 }' file

Disable output buffering

You can create an unbuffered file and assign this file to sys.stdout.

import sys 
myFile= open( "a.log", "w", 0 ) 
sys.stdout= myFile

You can't magically change the system-supplied stdout; since it's supplied to your python program by the OS.

How do you Programmatically Download a Webpage in Java

Jetty has an HTTP client which can be use to download a web page.

package com.zetcode;

import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;

public class ReadWebPageEx5 {

    public static void main(String[] args) throws Exception {

        HttpClient client = null;

        try {

            client = new HttpClient();
            client.start();

            String url = "http://www.something.com";

            ContentResponse res = client.GET(url);

            System.out.println(res.getContentAsString());

        } finally {

            if (client != null) {

                client.stop();
            }
        }
    }
}

The example prints the contents of a simple web page.

In a Reading a web page in Java tutorial I have written six examples of dowloading a web page programmaticaly in Java using URL, JSoup, HtmlCleaner, Apache HttpClient, Jetty HttpClient, and HtmlUnit.

How to select the comparison of two columns as one column in Oracle

I stopped using DECODE several years ago because it is non-portable. Also, it is less flexible and less readable than a CASE/WHEN.

However, there is one neat "trick" you can do with decode because of how it deals with NULL. In decode, NULL is equal to NULL. That can be exploited to tell whether two columns are different as below.

select a, b, decode(a, b, 'true', 'false') as same
  from t;

     A       B  SAME
------  ------  -----
     1       1  true
     1       0  false
     1          false
  null    null  true  

ValueError when checking if variable is None or numpy.array

To stick to == without consideration of the other type, the following is also possible.
type(a) == type(None)

Group list by values

I don't know about elegant, but it's certainly doable:

oldlist = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
# change into: list = [["A", "C"], ["B"], ["D", "E"]]

order=[]
dic=dict()
for value,key in oldlist:
  try:
    dic[key].append(value)
  except KeyError:
    order.append(key)
    dic[key]=[value]
newlist=map(dic.get, order)

print newlist

This preserves the order of the first occurence of each key, as well as the order of items for each key. It requires the key to be hashable, but does not otherwise assign meaning to it.

Difference between JPanel, JFrame, JComponent, and JApplet

JFrame and JApplet are top level containers. If you wish to create a desktop application, you will use JFrame and if you plan to host your application in browser you will use JApplet.

JComponent is an abstract class for all Swing components and you can use it as the base class for your new component. JPanel is a simple usable component you can use for almost anything.

Since this is for a fun project, the simplest way for you is to work with JPanel and then host it inside JFrame or JApplet. Netbeans has a visual designer for Swing with simple examples.

Difference between Encapsulation and Abstraction

A very practical example is.

let's just say I want to encrypt my password.

  • I don't want to know the details, I just call encryptionImpl.encrypt(password) and it returns an encrypted password.

    public interface Encryption{ public String encrypt(String password); }

    This is called abstraction. It just shows what should be done.

  • Now let us assume We have Two types of Encryption Md5 and RSA which implement Encryption from a third-party encryption jar.

    Then those Encryption classes have their own way of implementing encryption which protects their implementation from outsiders

    This is called Encapsulation. Hides how it should be done.

Remember:what should be done vs how it should be done.

Hiding complications vs Protecting implementations

How to "pull" from a local branch into another one?

What you are looking for is merging.

git merge master

With pull you fetch changes from a remote repository and merge them into the current branch.

Cannot add or update a child row: a foreign key constraint fails

Delete indexes of the UserID field of table2. Its suits for me

How to get the parents of a Python class?

The FASTEST way, to see all parents, and IN ORDER, just use the built in __mro__

i.e. repr(YOUR_CLASS.__mro__)


>>>
>>>
>>> import getpass
>>> getpass.GetPassWarning.__mro__

outputs, IN ORDER


(<class 'getpass.GetPassWarning'>, <type 'exceptions.UserWarning'>,
<type 'exceptions.Warning'>, <type 'exceptions.Exception'>, 
<type 'exceptions.BaseException'>, <type 'object'>)
>>>

There you have it. The "best" answer right now, has 182 votes (as I am typing this) but this is SO much simpler than some convoluted for loop, looking into bases one class at a time, not to mention when a class extends TWO or more parent classes. Importing and using inspect just clouds the scope unnecessarily. It honestly is a shame people don't know to just use the built-ins

I Hope this Helps!

How can I create tests in Android Studio?

Android Studio keeps evolving so the responses above will eventually be no longer applicable. For the current version of Android Studio 1.2.1.1, there's a nice tutorial on testing at:

http://evgenii.com/blog/testing-activity-in-android-studio-tutorial-part-1/

min and max value of data type in C

#include<stdio.h>

int main(void)
{
    printf("Minimum Signed Char %d\n",-(char)((unsigned char) ~0 >> 1) - 1);
    printf("Maximum Signed Char %d\n",(char) ((unsigned char) ~0 >> 1));

    printf("Minimum Signed Short %d\n",-(short)((unsigned short)~0 >>1) -1);
    printf("Maximum Signed Short %d\n",(short)((unsigned short)~0 >> 1));

    printf("Minimum Signed Int %d\n",-(int)((unsigned int)~0 >> 1) -1);
    printf("Maximum Signed Int %d\n",(int)((unsigned int)~0 >> 1));

    printf("Minimum Signed Long %ld\n",-(long)((unsigned long)~0 >>1) -1);
    printf("Maximum signed Long %ld\n",(long)((unsigned long)~0 >> 1));

    /* Unsigned Maximum Values */

    printf("Maximum Unsigned Char %d\n",(unsigned char)~0);
    printf("Maximum Unsigned Short %d\n",(unsigned short)~0);
    printf("Maximum Unsigned Int %u\n",(unsigned int)~0);
    printf("Maximum Unsigned Long %lu\n",(unsigned long)~0);

    return 0;
}

Powershell: Get FQDN Hostname

How about this

$FQDN=[System.Net.Dns]::GetHostByName($VM).Hostname.Split('.')
[int]$i = 1
[int]$x = 0
[string]$Domain = $null
do {
    $x = $i-$FQDN.Count
    $Domain = $Domain+$FQDN[$x]+"."
    $i = $i + 1
} until ( $i -eq $FQDN.Count )
$Domain = $Domain.TrimEnd(".")

How to increase time in web.config for executing sql query

You should add the httpRuntime block and deal with executionTimeout (in seconds).

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
...
 <system.web>
   <httpRuntime executionTimeout="90" maxRequestLength="4096"
    useFullyQualifiedRedirectUrl="false"
    minFreeThreads="8"
    minLocalRequestFreeThreads="4"
    appRequestQueueLimit="100" />
 </system.web>
... 
</configuration>

For more information, please, see msdn page.

GCD to perform task in main thread

No, you do not need to check whether you’re already on the main thread. By dispatching the block to the main queue, you’re just scheduling the block to be executed serially on the main thread, which happens when the corresponding run loop is run.

If you already are on the main thread, the behaviour is the same: the block is scheduled, and executed when the run loop of the main thread is run.

IO Error: The Network Adapter could not establish the connection

I figured out that in my case, my database was in different subnet than the subnet from where i was trying to access the db.

Numpy: Get random set of rows from 2D array

An alternative way of doing it is by using the choice method of the Generator class, https://github.com/numpy/numpy/issues/10835

import numpy as np

# generate the random array
A = np.random.randint(5, size=(10,3))

# use the choice method of the Generator class
rng = np.random.default_rng()
A_sampled = rng.choice(A, 2)

leading to a sampled data,

array([[1, 3, 2],
       [1, 2, 1]])

The running time is also profiled compared as follows,

%timeit rng.choice(A, 2)
15.1 µs ± 115 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit np.random.permutation(A)[:2]
4.22 µs ± 83.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit A[np.random.randint(A.shape[0], size=2), :]
10.6 µs ± 418 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

But when the array goes big, A = np.random.randint(10, size=(1000,300)). working on the index is the best way.

%timeit A[np.random.randint(A.shape[0], size=50), :]
17.6 µs ± 657 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit rng.choice(A, 50)
22.3 µs ± 134 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit np.random.permutation(A)[:50]
143 µs ± 1.33 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

So the permutation method seems to be the most efficient one when your array is small while working on the index is the optimal solution when your array goes big.

Is optimisation level -O3 dangerous in g++?

-O3 option turns on more expensive optimizations, such as function inlining, in addition to all the optimizations of the lower levels ‘-O2’ and ‘-O1’. The ‘-O3’ optimization level may increase the speed of the resulting executable, but can also increase its size. Under some circumstances where these optimizations are not favorable, this option might actually make a program slower.

Log4j: How to configure simplest possible file logging?

I have one generic log4j.xml file for you:

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration debug="false">

    <appender name="default.console" class="org.apache.log4j.ConsoleAppender">
        <param name="target" value="System.out" />
        <param name="threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
        </layout>
    </appender>

    <appender name="default.file" class="org.apache.log4j.FileAppender">
        <param name="file" value="/log/mylogfile.log" />
        <param name="append" value="false" />
        <param name="threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
        </layout>
    </appender>

    <appender name="another.file" class="org.apache.log4j.FileAppender">
        <param name="file" value="/log/anotherlogfile.log" />
        <param name="append" value="false" />
        <param name="threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
        </layout>
    </appender>

    <logger name="com.yourcompany.SomeClass" additivity="false">
        <level value="debug" />
        <appender-ref ref="another.file" />
    </logger>

    <root>
        <priority value="info" />
        <appender-ref ref="default.console" />
        <appender-ref ref="default.file" />
    </root>
</log4j:configuration>

with one console, two file appender and one logger poiting to the second file appender instead of the first.

EDIT

In one of the older projects I have found a simple log4j.properties file:

# For the general syntax of property based configuration files see
# the documentation of org.apache.log4j.PropertyConfigurator.

# The root category uses two appenders: default.out and default.file.
# The first one gathers all log output, the latter only starting with 
# the priority INFO.
# The root priority is DEBUG, so that all classes can be logged unless 
# defined otherwise in more specific properties.
log4j.rootLogger=DEBUG, default.out, default.file

# System.out.println appender for all classes
log4j.appender.default.out=org.apache.log4j.ConsoleAppender
log4j.appender.default.out.threshold=DEBUG
log4j.appender.default.out.layout=org.apache.log4j.PatternLayout
log4j.appender.default.out.layout.ConversionPattern=%-5p %c: %m%n

log4j.appender.default.file=org.apache.log4j.FileAppender
log4j.appender.default.file.append=true
log4j.appender.default.file.file=/log/mylogfile.log
log4j.appender.default.file.threshold=INFO
log4j.appender.default.file.layout=org.apache.log4j.PatternLayout
log4j.appender.default.file.layout.ConversionPattern=%-5p %c: %m%n

For the description of all the layout arguments look here: log4j PatternLayout arguments

Difference between static class and singleton pattern?

The Singleton pattern has several advantages over static classes. First, a singleton can extend classes and implement interfaces, while a static class cannot (it can extend classes, but it does not inherit their instance members). A singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded, leading to potential class loader issues. However the most important advantage, though, is that singletons can be handled polymorphically without forcing their users to assume that there is only one instance.

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

Loop through an array in JavaScript

For example, I used in a Firefox console:

[].forEach.call(document.getElementsByTagName('pre'), function(e){ 
   console.log(e);
})

You can use querySelectorAll to get same result

_x000D_
_x000D_
document.querySelectorAll('pre').forEach( (e) => { 
   console.log(e.textContent);
})
_x000D_
<pre>text 1</pre>
<pre>text 2</pre>
<pre>text 3</pre>
_x000D_
_x000D_
_x000D_

Configure Nginx with proxy_pass

Give this a try...

server {
    listen   80;
    server_name  dev.int.com;
    access_log off;
    location / {
        proxy_pass http://IP:8080;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:8080/jira  /;
        proxy_connect_timeout 300;
    }

    location ~ ^/stash {
        proxy_pass http://IP:7990;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:7990/  /stash;
        proxy_connect_timeout 300;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/local/nginx/html;
    }
}

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

Suppose you are usin Jersey 2.25.1, this worked for me - I am using Apache Tomcat web container:

    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>2.25.1</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
        <version>2.25.1</version>
    </dependency>

NB: Replace version with the version you are using

Add an incremental number in a field in INSERT INTO SELECT query in SQL Server

You can use the row_number() function for this.

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

If you want to start with the maximum already in the table then do:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

Finally, you can just make the sequence column an auto-incrementing identity column. This saves the need to increment it each time:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .
)

How to close current tab in a browser window?

As far as I can tell, it no longer is possible in Chrome or FireFox. It may still be possible in IE (at least pre-Edge).

Passing data to components in vue.js

I think the issue is here:

<template id="newtemp" :name ="{{user.name}}">

When you prefix the prop with : you are indicating to Vue that it is a variable, not a string. So you don't need the {{}} around user.name. Try:

<template id="newtemp" :name ="user.name">

EDIT-----

The above is true, but the bigger issue here is that when you change the URL and go to a new route, the original component disappears. In order to have the second component edit the parent data, the second component would need to be a child component of the first one, or just a part of the same component.

When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

To make it just show up in your JSP pages, you can use the Spring Security Tag Lib:

http://static.springsource.org/spring-security/site/docs/3.0.x/reference/taglibs.html

To use any of the tags, you must have the security taglib declared in your JSP:

<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>

Then in a jsp page do something like this:

<security:authorize access="isAuthenticated()">
    logged in as <security:authentication property="principal.username" /> 
</security:authorize>

<security:authorize access="! isAuthenticated()">
    not logged in
</security:authorize>

NOTE: As mentioned in the comments by @SBerg413, you'll need to add

use-expressions="true"

to the "http" tag in the security.xml config for this to work.

Get final URL after curl is redirected

You could use grep. doesn't wget tell you where it's redirecting too? Just grep that out.

How do I switch between command and insert mode in Vim?

Looks like your Vim is launched in easy mode. See :help easy.

This happens when Vim is invoked with the -y argument or as evim, or maybe you have a :set insertmode somewhere in your .vimrc configuration. Find the source and disable it; temporarily this can be also done via Ctrl + O :set noim Enter.

How can I debug a Perl script?

I would also recommend using the Perl debugger.

However, since you asked about something like shell's -x have a look at the Devel::Trace module which does something similar.

Remove large .pack file created by git

Run the following command, replacing PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA with the path to the file you want to remove, not just its filename. These arguments will:

  1. Force Git to process, but not check out, the entire history of every branch and tag
  2. Remove the specified file, as well as any empty commits generated as a result
  3. Overwrite your existing tags
git filter-branch --force --index-filter "git rm --cached --ignore-unmatch PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA" --prune-empty --tag-name-filter cat -- --all

This will forcefully remove all references to the files from the active history of the repo.

Next step, to perform a GC cycle to force all references to the file to be expired and purged from the pack file. Nothing needs to be replaced in these commands.

git update-ref -d refs/original/refs/remotes/origin/master
git for-each-ref --format='delete %(refname)' refs/original | git update-ref --stdin
git reflog expire --expire=now --all
git gc --aggressive --prune=now

Detecting when user scrolls to bottom of div with jQuery

I found a solution that when you scroll your window and end of a div shown from bottom gives you an alert.

$(window).bind('scroll', function() {
    if($(window).scrollTop() >= $('.posts').offset().top + $('.posts').outerHeight() - window.innerHeight) {
        alert('end reached');
    }
});

In this example if you scroll down when div (.posts) finish its give you an alert.

Execute JavaScript code stored as a string

For users that are using node and that are concerned with the context implications of eval() nodejs offers vm. It creates a V8 virtual machine that can sandbox the execution of your code in a separate context.

Taking things a step further is vm2 which hardens vm allowing the vm to run untrusted code.

const vm = require('vm');

const x = 1;

const sandbox = { x: 2 };
vm.createContext(sandbox); // Contextify the sandbox.

const code = 'x += 40; var y = 17;';
// `x` and `y` are global variables in the sandboxed environment.
// Initially, x has the value 2 because that is the value of sandbox.x.
vm.runInContext(code, sandbox);

console.log(sandbox.x); // 42
console.log(sandbox.y); // 17

console.log(x); // 1; y is not defined.

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

npm install -g increase-memory-limit

increase-memory-limit

OR

  1. Navigate to %appdata% -> npm folder or C:\Users\{user_name}\AppData\Roaming\npm
  2. Open ng.cmd in your favorite editor
  3. Add --max_old_space_size=8192 to the IF and ELSE block

now ng.cmd file looks like this after the change:

@IF EXIST "%~dp0\node.exe" (
  "%~dp0\node.exe" "--max_old_space_size=8192" "%~dp0\node_modules\@angular\cli\bin\ng" %*
) ELSE (
  @SETLOCAL
  @SET PATHEXT=%PATHEXT:;.JS;=;%
  node "--max_old_space_size=8192" "%~dp0\node_modules\@angular\cli\bin\ng" %*
)

How to listen for a WebView finishing loading a URL?

Just to show progress bar, "onPageStarted" and "onPageFinished" methods are enough; but if you want to have an "is_loading" flag (along with page redirects, ...), this methods may executed with non-sequencing, like "onPageStarted > onPageStarted > onPageFinished > onPageFinished" queue.

But with my short test (test it yourself.), "onProgressChanged" method values queue is "0-100 > 0-100 > 0-100 > ..."

private boolean is_loading = false;

webView.setWebChromeClient(new MyWebChromeClient(context));

private final class MyWebChromeClient extends WebChromeClient{
    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        if (newProgress == 0){
            is_loading = true;
        } else if (newProgress == 100){
            is_loading = false;
        }
        super.onProgressChanged(view, newProgress);
    }
}

Also set "is_loading = false" on activity close, if it is a static variable because activity can be finished before page finish.

The operation couldn’t be completed. (com.facebook.sdk error 2.) ios6

Another potential cause for this error: Attempting to get permission for a Facebook app in sandbox mode when the Facebook user is not listed in the app's admins, developers or testers.

How to make Unicode charset in cmd.exe by default?

Save the following into a file with ".reg" suffix:

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Console\%SystemRoot%_system32_cmd.exe]
"CodePage"=dword:0000fde9

Double click this file, and regedit will import it.

It basically sets the key HKEY_CURRENT_USER\Console\%SystemRoot%_system32_cmd.exe\CodePage to 0xfde9 (65001 in decimal system).

Returning JSON object from an ASP.NET page

no problem doing it with asp.... it's most natural to do so with MVC, but can be done with standard asp as well.

The MVC framework has all sorts of helper classes for JSON, if you can, I'd suggest sussing in some MVC-love, if not, you can probably easily just get the JSON helper classes used by MVC in and use them in the context of asp.net.

edit:

here's an example of how to return JSON data with MVC. This would be in your controller class. This is out of the box functionality with MVC--when you crate a new MVC project this stuff gets auto-created so it's nothing special. The only thing that I"m doing is returning an actionResult that is JSON. The JSON method I'm calling is a method on the Controller class. This is all very basic, default MVC stuff:

public ActionResult GetData()
{
    var data = new { Name="kevin", Age=40 };
    return Json(data, JsonRequestBehavior.AllowGet);
}

This return data could be called via JQuery as an ajax call thusly:

$.get("/Reader/GetData/", function(data) { someJavacriptMethodOnData(data); });

Adding onClick event dynamically using jQuery

Try below approach,

$('#bfCaptchaEntry').on('click', myfunction);

or in case jQuery is not an absolute necessaity then try below,

document.getElementById('bfCaptchaEntry').onclick = myfunction;

However the above method has few drawbacks as it set onclick as a property rather than being registered as handler...

Read more on this post https://stackoverflow.com/a/6348597/297641

Display an image into windows forms

private void Form1_Load(object sender, EventArgs e)
    {
        PictureBox pb = new PictureBox();
        pb.Location = new Point(0, 0);
        pb.Size = new Size(150, 150);
        pb.Image = Image.FromFile("E:\\Wallpaper (204).jpg");
        pb.Visible = true;
        this.Controls.Add(pb);
    }

Mongoose delete array element in document and save

This is working for me and really very helpful.

SubCategory.update({ _id: { $in:
        arrOfSubCategory.map(function (obj) {
            return mongoose.Types.ObjectId(obj);
        })
    } },
    {
        $pull: {
            coupon: couponId,
        }
    }, { multi: true }, function (err, numberAffected) {
        if(err) {
            return callback({
                error:err
            })
        }
    })
});

I have a model which name is SubCategory and I want to remove Coupon from this category Array. I have an array of categories so I have used arrOfSubCategory. So I fetch each array of object from this array with map function with the help of $in operator.

How to set the timezone in Django?

Here is the list of valid timezones:

http://en.wikipedia.org/wiki/List_of_tz_database_time_zones

You can use

TIME_ZONE = 'Europe/Istanbul'

for UTC+02:00

How would you implement an LRU cache in Java?

I would consider using java.util.concurrent.PriorityBlockingQueue, with priority determined by a "numberOfUses" counter in each element. I would be very, very careful to get all my synchronisation correct, as the "numberOfUses" counter implies that the element can't be immutable.

The element object would be a wrapper for the objects in the cache:

class CacheElement {
    private final Object obj;
    private int numberOfUsers = 0;

    CacheElement(Object obj) {
        this.obj = obj;
    }

    ... etc.
}

How to restrict user to type 10 digit numbers in input element?

This is what I use:

<input type="tel" name="phoneNumber" id="phoneNumber" title="Please use a 10 digit telephone number with no dashes or dots" pattern="[0-9]{10}" required /> <i>10 digits</i>

It clarifies exactly what is expected in the entry and gives usable error messages.

ORA-12560: TNS:protocol adaptor error

ORA-12560: TNS:erro de adaptador de protocolo

  1. set Environment Variables: ORACLE_BASE, ORACLE_HOME, ORACLE_SID
  2. make sure your user is part of ORACLE_GROUP_NAME (Windows)
  3. make sure the file ORACLE_HOME/network/admin/sqlnet.ora is: SQLNET.AUTHENTICATION_SERVICES = (NTS)
  4. (Windows) Be carefull when you add a new Oracle client: adding a new path to the PATH env. variable can mess things up. The first entry in this variable makes a difference: certify that the sqlplus executable in the ORACLE_HOME (ORACLE_HOME/bin) comes first in the PATH env. variable.

PHP calculate age

Ready to use function that returns full result (year, month, day, hour, min, sec). Regarding date above current date, it will return negative values that can be useful for countdown function.

/* By default,
* format is 'us'
* and delimiter is '-'
*/

function date_calculate($input_date, $format = 'us', $delimiter = '-')
{
    switch (strtolower($format)) {
        case 'us': // date in 'us' format (yyyy/mm/dd), like '1994/03/01'
            list($y, $m, $d) = explode($delimiter, $input_date);
            break;
        case 'fr': // date in 'fr' format (dd/mm/yyyy), like '01/03/1994'
            list($d, $m, $y) = explode($delimiter, $input_date);
            break;
        default: return null;
    }

    $tz          = new \DateTimeZone('UTC'); // TimeZone. Not required but can be useful. By default, server TimeZone will be returned
    $format_date = sprintf('%s-%s-%s', $y, $m, $d);
    $cur_date    = new \DateTime(null, $tz);
    $user_date   = new \DateTime($format_date, $tz);
    $interval    = $user_date->diff($cur_date);

    return [
        'year'  => $interval->format('%r%y'),
        'month' => $interval->format('%r%m'),
        'day'   => $interval->format('%r%d'),
        'hour'  => $interval->format('%r%H'),
        'min'   => $interval->format('%r%i'),
        'sec'   => $interval->format('%r%s'),
    ];
}

var_dump(date_calculate('06/09/2016', 'fr', '/'));
var_dump(date_calculate('2016-09-06'));

More++:

Detect if PHP session exists

If you are on php 5.4+, it is cleaner to use session_status():

if (session_status() == PHP_SESSION_ACTIVE) {
  echo 'Session is active';
}
  • PHP_SESSION_DISABLED if sessions are disabled.
  • PHP_SESSION_NONE if sessions are enabled, but none exists.
  • PHP_SESSION_ACTIVE if sessions are enabled, and one exists.

Responsive css styles on mobile devices ONLY

I had to solve a similar problem--I wanted certain styles to only apply to mobile devices in landscape mode. Essentially the fonts and line spacing looked fine in every other context, so I just needed the one exception for mobile landscape. This media query worked perfectly:

@media all and (max-width: 600px) and (orientation:landscape) 
{
    /* styles here */
}

How to sign in kubernetes dashboard?

A self-explanatory simple one-liner to extract token for kubernetes dashboard login.

kubectl describe secret -n kube-system | grep deployment -A 12

Copy the token and paste it on the kubernetes dashboard under token sign in option and you are good to use kubernetes dashboard

Android Viewpager as Image Slide Gallery

Just use this https://gist.github.com/8cbe094bb7a783e37ad1 for make surrounding pages visible and http://viewpagerindicator.com/ this, for indicator. That's pretty cool, i'm using it for a gallery.

Remove spacing between table cells and rows

Nothing has worked. The solution for the issue is.

<style>
table td {
    padding: 0;
}
</style>

How can I remove the "No file chosen" tooltip from a file input in Chrome?

This is a tricky one. I could not find a way to select the 'no file chosen' element so I created a mask using the :after pseudo selector.

My solution also requires the use of the following pseudo selector to style the button:

::-webkit-file-upload-button

Try this: http://jsfiddle.net/J8Wfx/1/

FYI: This will only work in webkit browsers.

P.S if anyone knows how to view webkit pseudo selectors like the one above in the webkit inspector please let me know

Sequence contains no elements?

Well, what is ID here? In particular, is it a local variable? There are some scope / capture issues, which mean that it may be desirable to use a second variable copy, just for the query:

var id = ID;
BlogPost post = (from p in dc.BlogPosts
                 where p.BlogPostID == id
                 select p).Single();

Also; if this is LINQ-to-SQL, then in the current version you get a slightly better behaviour if you use the form:

var id = ID;
BlogPost post = dc.BlogPosts.Single(p => p.BlogPostID == id);

Android: TextView: Remove spacing and padding on top and bottom

I searched a lot for proper answer but no where I could find an Answer which could exactly remove all the padding from the TextView, but finally after going through the official doc got a work around for Single Line Texts

android:includeFontPadding="false"
android:lineSpacingExtra="0dp"

Adding these two lines to TextView xml will do the work.
First attribute removes the padding reserved for accents and second attribute removes the spacing reserved to maintain proper space between two lines of text.

Make sure not to add lineSpacingExtra="0dp" in multiline TextView as it might make the appearance clumsy

Tomcat request timeout

With Tomcat 7, you can add the StuckThreadDetectionValve which will enable you to identify threads that are "stuck". You can set-up the valve in the Context element of the applications where you want to do detecting:

<Context ...>
  ...
  <Valve 
    className="org.apache.catalina.valves.StuckThreadDetectionValve"
    threshold="60" />
  ...
</Context>

This would write a WARN entry into the tomcat log for any thread that takes longer than 60 seconds, which would enable you to identify the applications and ban them because they are faulty.

Based on the source code you may be able to write your own valve that attempts to stop the thread, however this would have knock on effects on the thread pool and there is no reliable way of stopping a thread in Java without the cooperation of that thread...

Achieving white opacity effect in html/css

Try RGBA, e.g.

div { background-color: rgba(255, 255, 255, 0.5); }

As always, this won't work in every single browser ever written.

Change form size at runtime in C#

You cannot change the Width and Height properties of the Form as they are readonly. You can change the form's size like this:

button1_Click(object sender, EventArgs e)
{
    // This will change the Form's Width and Height, respectively.
    this.Size = new Size(420, 200);
}

Where does Anaconda Python install on Windows?

Update May 2020, installed Anaconda 3 Individual Edition from https://www.anaconda.com/products/individual, chose 32-bit installer for Python 3.7, and installed with Default options.

enter image description here

Here is the directory where Anaconda was installed (C:\ProgramData\Anaconda3). Note ProgramData is a hidden folder not visible via Windows File Explorer. enter image description here

And launching Anaconda command prompt from Start Menu>>Anaconda3 gives below command shell

enter image description here

"where anaconda" command gives below output C:\ProgramData\Anaconda3\Scripts\anaconda.exe and versions for anaconda, conda, python enter image description here

Updated original question which was asked 3 years ago, and is relevant today as well in May 2020 as I had similar question/doubt when installing Anaconda recently.

Maximum on http header values?

If you are going to use any DDOS provider like Akamai, they have a maximum limitation of 8k in the response header size. So essentially try to limit your response header size below 8k.

How to match all occurrences of a regex

if you have a regexp with groups:

str="A 54mpl3 string w1th 7 numbers scatter3r ar0und"
re=/(\d+)[m-t]/

you can use String's scan method to find matching groups:

str.scan re
#> [["54"], ["1"], ["3"]]

To find the matching pattern:

str.to_enum(:scan,re).map {$&}
#> ["54m", "1t", "3r"]

jquery datatables default sort

This worked for me:

       jQuery('#tblPaging').dataTable({
            "sort": true,
            "pageLength": 20
        });

Execution order of events when pressing PrimeFaces p:commandButton

It failed because you used ajax="false". This fires a full synchronous request which in turn causes a full page reload, causing the oncomplete to be never fired (note that all other ajax-related attributes like process, onstart, onsuccess, onerror and update are also never fired).

That it worked when you removed actionListener is also impossible. It should have failed the same way. Perhaps you also removed ajax="false" along it without actually understanding what you were doing. Removing ajax="false" should indeed achieve the desired requirement.


Also is it possible to execute actionlistener and oncomplete simultaneously?

No. The script can only be fired before or after the action listener. You can use onclick to fire the script at the moment of the click. You can use onstart to fire the script at the moment the ajax request is about to be sent. But they will never exactly simultaneously be fired. The sequence is as follows:

  • User clicks button in client
  • onclick JavaScript code is executed
  • JavaScript prepares ajax request based on process and current HTML DOM tree
  • onstart JavaScript code is executed
  • JavaScript sends ajax request from client to server
  • JSF retrieves ajax request
  • JSF processes the request lifecycle on JSF component tree based on process
  • actionListener JSF backing bean method is executed
  • action JSF backing bean method is executed
  • JSF prepares ajax response based on update and current JSF component tree
  • JSF sends ajax response from server to client
  • JavaScript retrieves ajax response
    • if HTTP response status is 200, onsuccess JavaScript code is executed
    • else if HTTP response status is 500, onerror JavaScript code is executed
  • JavaScript performs update based on ajax response and current HTML DOM tree
  • oncomplete JavaScript code is executed

Note that the update is performed after actionListener, so if you were using onclick or onstart to show the dialog, then it may still show old content instead of updated content, which is poor for user experience. You'd then better use oncomplete instead to show the dialog. Also note that you'd better use action instead of actionListener when you intend to execute a business action.

See also:

<button> background image

try this way

<button> 
    <img height="100%" src="images/s.png"/>
</button>

ETag vs Header Expires

Expires and Cache-Control are "strong caching headers"

Last-Modified and ETag are "weak caching headers"

First the browser check Expires/Cache-Control to determine whether or not to make a request to the server

If have to make a request, it will send Last-Modified/ETag in the HTTP request. If the Etag value of the document matches that, the server will send a 304 code instead of 200, and no content. The browser will load the contents from its cache.

Javascript Thousand Separator / string format

You can use javascript. below are the code, it will only accept numeric and one dot

here is the javascript

<script >

            function FormatCurrency(ctrl) {
                //Check if arrow keys are pressed - we want to allow navigation around textbox using arrow keys
                if (event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40) {
                    return;
                }

                var val = ctrl.value;

                val = val.replace(/,/g, "")
                ctrl.value = "";
                val += '';
                x = val.split('.');
                x1 = x[0];
                x2 = x.length > 1 ? '.' + x[1] : '';

                var rgx = /(\d+)(\d{3})/;

                while (rgx.test(x1)) {
                    x1 = x1.replace(rgx, '$1' + ',' + '$2');
                }

                ctrl.value = x1 + x2;
            }

            function CheckNumeric() {
                return event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 46;
            }

  </script>

HTML

<input type="text" onkeypress="return CheckNumeric()" onkeyup="FormatCurrency(this)" />

DEMO JSFIDDLE

How to remove special characters from a string?

To Remove Special character

String t2 = "!@#$%^&*()-';,./?><+abdd";

t2 = t2.replaceAll("\\W+","");

Output will be : abdd.

This works perfectly.

Count(*) vs Count(1) - SQL Server

If you run the following in SQL Server, you'll notice that COUNT(1) is evaluated as COUNT(*) anyway. So it appears that there is no difference, and also that COUNT(*) is the expression most native to the query optimizer:

SET SHOWPLAN_TEXT ON
GO

SELECT COUNT(1)
FROM <table>
GO

SET SHOWPLAN_TEXT OFF
GO

How to delete parent element using jQuery

$('#' + catId).parent().remove('.subcatBtns');

How to remove item from array by value?

Check out this way:

delete this.arrayName[this.arrayName.indexOf(value)];

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

How to enable mbstring from php.ini?

All XAMPP packages come with Multibyte String (php_mbstring.dll) extension installed.

If you have accidentally removed DLL file from php/ext folder, just add it back (get the copy from XAMPP zip archive - its downloadable).

If you have deleted the accompanying INI configuration line from php.ini file, add it back as well:

extension=php_mbstring.dll

Also, ensure to restart your webserver (Apache) using XAMPP control panel.

Additional Info on Enabling PHP Extensions

  • install extension (e.g. put php_mbstring.dll into /XAMPP/php/ext directory)
  • in php.ini, ensure extension directory specified (e.g. extension_dir = "ext")
  • ensure correct build of DLL file (e.g. 32bit thread-safe VC9 only works with DLL files built using exact same tools and configuration: 32bit thread-safe VC9)
  • ensure PHP API versions match (If not, once you restart the webserver you will receive related error.)

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

("Jesse" or "jesse")

The above expression tests whether or not "Jesse" evaluates to True. If it does, then the expression will return it; otherwise, it will return "jesse". The expression is equivalent to writing:

"Jesse" if "Jesse" else "jesse"

Because "Jesse" is a non-empty string though, it will always evaluate to True and thus be returned:

>>> bool("Jesse")  # Non-empty strings evaluate to True in Python
True
>>> bool("")  # Empty strings evaluate to False
False
>>>
>>> ("Jesse" or "jesse")
'Jesse'
>>> ("" or "jesse")
'jesse'
>>>

This means that the expression:

name == ("Jesse" or "jesse")

is basically equivalent to writing this:

name == "Jesse"

In order to fix your problem, you can use the in operator:

# Test whether the value of name can be found in the tuple ("Jesse", "jesse")
if name in ("Jesse", "jesse"):

Or, you can lowercase the value of name with str.lower and then compare it to "jesse" directly:

# This will also handle inputs such as "JeSSe", "jESSE", "JESSE", etc.
if name.lower() == "jesse":

Javascript "Not a Constructor" Exception while creating objects

I've googled around also and found this solution:

You have a variable Project somewhere that is not a function. Then the new operator will complain about it. Try console.log(Project) at the place where you would have used it as a construcotr, and you will find it.

What's the difference between IFrame and Frame?

The only reasons I can think of are actually in the wiki article you referenced to mention a couple...

"The "Verified by Visa" system has drawn some criticism, since it is hard for users to differentiate between the legitimate Verified by Visa pop-up window or inline frame, and a fraudulent phishing site."

"as of 2008, most web browsers do not provide a simple way to check the security certificate for the contents of an iframe"

If you read the Criticism section in the article it details all the potential security flaws.

Otherwise the only difference is the fact that an IFrame is an inline frame and a Frame is part of a Frameset. Which means more layout problems than anything else!

Javascript ES6 export const vs export let

I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).

The only difference would be if you try to reassign it before the end of this very file.

what's the easiest way to put space between 2 side-by-side buttons in asp.net

I used &nbsp; and it is working fine. You could try it. You do not need to use the quotation marks

@Nullable annotation usage

Different tools may interpret the meaning of @Nullable differently. For example, the Checker Framework and FindBugs handle @Nullable differently.

Laravel $q->where() between dates

@Tom : Instead of using 'now' or 'addWeek' if we provide date in following format, it does not give correct records

$projects = Project::whereBetween('recur_at', array(new DateTime('2015-10-16'), new DateTime('2015-10-23')))
->where('status', '<', 5)
->where('recur_cancelled', '=', 0)
->get();

it gives records having date form 2015-10-16 to less than 2015-10-23. If value of recur_at is 2015-10-23 00:00:00 then only it shows that record else if it is 2015-10-23 12:00:45 then it is not shown.

How to remove stop words using nltk or python

Although the question is a bit old, here is a new library, which is worth mentioning, that can do extra tasks.

In some cases, you don't want only to remove stop words. Rather, you would want to find the stopwords in the text data and store it in a list so that you can find the noise in the data and make it more interactive.

The library is called 'textfeatures'. You can use it as follows:

! pip install textfeatures
import textfeatures as tf
import pandas as pd

For example, suppose you have the following set of strings:

texts = [
    "blue car and blue window",
    "black crow in the window",
    "i see my reflection in the window"]

df = pd.DataFrame(texts) # Convert to a dataframe
df.columns = ['text'] # give a name to the column
df

Now, call the stopwords() function and pass the parameters you want:

tf.stopwords(df,"text","stopwords") # extract stop words
df[["text","stopwords"]].head() # give names to columns

The result is going to be:

    text                                 stopwords
0   blue car and blue window             [and]
1   black crow in the window             [in, the]
2   i see my reflection in the window    [i, my, in, the]

As you can see, the last column has the stop words included in that docoument (record).

How to create tar.gz archive file in Windows?

tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.

If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.

ORA-01017 Invalid Username/Password when connecting to 11g database from 9i client

Credentials may be correct and something else wrong. I based my pluggable DB connection string on its container DB. Instead of the original parent.example.com service name the correct appeared to be pluggable.example.com.

How to delete the last row of data of a pandas dataframe

drop returns a new array so that is why it choked in the og post; I had a similar requirement to rename some column headers and deleted some rows due to an ill formed csv file converted to Dataframe, so after reading this post I used:

newList = pd.DataFrame(newList)
newList.columns = ['Area', 'Price']
print(newList)
# newList = newList.drop(0)
# newList = newList.drop(len(newList))
newList = newList[1:-1]
print(newList)

and it worked great, as you can see with the two commented out lines above I tried the drop.() method and it work but not as kool and readable as using [n:-n], hope that helps someone, thanks.

How to delete last character in a string in C#?

paramstr.Remove((paramstr.Length-1),1);

This does work to remove a single character from the end of a string. But if I use it to remove, say, 4 characters, this doesn't work:

paramstr.Remove((paramstr.Length-4),1);

As an alternative, I have used this approach instead:

DateFrom = DateFrom.Substring(0, DateFrom.Length-4);

Visual Studio Code pylint: Unable to import 'protorpc'

I had same problem for pyodbc , I had two version of python on my Ubuntu (python3.8 and python3.9), problem was: package installed on python3.8 location but my interpreter was for python3.9. i installed python3.8 interpreter in command palette and it fixed.

Unzip All Files In A Directory

Unzip all .zip files and store the content in a new folder with the same name and in the same folder as the .zip file:

find -name '*.zip' -exec sh -c 'unzip -d "${1%.*}" "$1"' _ {} \;

This is an extension of @phatmanace's answer and addresses @RishabhAgrahari's comment:

This will extract all the zip files in current directory, what if I want the zip files (present in subfolders) to be extracted in the respective subfolders ?

What are the most common font-sizes for H1-H6 tags

It would depend on the browser's default stylesheet. You can view an (unofficial) table of CSS2.1 User Agent stylesheet defaults here.

Based on the page listed above, the default sizes look something like this:

    IE7     IE8     FF2         FF3         Opera   Safari 3.1
H1  24pt    2em     32px        32px        32px    32px       
H2  18pt    1.5em   24px        24px        24px    24px
H3  13.55pt 1.17em  18.7333px   18.7167px   18px    19px
H4  n/a     n/a     n/a         n/a         n/a     n/a
H5  10pt    0.83em  13.2667px   13.2833px   13px    13px
H6  7.55pt  0.67em  10.7333px   10.7167px   10px    11px

Also worth taking a look at is the default stylesheet for HTML 4. The W3C recommends using these styles as the default. An abridged excerpt:

h1 { font-size: 2em; }
h2 { font-size: 1.5em; }
h3 { font-size: 1.17em; }
h4 { font-size: 1.12em; }
h5 { font-size: .83em; }
h6 { font-size: .75em; }

Hope this information is helpful.

HttpServletRequest get JSON POST data

Normaly you can GET and POST parameters in a servlet the same way:

request.getParameter("cmd");

But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.

If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:

BufferedReader reader = request.getReader();

Json post processing example (uses org.json package )

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

  StringBuffer jb = new StringBuffer();
  String line = null;
  try {
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
      jb.append(line);
  } catch (Exception e) { /*report an error*/ }

  try {
    JSONObject jsonObject =  HTTP.toJSONObject(jb.toString());
  } catch (JSONException e) {
    // crash and burn
    throw new IOException("Error parsing JSON request string");
  }

  // Work with the data using methods like...
  // int someInt = jsonObject.getInt("intParamName");
  // String someString = jsonObject.getString("stringParamName");
  // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
  // JSONArray arr = jsonObject.getJSONArray("arrayParamName");
  // etc...
}

How can I change the app display name build with Flutter?

For Android, change the app name from the Android folder. In the AndroidManifest.xml file, in folder android/app/src/main, let the android label refer to the name you prefer, for example,

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    <application
        `android:label="myappname"`
        // The rest of the code
    </application>
</manifest>

Django: OperationalError No Such Table

Running the following commands solved this for me 1. python manage.py migrate 2. python manage.py makemigrations 3. python manage.py makemigrations appName

Unable to resolve "unable to get local issuer certificate" using git on Windows with self-signed certificate

I had this issue as well. In my case, I was trying to get a post-receive Git hook to update a working copy on a server with each push. Tried to follow the instructions in the blog you linked to. Didn't work for me as well and overriding the settings on a per-user basis didn't seem to work either.

What I ended up having to do was disable SSL verification (as the article mentions) for Git as a whole. Not the perfect solution, but it'll work until I can figure out a better one.

I edited the Git config text file (with my favorite line-ending neutral app like Notepad++) located at:

C:\Program Files (x86)\Git\etc\gitconfig

In the [http] block, I added an option to disable sslVerify. It looked like this when I was done:

[http]
    sslVerify = false
    sslCAinfo = /bin/curl-ca-bundle.crt

That did the trick.

NOTE:

  • This disables SSL verification and is not recommended as a long term solution.

  • You can disable this per-repository which still isn't great, but localizes the setting.

  • With the advent of LetsEncrypt.org, it is now fairly simple, automated and free to set up SSL as an alternative to self-signed certs and negates the need to turn off sslVerify.

How to atomically delete keys matching a pattern using Redis

FYI.

  • only using bash and redis-cli
  • not using keys (this uses scan)
  • works well in cluster mode
  • not atomic

Maybe you only need to modify capital characters.

scan-match.sh

#!/bin/bash
rcli="/YOUR_PATH/redis-cli" 
default_server="YOUR_SERVER"
default_port="YOUR_PORT"
servers=`$rcli -h $default_server -p $default_port cluster nodes | grep master | awk '{print $2}' | sed 's/:.*//'`
if [ x"$1" == "x" ]; then 
    startswith="DEFAULT_PATTERN"
else
    startswith="$1"
fi
MAX_BUFFER_SIZE=1000
for server in $servers; do 
    cursor=0
    while 
        r=`$rcli -h $server -p $default_port scan $cursor match "$startswith*" count $MAX_BUFFER_SIZE `
        cursor=`echo $r | cut -f 1 -d' '`
        nf=`echo $r | awk '{print NF}'`
        if [ $nf -gt 1 ]; then
            for x in `echo $r | cut -f 1 -d' ' --complement`; do 
                echo $x
            done
        fi
        (( cursor != 0 ))
    do
        :
    done
done

clear-redis-key.sh

#!/bin/bash
STARTSWITH="$1"

RCLI=YOUR_PATH/redis-cli
HOST=YOUR_HOST
PORT=6379
RCMD="$RCLI -h $HOST -p $PORT -c "

./scan-match.sh $STARTSWITH | while read -r KEY ; do
    $RCMD del $KEY 
done

Run at bash prompt

$ ./clear-redis-key.sh key_head_pattern

How to determine day of week by passing specific date?

Calendar cal = Calendar.getInstance(desired date);
cal.setTimeInMillis(System.currentTimeMillis());
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);

Get the day value by providing the current time stamp.

How to make a <ul> display in a horizontal row

#ul_top_hypers li {
  display: flex;
}

Get program execution time in the shell

Should you want more precision, use %N with date (and use bc for the diff, because $(()) only handles integers).

Here's how to do it:

start=$(date +%s.%N)
# do some stuff here
dur=$(echo "$(date +%s.%N) - $start" | bc)

printf "Execution time: %.6f seconds" $dur

Example:

start=$(date +%s.%N); \
  sleep 0.1s; \
  dur=$(echo "$(date +%s.%N) - $start" | bc); \
  printf "Execution time: %.6f seconds\n" $dur

Result:

Execution time: 0.104623 seconds

Laravel Escaping All HTML in Blade Template

{{html_entity_decode ($post->content())}} saved the issue for me with Laravel 4.0. Now My HTML content is interpreted as it should.

Can a CSS class inherit one or more other classes?

You can add multiple classes to a single DOM element, e.g.

<div class="firstClass secondClass thirdclass fourthclass"></div>

Rules given in later classes (or which are more specific) override. So the fourthclass in that example kind of prevails.

Inheritance is not part of the CSS standard.

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

FIX FOR OSX EL CAPITAN

I'm still on OSX 10.11.6 with XCode 8.2.1 ... will upgrade someday but not today. I was able to get past the :CFBundleIdentifier error by downgrading react native to 52.0

yarn upgrade [email protected]

Got me a successful build on the simulator. Cheers!

How do I get the list of keys in a Dictionary?

I often used this to get the key and value inside a dictionary: (VB.Net)

 For Each kv As KeyValuePair(Of String, Integer) In layerList

 Next

(layerList is of type Dictionary(Of String, Integer))

How to Convert Boolean to String

function ToStr($Val=null,$T=0){

    return is_string($Val)?"$Val"
    :
    (
        is_numeric($Val)?($T?"$Val":$Val)
        :
        (
            is_null($Val)?"NULL"
            :
            (
                is_bool($Val)?($Val?"TRUE":"FALSE")
                :
                (
                    is_array($Val)?@StrArr($Val,$T)
                    :
                    false
                )
            )
        )
    );

}
function StrArr($Arr,$T=0)
{
    $Str="";
    $i=-1;
    if(is_array($Arr))
    foreach($Arr AS $K => $V)
    $Str.=((++$i)?", ":null).(is_string($K)?"\"$K\"":$K)." => ".(is_string($V)?"\"$V\"":@ToStr($V,$T+1));
    return "array( ".($i?@ToStr($Arr):$Str)." )".($T?null:";");
}

$A = array(1,2,array('a'=>'b'),array('a','b','c'),true,false,ToStr(100));
echo StrArr($A); // OR ToStr($A) // OR ToStr(true) // OR StrArr(true)

Angular.js vs Knockout.js vs Backbone.js

It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.

Are you doing heavy DOM manipulation? I would use jQuery and Backbone.

Very data driven app? Angular with its nice data binding.

Game programming? None - direct to canvas; maybe a game engine.

How to convert a file into a dictionary?

I had a requirement to take values from text file and use as key value pair. i have content in text file as key = value, so i have used split method with separator as "=" and wrote below code

d = {}
file = open("filename.txt")
for x in file:
    f = x.split("=")
    d.update({f[0].strip(): f[1].strip()})

By using strip method any spaces before or after the "=" separator are removed and you will have the expected data in dictionary format

get selected value in datePicker and format it

If you want to take the formatted value of input do this :

$("input").datepicker({ dateFormat: 'dd, mm, yy' });

later in your code when the date is set you could get it by

dateVariable = $("input").val();

If you want just to take a formatted value with datepicker you might want to use the utility

dateString = $.datepicker.formatDate('dd, MM, yy', new Date("20 April 2012"));

I've updated the jsfiddle for experimenting with this

Label on the left side instead above an input field

You can see from the existing answers that Bootstrap's terminology is confusing. If you look at the bootstrap documentation, you see that the class form-horizontal is actually for a form with fields below each other, i.e. what most people would think of as a vertical form. The correct class for a form going across the page is form-inline. They probably introduced the term inline because they had already misused the term horizontal.

You see from some of the answers here that some people are using both of these classes in one form! Others think that they need form-horizontal when they actually want form-inline.

I suggest to do it exactly as described in the Bootstrap documentation:

<form class="form-inline">
  <div class="form-group">
    <label for="nameId">Name</label>
    <input type="text" class="form-control" id="nameId" placeholder="Jane Doe">
  </div>
</form>

Which produces:

enter image description here

How to call Stored Procedure in a View?

Easiest solution that I might have found is to create a table from the data you get from the SP. Then create a view from that:

Insert this at the last step when selecting data from the SP. SELECT * into table1 FROM #Temp

create view vw_view1 as select * from table1

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

You can build your HttpContent using the combination of JObject to avoid and JProperty and then call ToString() on it when building the StringContent:

        /*{
          "agent": {                             
            "name": "Agent Name",                
            "version": 1                                                          
          },
          "username": "Username",                                   
          "password": "User Password",
          "token": "xxxxxx"
        }*/

        JObject payLoad = new JObject(
            new JProperty("agent", 
                new JObject(
                    new JProperty("name", "Agent Name"),
                    new JProperty("version", 1)
                    ),
                new JProperty("username", "Username"),
                new JProperty("password", "User Password"),
                new JProperty("token", "xxxxxx")    
                )
            );

        using (HttpClient client = new HttpClient())
        {
            var httpContent = new StringContent(payLoad.ToString(), Encoding.UTF8, "application/json");

            using (HttpResponseMessage response = await client.PostAsync(requestUri, httpContent))
            {
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                return JObject.Parse(responseBody);
            }
        }

Open existing file, append a single line

File.AppendText will do it:

using (StreamWriter w = File.AppendText("textFile.txt")) 
{
    w.WriteLine ("-------HURRAY----------");
    w.Flush();
}

jQuery - setting the selected value of a select control via its text description

I haven't tested this, but this might work for you.

$("select#my-select option")
   .each(function() { this.selected = (this.text == myVal); });

How do I run SSH commands on remote system using Java?

You may take a look at this Java based framework for remote command execution, incl. via SSH: https://github.com/jkovacic/remote-exec It relies on two opensource SSH libraries, either JSch (for this implementation even an ECDSA authentication is supported) or Ganymed (one of these two libraries will be enough). At the first glance it might look a bit complex, you'll have to prepare plenty of SSH related classes (providing server and your user details, specifying encryption details, provide OpenSSH compatible private keys, etc., but the SSH itself is quite complex too). On the other hand, the modular design allows for simple inclusion of more SSH libraries, easy implementation of other command's output processing or even interactive classes etc.

TabLayout tab selection

I am using TabLayout to switch fragments. It works for the most part, except whenever I tried to select a tab programmatically using tab.select(), my TabLayout.OnTabSelectedListener would trigger the onTabSelected(TabLayout.Tab tab), which would cause me much grief. I was looking for a way to do programmatic selection without triggering the listener.

So I adapted @kenodoggy 's answer to my use. I was further facing a problem where some of the internal objects would return null (because they weren't created yet, because I was answering onActivityResult() from my fragment, which occurs before onCreate() in the case the activity is singleTask or singleInstance) so I wrote up a detailed if/else sequence which would report the error and fall through without the NullPointerException that would otherwise trigger. I use Timber for logging, if you're not using that substitute with Log.e().

void updateSelectedTabTo(int position) {
    if (tabLayout != null){
        int selected = tabLayout.getSelectedTabPosition();
        if (selected != -1){
            TabLayout.Tab oldTab = tabLayout.getTabAt(0);
            if (oldTab != null){
                View view = oldTab.getCustomView();
                if (view != null){
                    view.setSelected(false);
                }
                else {
                    Timber.e("oldTab customView is null");
                }
            }
            else {
                Timber.e("oldTab is null");
            }
        }
        else {
            Timber.e("selected is -1");
        }
        TabLayout.Tab newTab = tabLayout.getTabAt(position);
        if (newTab != null){
            View view = newTab.getCustomView();
            if (view != null){
                view.setSelected(false);
            }
            else {
                Timber.e("newTab customView is null");
            }
        }
        else {
            Timber.e("newTab is null");
        }
    }
    else {
        Timber.e("tablayout is null");
    }
}

Here, tabLayout is my memory variable bound to the TabLayout object in my XML. And I don't use the scrolling tab feature so I removed that as well.

What is the difference between encode/decode?

anUnicode.encode('encoding') results in a string object and can be called on a unicode object

aString.decode('encoding') results in an unicode object and can be called on a string, encoded in given encoding.


Some more explanations:

You can create some unicode object, which doesn't have any encoding set. The way it is stored by Python in memory is none of your concern. You can search it, split it and call any string manipulating function you like.

But there comes a time, when you'd like to print your unicode object to console or into some text file. So you have to encode it (for example - in UTF-8), you call encode('utf-8') and you get a string with '\u<someNumber>' inside, which is perfectly printable.

Then, again - you'd like to do the opposite - read string encoded in UTF-8 and treat it as an Unicode, so the \u360 would be one character, not 5. Then you decode a string (with selected encoding) and get brand new object of the unicode type.

Just as a side note - you can select some pervert encoding, like 'zip', 'base64', 'rot' and some of them will convert from string to string, but I believe the most common case is one that involves UTF-8/UTF-16 and string.

facet label font size

This should get you started:

R> qplot(hwy, cty, data = mpg) + 
       facet_grid(. ~ manufacturer) + 
       theme(strip.text.x = element_text(size = 8, colour = "orange", angle = 90))

See also this question: How can I manipulate the strip text of facet plots in ggplot2?

ASP.NET Bundles how to disable minification

If you have debug="true" in web.config and are using Scripts/Styles.Render to reference the bundles in your pages, that should turn off both bundling and minification. BundleTable.EnableOptimizations = false will always turn off both bundling and minification as well (irrespective of the debug true/false flag).

Are you perhaps not using the Scripts/Styles.Render helpers? If you are directly rendering references to the bundle via BundleTable.Bundles.ResolveBundleUrl() you will always get the minified/bundled content.

Should I use @EJB or @Inject

Here is a good discussion on the topic. Gavin King recommends @Inject over @EJB for non remote EJBs.

http://www.seamframework.org/107780.lace

or

https://web.archive.org/web/20140812065624/http://www.seamframework.org/107780.lace

Re: Injecting with @EJB or @Inject?

  1. Nov 2009, 20:48 America/New_York | Link Gavin King

That error is very strange, since EJB local references should always be serializable. Bug in glassfish, perhaps?

Basically, @Inject is always better, since:

it is more typesafe,
it supports @Alternatives, and
it is aware of the scope of the injected object.

I recommend against the use of @EJB except for declaring references to remote EJBs.

and

Re: Injecting with @EJB or @Inject?

  1. Nov 2009, 17:42 America/New_York | Link Gavin King

    Does it mean @EJB better with remote EJBs?

For a remote EJB, we can't declare metadata like qualifiers, @Alternative, etc, on the bean class, since the client simply isn't going to have access to that metadata. Furthermore, some additional metadata must be specified that we don't need for the local case (global JNDI name of whatever). So all that stuff needs to go somewhere else: namely the @Produces declaration.

Spring schemaLocation fails when there is no internet connection

Remove jars you added recently in the web-inf ->lib. for example jstl jars.

What is HTML5 ARIA?

What is it?

WAI-ARIA stands for “Web Accessibility Initiative – Accessible Rich Internet Applications”. It is a set of attributes to help enhance the semantics of a web site or web application to help assistive technologies, such as screen readers for the blind, make sense of certain things that are not native to HTML. The information exposed can range from something as simple as telling a screen reader that activating a link or button just showed or hid more items, to widgets as complex as whole menu systems or hierarchical tree views.

This is achieved by applying roles and state attributes to HTML 4.01 or later markup that has no bearing on layout or browser functionality, but provides additional information for assistive technologies.

One corner stone of WAI-ARIA is the role attribute. It tells the browser to tell the assistive technology that the HTML element used is not actually what the element name suggests, but something else. While it originally is only a div element, this div element may be the container to a list of auto-complete items, in which case a role of “listbox” would be appropriate to use. Likewise, another div that is a child of that container div, and which contains a single option item, should then get a role of “option”. Two divs, but through the roles, totally different meaning. The roles are modeled after commonly used desktop application counterparts.

An exception to this are document landmark roles, which don’t change the actual meaning of the element in question, but provide information about this particular place in a document.

The second corner stone are WAI-ARIA states and properties. They define the state of certain native or WAI-ARIA elements such as if something is collapsed or expanded, a form element is required, something has a popup menu attached to it or the like. These are often dynamic and change their values throughout the lifecycle of a web application, and are usually manipulated via JavaScript.

What is it not?

WAI-ARIA is not intended to influence browser behavior. Unlike a real button element, for example, a div which you pour the role of “button” onto does not give you keyboard focusability, an automatic click handler when Space or Enter are being pressed on it, and other properties that are indiginous to a button. The browser itself does not know that a div with role of “button” is a button, only its accessibility API portion does.

As a consequence, this means that you absolutely have to implement keyboard navigation, focusability and other behavioural patterns known from desktop applications yourself. You can find some Advanced ARIA techniques Here.

When should I not use it?

Yes, that’s correct, this section comes first! Because the first rule of using WAI-ARIA is: Don’t use it unless you absolutely have to! The less WAI-ARIA you have, and the more you can count on using native HTML widgets, the better! There are some more rules to follow, you can check them out here.

How to add an Access-Control-Allow-Origin header

For Java based Application add this to your web.xml file:

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.ttf</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.otf</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.eot</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.woff</url-pattern>
</servlet-mapping>

Difference between FetchType LAZY and EAGER in Java Persistence API?

I may consider performance and memory utilization. One big difference is that EAGER fetch strategy allows to use fetched data object without session. Why?
All data is fetched when eager marked data in the object when session is connected. However, in case of lazy loading strategy, lazy loading marked object does not retrieve data if session is disconnected (after session.close() statement). All that can be made by hibernate proxy. Eager strategy lets data to be still available after closing session.

What is the reason for a red exclamation mark next to my project in Eclipse?

This is common, you will need to do the following steps:

1- Right click on the project

2- Build path

3- Configure Build Path

4- Remove jars/projects that had moved from their old path

5- clean the project

6- build the project "if not automatically built"

7- Add the jars/projects using their new locations

Run and that is it!

Checking cin input stream produces an integer

You could use :

int a = 12;
if (a>0 || a<0){
cout << "Your text"<<endl;
}

I'm pretty sure it works.

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")

References

Efficient iteration with index in Scala

Indeed, calling zipWithIndex on a collection will traverse it and also create a new collection for the pairs. To avoid this, you can just call zipWithIndex on the iterator for the collection. This will just return a new iterator that keeps track of the index while iterating, so without creating an extra collection or additional traversing.

This is how scala.collection.Iterator.zipWithIndex is currently implemented in 2.10.3:

  def zipWithIndex: Iterator[(A, Int)] = new AbstractIterator[(A, Int)] {
    var idx = 0
    def hasNext = self.hasNext
    def next = {
      val ret = (self.next, idx)
      idx += 1
      ret
    }
  }

This should even be a bit more efficient than creating a view on the collection.

How to change pivot table data source in Excel?

Looks like this depends heavily on your version of Excel. I am using the 2007 version and it offers no wizard option when you right click on the table. You need to click on the pivot table to make extra 'PivotTable Tools' appear to the right of the other tabs at the top of the screen. Click the 'options' tab that appears here then there is a big icon on the middle of the ribbon named 'change data source'.

Declaring and using MySQL varchar variables

Looks like you forgot the @ in variable declaration. Also I remember having problems with SET in MySql a long time ago.

Try

DECLARE @FOO varchar(7);
DECLARE @oldFOO varchar(7);
SELECT @FOO = '138';
SELECT @oldFOO = CONCAT('0', @FOO);

update mypermits 
   set person = @FOO 
 where person = @oldFOO;

passing 2 $index values within nested ng-repeat

Each ng-repeat creates a child scope with the passed data, and also adds an additional $index variable in that scope.

So what you need to do is reach up to the parent scope, and use that $index.

See http://plnkr.co/edit/FvVhirpoOF8TYnIVygE6?p=preview

<li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu($parent.$index)" ng-repeat="tutorial in section.tutorials">
    {{tutorial.name}}
</li>

Android: How to overlay a bitmap and draw over a bitmap?

I think this example will definitely help you overlay a transparent image on top of another image. This is made possible by drawing both the images on canvas and returning a bitmap image.

Read more or download demo here

private Bitmap createSingleImageFromMultipleImages(Bitmap firstImage, Bitmap secondImage){

        Bitmap result = Bitmap.createBitmap(firstImage.getWidth(), firstImage.getHeight(), firstImage.getConfig());
        Canvas canvas = new Canvas(result);
        canvas.drawBitmap(firstImage, 0f, 0f, null);
        canvas.drawBitmap(secondImage, 10, 10, null);
        return result;
    }

and call the above function on button click and pass the two images to our function as shown below

public void buttonMerge(View view) {

        Bitmap bigImage = BitmapFactory.decodeResource(getResources(), R.drawable.img1);
        Bitmap smallImage = BitmapFactory.decodeResource(getResources(), R.drawable.img2);
        Bitmap mergedImages = createSingleImageFromMultipleImages(bigImage, smallImage);

        img.setImageBitmap(mergedImages);
    }

For more than two images, you can follow this link, how to merge multiple images programmatically on android

Error "library not found for" after putting application in AdMob

As for me this problem occurs because i installed Material Library for IOS. to solve this issue

1: Go to Build Settings of your target app.

2: Search for Other linker flags

3: Open the other linker flags and check for the library which is mention in the error.

4: remove that flag.

5: Clean and build.

I hope this fix your issue.

What does "request for member '*******' in something not a structure or union" mean?

It may means that you forgot include a header file that define this struct/union. For example:

foo.h file:

typedef union
{
    struct
    {
        uint8_t FIFO_BYTES_AVAILABLE    : 4;
        uint8_t STATE                   : 3;
        uint8_t CHIP_RDY                : 1;
    };
    uint8_t status;
} RF_CHIP_STATUS_t;

RF_CHIP_STATUS_t getStatus();

main.c file:

.
.
.
if (getStatus().CHIP_RDY) /* This will generate the error, you must add the  #include "foo.h" */
.
.
.

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

Same issue here, comparing the htdocs/xampp folder in 5.6.11 with 5.6.8 I saw all the files there are missing in 5.6.11. Copied the entire htdocs/xampp folder from 5.6.8 to 5.6.11 and worked fine.

Using JavaMail with TLS

The settings from the example above didn't work for the server I was using (authsmtp.com). I kept on getting this error:

javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?

I removed the mail.smtp.socketFactory settings and everything worked. The final settings were this (SMTP auth was not used and I set the port elsewhere):

java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.starttls.enable", "true");

TypeError: 'str' object is not callable (Python)

I had the same error. In my case wasn't because of a variable named str. But because I named a function with a str parameter and the variable the same.

same_name = same_name(var_name: str)

I run it in a loop. The first time it run ok. The second time I got this error. Renaming the variable to a name different from the function name fixed this. So I think it's because Python once associate a function name in a scope, the second time tries to associate the left part (same_name =) as a call to the function and detects that the str parameter is not present, so it's missing, then it throws that error.

Predict() - Maybe I'm not understanding it

instead of newdata you are using newdate in your predict code, verify once. and just use Coupon$estimate <- predict(model, Coupon) It will work.

SELECT * WHERE NOT EXISTS

SELECT * FROM employees WHERE name NOT IN (SELECT name FROM eotm_dyn)

OR

SELECT * FROM employees WHERE NOT EXISTS (SELECT * FROM eotm_dyn WHERE eotm_dyn.name = employees.name)

OR

SELECT * FROM employees LEFT OUTER JOIN eotm_dyn ON eotm_dyn.name = employees.name WHERE eotm_dyn IS NULL

What is Express.js?

1) What is Express.js?

Express.js is a Node.js framework. It's the most popular framework as of now (the most starred on NPM).

Enter image description here.

It's built around configuration and granular simplicity of Connect middleware. Some people compare Express.js to Ruby Sinatra vs. the bulky and opinionated Ruby on Rails.

2) What is the purpose of it with Node.js?

That you don't have to repeat same code over and over again. Node.js is a low-level I/O mechanism which has an HTTP module. If you just use an HTTP module, a lot of work like parsing the payload, cookies, storing sessions (in memory or in Redis), selecting the right route pattern based on regular expressions will have to be re-implemented. With Express.js, it is just there for you to use.

3) Why do we actually need Express.js? How it is useful for us to use with Node.js?

The first answer should answer your question. If no, then try to write a small REST API server in plain Node.js (that is, using only core modules) and then in Express.js. The latter will take you 5-10x less time and lines of code.

What is Redis? Does it come with Express.js?

Redis is a fast persistent key-value storage. You can optionally use it for storing sessions with Express.js, but you don't need to. By default, Express.js has memory storage for sessions. Redis also can be use for queueing jobs, for example, email jobs.

Check out my tutorial on REST API server with Express.js.

MVC but not by itself

Express.js is not an model-view-controller framework by itself. You need to bring your own object-relational mapping libraries such as Mongoose for MongoDB, Sequelize (http://sequelizejs.com) for SQL databases, Waterline (https://github.com/balderdashy/waterline) for many databases into the stack.

Alternatives

Other Node.js frameworks to consider (https://www.quora.com/Node-js/Which-Node-js-framework-is-best-for-building-a-RESTful-API):

UPDATE: I put together this resource that aid people in choosing Node.js frameworks: http://nodeframework.com

UPDATE2: We added some GitHub stats to nodeframework.com so now you can compare the level of social proof (GitHub stars) for 30+ frameworks on one page.

enter image description here

Full-stack:

Just REST API:

Ruby on Rails like:

Sinatra like:

Other:

Middleware:

Static site generators:

How can I print out all possible letter combinations a given phone number can represent?

public class Permutation {

    //display all combination attached to a 3 digit number

    public static void main(String ar[]){

            char data[][]= new char[][]{{'a','k','u'},
                                {'b','l','v'},
                                {'c','m','w'},
                                {'d','n','x'},
                                {'e','o','y'},
                                {'f','p','z'},
                                {'g','q','0'},
                                {'h','r','0'},
                                {'i','s','0'},
                                {'j','t','0'}};


        int num1, num2, num3=0;
        char tempdata[][]= new char[3][3];
        StringBuilder number = new StringBuilder("324"); // a 3 digit number

        //copy data to a tempdata array-------------------
        num1= Integer.parseInt(number.substring(0,1));
        tempdata[0] = data[num1];
        num2= Integer.parseInt(number.substring(1,2));
        tempdata[1] = data[num2];
        num3= Integer.parseInt(number.substring(2,3));
        tempdata[2] = data[num3];

        //display all combinations--------------------
        char temp2[][]=tempdata;
        char tempd, tempd2;
        int i,i2, i3=0;
        for(i=0;i<3;i++){
                tempd = temp2[0][i];
             for (i2=0;i2<3;i2++){
                 tempd2 = temp2[1][i2];
                 for(i3=0;i3<3;i3++){
                     System.out.print(tempd);
                     System.out.print(tempd2);
                     System.out.print(temp2[2][i3]);
                     System.out.println();
                 }//for i3

            }//for i2
         }
    }

}//end of class

find path of current folder - cmd

for /f "delims=" %%i in ("%0") do set "curpath=%%~dpi"
echo "%curpath%"

or

echo "%cd%"

The double quotes are needed if the path contains any & characters.

What does 'public static void' mean in Java?

The public keyword is an access specifier, which allows the programmer to control the visibility of class members. When a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared. (The opposite of public is private, which prevents a member from being used by code defined outside of its class.)

In this case, main( ) must be declared as public, since it must be called by code outside of its class when the program is started.

The keyword static allows main( ) to be called without having to instantiate a particular instance of the class. This is necessary since main( ) is called by the Java interpreter before any objects are made.

The keyword void simply tells the compiler that main( ) does not return a value. As you will see, methods may also return values.

Push Notifications in Android Platform

There's a lot a third party servers like Urban Airship, Xtify, Mainline, ... whiches allow send not only on Android, but also on iOs, Windows Phone ...

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed

I had the same error, then I tried <asp:PostBackTrigger ControlID="xyz"/> instead of AsyncPostBackTrigger .This worked for me. It is because we don't want a partial postback.

How to resolve compiler warning 'implicit declaration of function memset'

A good way to findout what header file you are missing:

 man <section> <function call>

To find out the section use:

apropos <function call>

Example:

 man 3 memset
 man 2 send

Edit in response to James Morris:

  • Section | Description
  • 1 General commands
  • 2 System calls
  • 3 C library functions
  • 4 Special files (usually devices, those found in /dev) and drivers
  • 5 File formats and conventions
  • 6 Games and screensavers
  • 7 Miscellanea
  • 8 System administration commands and daemons

Source: Wikipedia Man Page

How to make a PHP SOAP call using the SoapClient class

If you create the object of SoapParam, This will resolve your problem. Create a class and map it with object type given by WebService, Initialize the values and send in the request. See the sample below.

struct Contact {

    function Contact ($pid, $pname)
    {
      id = $pid;
      name = $pname;
  }
}

$struct = new Contact(100,"John");

$soapstruct = new SoapVar($struct, SOAP_ENC_OBJECT, "Contact","http://soapinterop.org/xsd");

$ContactParam = new SoapParam($soapstruct, "Contact")

$response = $client->Function1($ContactParam);

How to open .SQLite files

If you just want to see what's in the database without installing anything extra, you might already have SQLite CLI on your system. To check, open a command prompt and try:

sqlite3 database.sqlite

Replace database.sqlite with your database file. Then, if the database is small enough, you can view the entire contents with:

sqlite> .dump

Or you can list the tables:

sqlite> .tables

Regular SQL works here as well:

sqlite> select * from some_table;

Replace some_table as appropriate.

Remove a file from the list that will be committed

git rm --cached will remove it from the commit set ("un-adding" it); that sounds like what you want.

How do I serialize an object and save it to a file in Android?

I use SharePrefrences:

package myapps.serializedemo;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import java.io.IOException;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

//Create the SharedPreferences
    SharedPreferences sharedPreferences = this.getSharedPreferences("myapps.serilizerdemo", Context.MODE_PRIVATE);
    ArrayList<String> friends = new ArrayList<>();
    friends.add("Jack");
    friends.add("Joe");
    try {

 //Write / Serialize
 sharedPreferences.edit().putString("friends",
    ObjectSerializer.serialize(friends)).apply();
    } catch (IOException e) {
        e.printStackTrace();
    }
//READ BACK
    ArrayList<String> newFriends = new ArrayList<>();
    try {
        newFriends = (ArrayList<String>) ObjectSerializer.deserialize(
                sharedPreferences.getString("friends", ObjectSerializer.serialize(new ArrayList<String>())));
    } catch (IOException e) {
        e.printStackTrace();
    }
    Log.i("***NewFriends", newFriends.toString());
}
}

Spring Boot, Spring Data JPA with multiple DataSources

There is another way to have multiple dataSources by using @EnableAutoConfiguration and application.properties.

Basically put multiple dataSource configuration info on application.properties and generate default setup (dataSource and entityManagerFactory) automatically for first dataSource by @EnableAutoConfiguration. But for next dataSource, create dataSource, entityManagerFactory and transactionManager all manually by the info from property file.

Below is my example to setup two dataSources. First dataSource is setup by @EnableAutoConfiguration which can be assigned only for one configuration, not multiple. And that will generate 'transactionManager' by DataSourceTransactionManager, that looks default transactionManager generated by the annotation. However I have seen the transaction not beginning issue on the thread from scheduled thread pool only for the default DataSourceTransactionManager and also when there are multiple transaction managers. So I create transactionManager manually by JpaTransactionManager also for the first dataSource with assigning 'transactionManager' bean name and default entityManagerFactory. That JpaTransactionManager for first dataSource surely resolves the weird transaction issue on the thread from ScheduledThreadPool.

Update for Spring Boot 1.3.0.RELEASE

I found my previous configuration with @EnableAutoConfiguration for default dataSource has issue on finding entityManagerFactory with Spring Boot 1.3 version. Maybe default entityManagerFactory is not generated by @EnableAutoConfiguration, once after I introduce my own transactionManager. So now I create entityManagerFactory by myself. So I don't need to use @EntityScan. So it looks I'm getting more and more out of the setup by @EnableAutoConfiguration.

Second dataSource is setup without @EnableAutoConfiguration and create 'anotherTransactionManager' by manual way.

Since there are multiple transactionManager extends from PlatformTransactionManager, we should specify which transactionManager to use on each @Transactional annotation

Default Repository Config

@Configuration
@EnableTransactionManagement
@EnableAutoConfiguration
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactory",
        transactionManagerRef = "transactionManager",
        basePackages = {"com.mysource.repository"})
public class RepositoryConfig {
    @Autowired
    JpaVendorAdapter jpaVendorAdapter;

    @Autowired
    DataSource dataSource;

    @Bean(name = "entityManager")
    public EntityManager entityManager() {
        return entityManagerFactory().createEntityManager();
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public EntityManagerFactory entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
        emf.setDataSource(dataSource);
        emf.setJpaVendorAdapter(jpaVendorAdapter);
        emf.setPackagesToScan("com.mysource.model");
        emf.setPersistenceUnitName("default");   // <- giving 'default' as name
        emf.afterPropertiesSet();
        return emf.getObject();
    }

    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager tm = new JpaTransactionManager();
        tm.setEntityManagerFactory(entityManagerFactory());
        return tm;
    }
}

Another Repository Config

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "anotherEntityManagerFactory",
        transactionManagerRef = "anotherTransactionManager",
        basePackages = {"com.mysource.anothersource.repository"})
public class AnotherRepositoryConfig {
    @Autowired
    JpaVendorAdapter jpaVendorAdapter;

    @Value("${another.datasource.url}")
    private String databaseUrl;

    @Value("${another.datasource.username}")
    private String username;

    @Value("${another.datasource.password}")
    private String password;

    @Value("${another.dataource.driverClassName}")
    private String driverClassName;

    @Value("${another.datasource.hibernate.dialect}")
    private String dialect;

    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource(databaseUrl, username, password);
        dataSource.setDriverClassName(driverClassName);
        return dataSource;
    }

    @Bean(name = "anotherEntityManager")
    public EntityManager entityManager() {
        return entityManagerFactory().createEntityManager();
    }

    @Bean(name = "anotherEntityManagerFactory")
    public EntityManagerFactory entityManagerFactory() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.dialect", dialect);

        LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
        emf.setDataSource(dataSource());
        emf.setJpaVendorAdapter(jpaVendorAdapter);
        emf.setPackagesToScan("com.mysource.anothersource.model");   // <- package for entities
        emf.setPersistenceUnitName("anotherPersistenceUnit");
        emf.setJpaProperties(properties);
        emf.afterPropertiesSet();
        return emf.getObject();
    }

    @Bean(name = "anotherTransactionManager")
    public PlatformTransactionManager transactionManager() {
        return new JpaTransactionManager(entityManagerFactory());
    }
}

application.properties

# database configuration
spring.datasource.url=jdbc:h2:file:~/main-source;AUTO_SERVER=TRUE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.continueOnError=true
spring.datasource.initialize=false

# another database configuration
another.datasource.url=jdbc:sqlserver://localhost:1433;DatabaseName=another;
another.datasource.username=username
another.datasource.password=
another.datasource.hibernate.dialect=org.hibernate.dialect.SQLServer2008Dialect 
another.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver

Choose proper transactionManager for @Transactional annotation

Service for first datasource

@Service("mainService")
@Transactional("transactionManager")
public class DefaultDataSourceServiceImpl implements DefaultDataSourceService       
{

   //

}

Service for another datasource

@Service("anotherService")
@Transactional("anotherTransactionManager")
public class AnotherDataSourceServiceImpl implements AnotherDataSourceService 
{

   //

}

Check if a varchar is a number (TSQL)

Wade73's answer for decimals doesn't quite work. I've modified it to allow only a single decimal point.

declare @MyTable table(MyVar nvarchar(10));
insert into @MyTable (MyVar) 
values 
    (N'1234')
    , (N'000005')
    , (N'1,000')
    , (N'293.8457')
    , (N'x')
    , (N'+')
    , (N'293.8457.')
    , (N'......');

-- This shows that Wade73's answer allows some non-numeric values to slip through.
select * from (
    select 
        MyVar
        , case when MyVar not like N'%[^0-9.]%' then 1 else 0 end as IsNumber 
    from 
        @MyTable
) t order by IsNumber;

-- Notice the addition of "and MyVar not like N'%.%.%'".
select * from (
    select 
        MyVar
        , case when MyVar not like N'%[^0-9.]%' and MyVar not like N'%.%.%' then 1 else 0 end as IsNumber 
    from 
        @MyTable
) t 
order by IsNumber;

How to get a responsive button in bootstrap 3

For anyone who may be interested, another approach is using @media queries to scale the buttons on different viewport widths..

Demo: http://bootply.com/93706

Efficient way to rotate a list in python

It depends on what you want to have happen when you do this:

>>> shift([1,2,3], 14)

You might want to change your:

def shift(seq, n):
    return seq[n:]+seq[:n]

to:

def shift(seq, n):
    n = n % len(seq)
    return seq[n:] + seq[:n]

When to use NSInteger vs. int

If you dig into NSInteger's implementation:

#if __LP64__
typedef long NSInteger;
#else
typedef int NSInteger;
#endif

Simply, the NSInteger typedef does a step for you: if the architecture is 32-bit, it uses int, if it is 64-bit, it uses long. Using NSInteger, you don't need to worry about the architecture that the program is running on.

Cron job every three days

If you want it to run on specific days of the month, like the 1st, 4th, 7th, etc... then you can just have a conditional in your script that checks for the current day of the month.

I thought all you needed for this was instead of */3 which means every three days, use 1/3 which means every three days starting on the 1st of the month. so 7/3 would mean every three days starting on the 7th of the month, etc.

Get Mouse Position

In my scenario, I was supposed to open a dialog box in the mouse position based on a GUI operation done with the mouse. The following code worked for me:

    public Object open() {
    //create the contents of the dialog
    createContents();
    //setting the shell location based on the curent position
    //of the mouse
    PointerInfo a = MouseInfo.getPointerInfo();
    Point pt = a.getLocation();
    shellEO.setLocation (pt.x, pt.y);

    //once the contents are created and location is set-
    //open the dialog
    shellEO.open();
    shellEO.layout();
    Display display = getParent().getDisplay();
    while (!shellEO.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    return result;
}

pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/

I faced same problem but that was related proxy. it was resolved by setting proxy.

Set http_proxy=http://myuserid:mypassword@myproxyname:myproxyport
Set https_proxy=http://myuserid:mypassword@myproxyname:myproxyport

This might help someone.

'dict' object has no attribute 'has_key'

In python3, has_key(key) is replaced by __contains__(key)

Tested in python3.7:

a = {'a':1, 'b':2, 'c':3}
print(a.__contains__('a'))

Node.js heap out of memory

I have tried the below code and its working fine?.

  • open terminal from project root dir
  • execute the cmd to set new size.

    set NODE_OPTIONS=--max_old_space_size=8172
    

Or you can check the link for more info https://github.com/nodejs/node/issues/10137#issuecomment-487255987

What is a "bundle" in an Android application

Bundles are generally used for passing data between various Android activities. It depends on you what type of values you want to pass, but bundles can hold all types of values and pass them to the new activity.

You can use it like this:

Intent intent = new...
Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("myKey", AnyValue);  
startActivity(intent);

You can get the passed values by doing:

Bundle extras = intent.getExtras(); 
String tmp = extras.getString("myKey");

You can find more info at:

Need to get a string after a "word" in a string in c#

string founded = FindStringTakeX("UID:   994zxfa6q", "UID:", 9);


string FindStringTakeX(string strValue,string findKey,int take,bool ignoreWhiteSpace = true)
    {
        int index = strValue.IndexOf(findKey) + findKey.Length;

        if (index >= 0)
        {
            if (ignoreWhiteSpace)
            {
                while (strValue[index].ToString() == " ")
                {
                    index++;
                }
            }

            if(strValue.Length >= index + take)
            {
                string result = strValue.Substring(index, take);

                return result;
            }


        }

        return string.Empty;
    }

How do you use the "WITH" clause in MySQL?

In Sql the with statement specifies a temporary named result set, known as a common table expression (CTE). It can be used for recursive queries, but in this case, it specifies as subset. If mysql allows for subselectes i would try

select t1.* 
from  (
            SELECT  article.*, 
                    userinfo.*, 
                    category.* 
            FROM    question INNER JOIN 
                    userinfo ON userinfo.user_userid=article.article_ownerid INNER JOIN category ON article.article_categoryid=category.catid
            WHERE   article.article_isdeleted = 0
     ) t1
ORDER BY t1.article_date DESC Limit 1, 3

Can I change the color of Font Awesome's icon color?

This worked for me:

.icon-cog {
  color: black;
}

For versions of Font Awesome above 4.7.0, it looks this:

.fa-cog {
  color: black;
}

.autocomplete is not a function Error

Possibly multiple jquery.js file are added in , and the conflict appeared.

Stacked bar chart

Building on Roland's answer, using tidyr to reshape the data from wide to long:

library(tidyr)
library(ggplot2)

df <- read.table(text="Rank F1     F2     F3
1    500    250    50
2    400    100    30
3    300    155    100
4    200    90     10", header=TRUE)

df %>% 
  gather(variable, value, F1:F3) %>% 
  ggplot(aes(x = Rank, y = value, fill = variable)) + 
  geom_bar(stat = "identity")

enter image description here

Alphabet range in Python

This is the easiest way I can figure out:

#!/usr/bin/python3
for i in range(97, 123):
    print("{:c}".format(i), end='')

So, 97 to 122 are the ASCII number equivalent to 'a' to and 'z'. Notice the lowercase and the need to put 123, since it will not be included).

In print function make sure to set the {:c} (character) format, and, in this case, we want it to print it all together not even letting a new line at the end, so end=''would do the job.

The result is this: abcdefghijklmnopqrstuvwxyz

Print new output on same line

You can do something such as:

>>> print(''.join(map(str,range(1,11))))
12345678910

Assembly - JG/JNLE/JL/JNGE after CMP

Addition and subtraction in two's complement is the same for signed and unsigned numbers

The key observation is that CMP is basically subtraction, and:

In two's complement (integer representation used by x86), signed and unsigned addition are exactly the same operation

This allows for example hardware developers to implement it more efficiently with just one circuit.

So when you give input bytes to the x86 ADD instruction for example, it does not care if they are signed or not.

However, ADD does set a few flags depending on what happened during the operation:

  • carry: unsigned addition or subtraction result does not fit in bit size, e.g.: 0xFF + 0x01 or 0x00 - 0x01

    For addition, we would need to carry 1 to the next level.

  • sign: result has top bit set. I.e.: is negative if interpreted as signed.

  • overflow: input top bits are both 0 and 0 or 1 and 1 and output inverted is the opposite.

    I.e. signed operation changed sigedness in an impossible way (e.g. positive + positive or negative

We can then interpret those flags in a way that makes comparison match our expectations for signed or unsigned numbers.

This interpretation is exactly what JA vs JG and JB vs JL do for us!

Code example

Here is GNU GAS a code snippet to make this more concrete:

/* 0x0 ==
 *
 * * 0 in 2's complement signed
 * * 0 in 2's complement unsigned
 */
mov $0, %al

/* 0xFF ==
 *
 * *  -1 in 2's complement signed
 * * 255 in 2's complement unsigned
 */
mov $0xFF, %bl

/* Do the operation "Is al < bl?" */
cmp %bl, %al

Note that AT&T syntax is "backwards": mov src, dst. So you have to mentally reverse the operands for the condition codes to make sense with cmp. In Intel syntax, this would be cmp al, bl

After this point, the following jumps would be taken:

  • JB, because 0 < 255
  • JNA, because !(0 > 255)
  • JNL, because !(0 < -1)
  • JG, because 0 > -1

Note how in this particular example the signedness mattered, e.g. JB is taken but not JL.

Runnable example with assertions.

Equals / Negated versions like JLE / JNG are just aliases

By looking at the Intel 64 and IA-32 Architectures Software Developer's Manuals Volume 2 section "Jcc - Jump if Condition Is Met" we see that the encodings are identical, for example:

Opcode  Instruction  Description
7E cb   JLE rel8     Jump short if less or equal (ZF=1 or SF ? OF).
7E cb   JNG rel8     Jump short if not greater (ZF=1 or SF ? OF).

Function ereg_replace() is deprecated - How to clear this bug?

Here is more information regarding replacing ereg_replace with preg_replace

how to do file upload using jquery serialization

Use FormData object.It works for any type of form

$(document).on("submit", "form", function(event)
{
    event.preventDefault();
    $.ajax({
        url: $(this).attr("action"),
        type: $(this).attr("method"),
        dataType: "JSON",
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function (data, status)
        {

        },
        error: function (xhr, desc, err)
        {
            

        }
    });        

});

Add an object to a python list

If i am correct in believing that you are adding a variable to the array but when you change that variable outside of the array, it also changes inside the array but you don't want it to then it is a really simple solution.

When you are saving the variable to the array you should turn it into a string by simply putting str(variablename). For example:

array.append(str(variablename))

Using this method your code should look like this:

arrayList = []
for x in allValues:
    result = model(x)
    arrayList.append(str(wM))        #this is the only line that is changed.
    wM.reset()

Round float to x decimals?

Use the built-in function round():

In [23]: round(66.66666666666,4)
Out[23]: 66.6667

In [24]: round(1.29578293,6)
Out[24]: 1.295783

help on round():

round(number[, ndigits]) -> floating point number

Round a number to a given precision in decimal digits (default 0 digits). This always returns a floating point number. Precision may be negative.

How to create a JavaScript callback for knowing when an image is loaded?

Life is too short for jquery.

_x000D_
_x000D_
function waitForImageToLoad(imageElement){_x000D_
  return new Promise(resolve=>{imageElement.onload = resolve})_x000D_
}_x000D_
_x000D_
var myImage = document.getElementById('myImage');_x000D_
var newImageSrc = "https://pmchollywoodlife.files.wordpress.com/2011/12/justin-bieber-bio-photo1.jpg?w=620"_x000D_
_x000D_
myImage.src = newImageSrc;_x000D_
waitForImageToLoad(myImage).then(()=>{_x000D_
  // Image have loaded._x000D_
  console.log('Loaded lol')_x000D_
});
_x000D_
<img id="myImage" src="">
_x000D_
_x000D_
_x000D_

What is the maximum length of data I can put in a BLOB column in MySQL?

A BLOB can be 65535 bytes (64 KB) maximum.

If you need more consider using:

  • a MEDIUMBLOB for 16777215 bytes (16 MB)

  • a LONGBLOB for 4294967295 bytes (4 GB).

See Storage Requirements for String Types for more info.

How to .gitignore all files/folder in a folder, but not the folder itself?

Put this .gitignore into the folder, then git add .gitignore.

*
*/
!.gitignore

The * line tells git to ignore all files in the folder, but !.gitignore tells git to still include the .gitignore file. This way, your local repository and any other clones of the repository all get both the empty folder and the .gitignore it needs.

Edit: May be obvious but also add */ to the .gitignore to also ignore subfolders.

border-radius not working

For my case, I have a dropdown list in my div container, so I can not use overflow: hidden or my dropdown list will be hidden.

Inspired by this discussion: https://twitter.com/siddharthkp/status/1094821277452234752 I use border-bottom-left-radius and border-bottom-right-radius in the child element to fix this issue.

make sure you add it the correct value for each child separately

enter image description here

LINQ: Distinct values

In addition to Jon Skeet's answer, you can also use the group by expressions to get the unique groups along w/ a count for each groups iterations:

var query = from e in doc.Elements("whatever")
            group e by new { id = e.Key, val = e.Value } into g
            select new { id = g.Key.id, val = g.Key.val, count = g.Count() };

PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value

If you still need an answer then in my case it works after (re)download Android image but directly from Android Studio not through Visual Studio button.

Git pull till a particular commit

If you merge a commit into your branch, you should get all the history between.

Observe:

$ git init ./
Initialized empty Git repository in /Users/dfarrell/git/demo/.git/
$ echo 'a' > letter
$ git add letter
$ git commit -m 'Initial Letter'
[master (root-commit) 6e59e76] Initial Letter
 1 file changed, 1 insertion(+)
 create mode 100644 letter
$ echo 'b' >> letter
$ git add letter && git commit -m 'Adding letter'
[master 7126e6d] Adding letter
 1 file changed, 1 insertion(+)
$ echo 'c' >> letter; git add letter && git commit -m 'Adding letter'
[master f2458be] Adding letter
 1 file changed, 1 insertion(+)
$ echo 'd' >> letter; git add letter && git commit -m 'Adding letter'
[master 7f77979] Adding letter
 1 file changed, 1 insertion(+)
$ echo 'e' >> letter; git add letter && git commit -m 'Adding letter'
[master 790eade] Adding letter
 1 file changed, 1 insertion(+)
$ git log
commit 790eade367b0d8ab8146596cd717c25fd895302a
Author: Dan Farrell 
Date:   Thu Jul 16 14:21:26 2015 -0500

    Adding letter

commit 7f77979efd17f277b4be695c559c1383d2fc2f27
Author: Dan Farrell 
Date:   Thu Jul 16 14:21:24 2015 -0500

    Adding letter

commit f2458bea7780bf09fe643095dbae95cf97357ccc
Author: Dan Farrell 
Date:   Thu Jul 16 14:21:19 2015 -0500

    Adding letter

commit 7126e6dcb9c28ac60cb86ae40fb358350d0c5fad
Author: Dan Farrell 
Date:   Thu Jul 16 14:20:52 2015 -0500

    Adding letter

commit 6e59e7650314112fb80097d7d3803c964b3656f0
Author: Dan Farrell 
Date:   Thu Jul 16 14:20:33 2015 -0500

    Initial Letter
$ git checkout 6e59e7650314112fb80097d7d3803c964b3656f
$ git checkout 7126e6dcb9c28ac60cb86ae40fb358350d0c5fad
Note: checking out '7126e6dcb9c28ac60cb86ae40fb358350d0c5fad'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b new_branch_name

HEAD is now at 7126e6d... Adding letter
$ git checkout -b B 7126e6dcb9c28ac60cb86ae40fb358350d0c5fad
Switched to a new branch 'B'
$ git pull 790eade367b0d8ab8146596cd717c25fd895302a
fatal: '790eade367b0d8ab8146596cd717c25fd895302a' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
$ git merge 7f77979efd17f277b4be695c559c1383d2fc2f27
Updating 7126e6d..7f77979
Fast-forward
 letter | 2 ++
 1 file changed, 2 insertions(+)
$ cat letter
a
b
c
d

printf with std::string?

printf accepts a variable number of arguments. Those can only have Plain Old Data (POD) types. Code that passes anything other than POD to printf only compiles because the compiler assumes you got your format right. %s means that the respective argument is supposed to be a pointer to a char. In your case it is an std::string not const char*. printf does not know it because the argument type goes lost and is supposed to be restored from the format parameter. When turning that std::string argument into const char* the resulting pointer will point to some irrelevant region of memory instead of your desired C string. For that reason your code prints out gibberish.

While printf is an excellent choice for printing out formatted text, (especially if you intend to have padding), it can be dangerous if you haven't enabled compiler warnings. Always enable warnings because then mistakes like this are easily avoidable. There is no reason to use the clumsy std::cout mechanism if the printf family can do the same task in a much faster and prettier way. Just make sure you have enabled all warnings (-Wall -Wextra) and you will be good. In case you use your own custom printf implementation you should declare it with the __attribute__ mechanism that enables the compiler to check the format string against the parameters provided.

Programmatically scroll a UIScrollView

I'm amazed that this topic is 9 years old and the actual straightforward answer is not here!

What you're looking for is scrollRectToVisible(_:animated:).

Example:

extension SignUpView: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        scrollView.scrollRectToVisible(textField.frame, animated: true)
    }
}

What it does is exactly what you need, and it's far better than hacky contentOffset

This method scrolls the content view so that the area defined by rect is just visible inside the scroll view. If the area is already visible, the method does nothing.

From: https://developer.apple.com/documentation/uikit/uiscrollview/1619439-scrollrecttovisible

C++ JSON Serialization

For that you need reflection in C/C++ language, that doesn't exists. You need to have some meta data describing the structure of your classes (members, inherited base classes). For the moment C/C++ compilers doesn't provide automatically that information in built binaries.

I had the same idea in mind, and I used GCC XML project to get this information. It outputs XML data describing class structures. I have built a project and I'm explaining some key points in this page :

Serialization is easy, but we have to deal with complex data structure implementations (std::string, std::map for example) that play with allocated buffers. Deserialization is more complex and you need to rebuild your object with all its members, plus references to vtables ... a painful implementation.

For example you can serialize like that :

    // Random class initialization
    com::class1* aObject = new com::class1();

    for (int i=0; i<10; i++){
            aObject->setData(i,i);
    }      

    aObject->pdata = new char[7];
    for (int i=0; i<7; i++){
            aObject->pdata[i] = 7-i;
    }
    // dictionary initialization
    cjson::dictionary aDict("./data/dictionary.xml");

    // json transformation
    std::string aJson = aDict.toJson<com::class1>(aObject);

    // print encoded class
    cout << aJson << std::endl ;

To deserialize data it works like that:

    // decode the object
    com::class1* aDecodedObject = aDict.fromJson<com::class1>(aJson);

    // modify data
    aDecodedObject->setData(4,22);

    // json transformation
    aJson = aDict.toJson<com::class1>(aDecodedObject);

    // print encoded class
    cout << aJson << std::endl ;

Ouptuts:

>:~/cjson$ ./main
{"_index":54,"_inner":  {"_ident":"test","pi":3.141593},"_name":"first","com::class0::_type":"type","com::class0::data":[0,1,2,3,4,5,6,7,8,9],"com::classb::_ref":"ref","com::classm1::_type":"typem1","com::classm1::pdata":[7,6,5,4,3,2,1]}
{"_index":54,"_inner":{"_ident":"test","pi":3.141593},"_name":"first","com::class0::_type":"type","com::class0::data":[0,1,2,3,22,5,6,7,8,9],"com::classb::_ref":"ref","com::classm1::_type":"typem1","com::classm1::pdata":[7,6,5,4,3,2,1]}
>:~/cjson$ 

Usually these implementations are compiler dependent (ABI Specification for example), and requires external description to work (GCCXML output), such are not really easy to integrate to projects.

How to change symbol for decimal point in double.ToString()?

Some shortcut is to create a NumberFormatInfo class, set its NumberDecimalSeparator property to "." and use the class as parameter to ToString() method whenever u need it.

using System.Globalization;

NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ".";

value.ToString(nfi);

Multiple arguments to function called by pthread_create()?

I have the same question as the original poster, Michael.

However I have tried to apply the answers submitted for the original code without success

After some trial and error, here is my version of the code that works (or at least works for me!). And if you look closely, you will note that it is different to the earlier solutions posted.

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

struct arg_struct
{
   int arg1;
   int arg2;
} *args;

void *print_the_arguments(void *arguments)
{
   struct arg_struct *args = arguments;
   printf("Thread\n");
   printf("%d\n", args->arg1);
   printf("%d\n", args->arg2);
   pthread_exit(NULL);
   return NULL;
}

int main()
{
   pthread_t some_thread;
   args = malloc(sizeof(struct arg_struct) * 1);

   args->arg1 = 5;
   args->arg2 = 7;

   printf("Before\n");
   printf("%d\n", args->arg1);
   printf("%d\n", args->arg2);
   printf("\n");


   if (pthread_create(&some_thread, NULL, &print_the_arguments, args) != 0)
   {
      printf("Uh-oh!\n");
      return -1;
   }

   return pthread_join(some_thread, NULL); /* Wait until thread is finished */
}

How do I use dataReceived event of the SerialPort Port Object in C#?

I believe this won't work because you are using a console application and there is no Event Loop running. An Event Loop / Message Pump used for event handling is setup automatically when a Winforms application is created, but not for a console app.

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

How to open a new tab using Selenium WebDriver

I am using Selenium 2.52.0 in Java and Firefox 44.0.2. Unfortunately none of the previous solutions worked for me.

The problem is if I a call driver.getWindowHandles() I always get one single handle. Somehow this makes sense to me as Firefox is a single process and each tab is not a separate process. But maybe I am wrong. Anyhow, I try to write my own solution:

// Open a new tab
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");

// URL to open in a new tab
String urlToOpen = "https://url_to_open_in_a_new_tab";

Iterator<String> windowIterator = driver.getWindowHandles()
        .iterator();
// I always get handlesSize == 1, regardless how many tabs I have
int handlesSize = driver.getWindowHandles().size();

// I had to grab the original handle
String originalHandle = driver.getWindowHandle();

driver.navigate().to(urlToOpen);

Actions action = new Actions(driver);
// Close the newly opened tab
action.keyDown(Keys.CONTROL).sendKeys("w").perform();
// Switch back to original
action.keyDown(Keys.CONTROL).sendKeys("1").perform();

// And switch back to the original handle. I am not sure why, but
// it just did not work without this, like it has lost the focus
driver.switchTo().window(originalHandle);

I used the Ctrl + T combination to open a new tab, Ctrl + W to close it, and to switch back to original tab I used Ctrl + 1 (the first tab).

I am aware that mine solution is not perfect or even good and I would also like to switch with driver's switchTo call, but as I wrote it was not possible as I had only one handle. Maybe this will be helpful to someone with the same situation.

Response::json() - Laravel 5.1

although Response::json() is not getting popular of recent, that does not stop you and Me from using it. In fact you don't need any facade to use it,

instead of:

$response = Response::json($messages, 200);

Use this:

$response = \Response::json($messages, 200);

with the slash, you are sure good to go.

Align nav-items to right side in bootstrap-4

With Bootstrap v4.0.0-alpha.6: Two <ul>s (.navbar-na), one with .mr-auto and one with .ml-auto:

<nav ...> 
  ...     
  <div class="collapse navbar-collapse">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Left Link </a>
      </li>
    </ul>
    <ul class="navbar-nav ml-auto">
      <li class="nav-item">
        <a class="nav-link" href="#">Right Link </a>
      </li>
    </ul>
  </div>
</nav>

How do I turn off PHP Notices?

Use phpinfo() and search for Configuration File (php.ini) Path to see which config file path for php is used. PHP can have multiple config files depending on environment it's running. Usually, for console it's:

/etc/php5/cli/php.ini

and for php run by apache it's:

/etc/php5/apache2/php.ini

And then set error_reporting the way you need it:

http://www.phpknowhow.com/configuration/php-ini-error-settings/ http://www.zootemplate.com/news-updates/how-to-disable-notice-and-warning-in-phpini-file

How do I create a link to add an entry to a calendar?

The links in Dave's post are great. Just to put a few technical details about the google links into an answer here on SO:

Google Calendar Link

<a href="http://www.google.com/calendar/event?action=TEMPLATE&text=Example%20Event&dates=20131124T010000Z/20131124T020000Z&details=Event%20Details%20Here&location=123%20Main%20St%2C%20Example%2C%20NY">Add to gCal</a>

the parameters being:

  • action=TEMPLATE (required)
  • text (url encoded name of the event)
  • dates (ISO date format, startdate/enddate - must have both start and end time - the button generator will let you leave the endtime blank, but you must have one or it won't work.)
    • to use the user's timezone: 20131208T160000/20131208T180000
    • to use global time, convert to UTC, then use 20131208T160000Z/20131208T180000Z
    • all day events, you can use 20131208/20131209 - note that the button generator gets it wrong. You must use the following date as the end date for a one day all day event, or +1 day to whatever you want the end date to be.
  • details (url encoded event description/details)
  • location (url encoded location of the event - make sure it's an address google maps can read easily)

Update Feb 2018:

Here's a new link structure that seems to support the new google version of google calendar w/o requiring API interaction:

https://calendar.google.com/calendar/r/eventedit?text=My+Custom+Event&dates=20180512T230000Z/20180513T030000Z&details=For+details,+link+here:+https://example.com/tickets-43251101208&location=Garage+Boston+-+20+Linden+Street+-+Allston,+MA+02134

New base url: https://calendar.google.com/calendar/r/eventedit

New parameters:

  • text (name of the event)
  • dates (ISO date format, startdate/enddate - must have both start and end time)
    • an event w/ start/end times: 20131208T160000/20131208T180000
    • all day events, you can use 20131208/20131209 - end date must be +1 day to whatever you want the end date to be.
  • ctz (timezone such as America/New_York - leave blank to use the user's default timezone. Highly recommended to include this in almost all situations. For example, a reminder for a video conference: if three people in different timezones clicked this link and set a reminder for their "own" Tuesday at 10:00am, this would not work out well.)
  • details (url encoded event description/details)
  • location (url encoded location of the event - make sure it's an address google maps can read easily)
  • add (comma separated list of emails - adds guests to your new event)

Notes:

  • the old url structure above now redirects here
  • supports https
  • deals w/ timezones better
  • accepts + for space in addition to %20 (urlencode vs rawurlencode in php - both work)

Regular expression to extract numbers from a string

we can use \b as a word boundary and then; \b\d+\b

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

By reading your exception , It's sure that you forgot to autowire customerService

You should autowire your customerservice .

make following changes in your controller class

@Controller
public class CustomerController{

    @Autowired
    private Customerservice customerservice;
......other code......

}

Again your service implementation class

write

@Service
public class CustomerServiceImpl implements CustomerService {
    @Autowired
    private CustomerDAO customerDAO;
......other code......

.....add transactional methods
}

If you are using hibernate make necessary changes in your applicationcontext xml file(configuration of session factory is needed).

you should autowire sessionFactory set method in your DAO mplementation

please find samle application context :

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:annotation-config />
    <context:component-scan base-package="com.sparkle" />
    <!-- Configures the @Controller programming model -->
    <mvc:annotation-driven />

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
            p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="0" />

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>
    <!-- <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.properties" /> -->

     <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">         
        <list>
            <value>/WEB-INF/jdbc.properties</value>          

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




    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
        p:password="${jdbc.password}" />


    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <tx:annotation-driven />


   <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
          p:sessionFactory-ref="sessionFactory"/>


</beans>

note that i am using jdbc.properties file for jdbc url and driver specification

How to change color of ListView items on focus and on click

Here's a good article on how to use selectors with lists.

Instead of setting it to be the android:background of the ListView, I believe you want to set android:listSelector as shown below:

<ListView android:id="@+id/list" 
  android:layout_width="fill_parent"
  android:layout_height="wrap_content" 
  android:layout_gravity="center"
  android:divider="@null" 
  android:dividerHeight="0dip"
  android:listSelector="@drawable/list_selector" />

Launch Failed. Binary not found. CDT on Eclipse Helios

First you need to make sure that the project has been built. You can build a project with the hammer icon in the toolbar. You can choose to build either a Debug or Release version. If you cannot build the project then the problem is that you either don't have a compiler installed or that the IDE does not find the compiler.

To see if you have a compiler installed in a Mac you can run the following command from the command line:

g++ --version

If you have it already installed (it gets installed when you install the XCode tools) you can see its location running:

which g++

If you were able to build the project but you still get the "binary not found" message then the issue might be that a default launch configuration is not being created for the project. In that case do this:

Right click project > Run As > Run Configurations... > 

Then create a new configuration under the "C/C++ Application" section > Enter the full path to the executable file (the file that was created in the build step and that will exist in either the Debug or Release folder). Your launch configuration should look like this:

enter image description here

How to sort 2 dimensional array by column value?

Nothing special, just saving the cost it takes to return a value at certain index from an array.

function sortByCol(arr, colIndex){
    arr.sort(sortFunction)
    function sortFunction(a, b) {
        a = a[colIndex]
        b = b[colIndex]
        return (a === b) ? 0 : (a < b) ? -1 : 1
    }
}
// Usage
var a = [[12, 'AAA'], [58, 'BBB'], [28, 'CCC'],[18, 'DDD']]
sortByCol(a, 0)
console.log(JSON.stringify(a))
// "[[12,"AAA"],[18,"DDD"],[28,"CCC"],[58,"BBB"]]"