Programs & Examples On #Locationmanager

The LocationManager class in Android provides access to the system location services. These services allow applications to obtain periodic updates of the device's geographical location, or to fire an application-specified Intent when the device enters the proximity of a given geographical location.

Android check permission for LocationManager

if you are working on dynamic permissions and any permission like ACCESS_FINE_LOCATION,ACCESS_COARSE_LOCATION giving error "cannot resolve method PERMISSION_NAME" in this case write you code with permission name and then rebuild your project this will regenerate the manifest(Manifest.permission) file.

Adding Buttons To Google Sheets and Set value to Cells on clicking

Consider building an Add-on that has an actual button and not using the outdated method of linking an image to a script function.

In the script editor, under the Help menu >> Welcome Screen >> link to Google Sheets Add-on - will give you sample code to use.

How do I add an image to a JButton

For example if you have image in folder res/image.png you can write:

try
{
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream input = classLoader.getResourceAsStream("image.png");
    // URL input = classLoader.getResource("image.png"); // <-- You can use URL class too.
    BufferedImage image = ImageIO.read(input);

    button.setIcon(new ImageIcon(image));
}
catch(IOException e)
{
    e.printStackTrace();
}

In one line:

try
{
    button.setIcon(new ImageIcon(ImageIO.read(Thread.currentThread().getContextClassLoader().getResourceAsStream("image.png"))));
}
catch(IOException e)
{
    e.printStackTrace();
}

If the image is bigger than button then it will not shown.

CSS position absolute full width problem

I have similar situation. In my case, it doesn't have a parent with position:relative. Just paste my solution here for those that might need.

position: fixed;
left: 0;
right: 0;

How can I commit files with git?

This happens when you do not include a message when you try to commit using:

git commit

It launches an editor environment. Quit it by typing :q! and hitting enter.

It's going to take you back to the terminal without committing, so make sure to try again, this time pass in a message:

git commit -m 'Initial commit'

Windows 7 environment variable not working in path

I had exactly the same problem, to solve it, you can do one of two things:

  • Put all variables in System Variables instead of User and add the ones you want to PATH

Or

  • Put all variables in User Variables, and create or edit the PATH variables in User Variable, not In System. The Path variables in System don't expand the User Variables.

If the above are all correct, but the problem is still present, you need to check the system Registry, in HKEY_CURRENT_USER\Environment, to make sure the "PATH" key type is REG_EXPAND_SZ (not REG_SZ).

How to send and receive JSON data from a restful webservice using Jersey API

For me, parameter (JSONObject inputJsonObj) was not working. I am using jersey 2.* Hence I feel this is the

java(Jax-rs) and Angular way

I hope it's helpful to someone using JAVA Rest and AngularJS like me.

@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public Map<String, String> methodName(String data) throws Exception {
    JSONObject recoData = new JSONObject(data);
    //Do whatever with json object
}

Client side I used AngularJS

factory.update = function () {
data = {user:'Shreedhar Bhat',address:[{houseNo:105},{city:'Bengaluru'}]};
        data= JSON.stringify(data);//Convert object to string
        var d = $q.defer();
        $http({
            method: 'POST',
            url: 'REST/webApp/update',
            headers: {'Content-Type': 'text/plain'},
            data:data
        })
        .success(function (response) {
            d.resolve(response);
        })
        .error(function (response) {
            d.reject(response);
        });

        return d.promise;
    };

What does "pending" mean for request in Chrome Developer Window?

I had some problems with pending request for mp3 files. I had a list of mp3 files and one player to play them. If I picked a file that had already been downloaded, Chrome would block the request and show "pending request" in the network tab of the developer tools.

All versions of Chrome seem to be affected.

Here is a solution I found:

player[0].setAttribute('src','video.webm?dummy=' + Date.now());

You just add a dummy query string to the end of each url. This forces Chrome to download the file again.

Another example with popcorn player (using jquery) :

url = $(this).find('.url_song').attr('url');
pop = Popcorn.smart( "#player_",  url + '?i=' + Date.now());

This works for me. In fact, the resource is not stored in the cache system. This should also work in the same way for .csv files.

How to access Spring context in jUnit tests annotated with @RunWith and @ContextConfiguration?

It's possible to inject instance of ApplicationContext class by using SpringClassRule and SpringMethodRule rules. It might be very handy if you would like to use another non-Spring runners. Here's an example:

@ContextConfiguration(classes = BeanConfiguration.class)
public static class SpringRuleUsage {

    @ClassRule
    public static final SpringClassRule springClassRule = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

    @Autowired
    private ApplicationContext context;

    @Test
    public void shouldInjectContext() {
    }
}

Displaying the Error Messages in Laravel after being Redirected from controller

$validator = Validator::make($request->all(), [ 'email' => 'required|email', 'password' => 'required', ]);

if ($validator->fails()) { return $validator->errors(); }

Can I append an array to 'formdata' in javascript?

This works for me when I sent file + text + array:

const uploadData = new FormData();
if (isArray(value)) {
  const k = `${key}[]`;
  uploadData.append(k, value);
} else {
  uploadData.append(key, value);
}


const headers = {
  'Content-Type': 'multipart/form-data',
};

How to get a microtime in Node.js?

new Date().getTime()? This gives you a timestamp in milliseconds, which is the most accurate that JS will give you.

Update: As stated by vaughan, process.hrtime() is available within Node.js - its resolution are nanoseconds and therefore its much higher, also this doesn't mean it has to be more exact.

PS.: Just to be clearer, process.hrtime() returns you a tuple Array containing the current high-resolution real time in a [seconds, nanoseconds]

Pass a JavaScript function as parameter

Here it's another approach :

function a(first,second)    
{        
return (second)(first);           
}     

a('Hello',function(e){alert(e+ ' world!');}); //=> Hello world     

Ruby: What is the easiest way to remove the first element from an array?

This is pretty neat:

head, *tail = [1, 2, 3, 4, 5]
#==> head = 1, tail = [2, 3, 4, 5]

As written in the comments, there's an advantage of not mutating the original list.

How to set time delay in javascript

setTimeout(function(){


}, 500); 

Place your code inside of the { }

500 = 0.5 seconds

2200 = 2.2 seconds

etc.

How to check if one DateTime is greater than the other in C#

I'd like to demonstrate that if you convert to .Date that you don't need to worry about hours/mins/seconds etc:

    [Test]
    public void ConvertToDateWillHaveTwoDatesEqual()
    {
        DateTime d1 = new DateTime(2008, 1, 1);
        DateTime d2 = new DateTime(2008, 1, 2);
        Assert.IsTrue(d1 < d2);

        DateTime d3 = new DateTime(2008, 1, 1,7,0,0);
        DateTime d4 = new DateTime(2008, 1, 1,10,0,0);
        Assert.IsTrue(d3 < d4);
        Assert.IsFalse(d3.Date < d4.Date);
    }

What type of hash does WordPress use?

MD5 worked for me changing my database manually. See: Resetting Your Password

How can I check for NaN values?

math.isnan(x)

Return True if x is a NaN (not a number), and False otherwise.

>>> import math
>>> x = float('nan')
>>> math.isnan(x)
True

How do I check if a variable is of a certain type (compare two types) in C?

As other people have already said this isn't supported in the C language. You could however check the size of a variable using the sizeof() function. This may help you determine if two variables can store the same type of data.

Before you do that, read the comments below.

jQuery: find element by text

The following jQuery selects div nodes that contain text but have no children, which are the leaf nodes of the DOM tree.

_x000D_
_x000D_
$('div:contains("test"):not(:has(*))').css('background-color', 'red');
_x000D_
<div>div1_x000D_
<div>This is a test, nested in div1</div>_x000D_
<div>Nested in div1<div>_x000D_
</div>_x000D_
<div>div2 test_x000D_
<div>This is another test, nested in div2</div>_x000D_
<div>Nested in div2</div>_x000D_
</div>_x000D_
<div>_x000D_
div3_x000D_
</div>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Node.js res.setHeader('content-type', 'text/javascript'); pushing the response javascript as file download

Use application/javascript as content type instead of text/javascript

text/javascript is mentioned obsolete. See reference docs.

http://www.iana.org/assignments/media-types/application

Also see this question on SO.

UPDATE:

I have tried executing the code you have given and the below didn't work.

res.setHeader('content-type', 'text/javascript');
res.send(JS_Script);

This is what worked for me.

res.setHeader('content-type', 'text/javascript');
res.end(JS_Script);

As robertklep has suggested, please refer to the node http docs, there is no response.send() there.

Can you control how an SVG's stroke-width is drawn?

I found an easy way, which has a few restrictions, but worked for me:

  • define the shape in defs
  • define a clip path referencing the shape
  • use it and double the stroke with as the outside is clipped

Here a working example:

_x000D_
_x000D_
<svg width="240" height="240" viewBox="0 0 1024 1024">_x000D_
<defs>_x000D_
 <path id="ld" d="M256,0 L0,512 L384,512 L128,1024 L1024,384 L640,384 L896,0 L256,0 Z"/>_x000D_
 <clipPath id="clip">_x000D_
  <use xlink:href="#ld"/>_x000D_
 </clipPath>_x000D_
</defs>_x000D_
<g>_x000D_
 <use xlink:href="#ld" stroke="#0081C6" stroke-width="160" fill="#00D2B8" clip-path="url(#clip)"/>_x000D_
</g>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

How does #include <bits/stdc++.h> work in C++?

That header file is not part of the C++ standard, is therefore non-portable, and should be avoided.

Moreover, even if there were some catch-all header in the standard, you would want to avoid it in lieu of specific headers, since the compiler has to actually read in and parse every included header (including recursively included headers) every single time that translation unit is compiled.

Merging two images in C#/.NET

This will add an image to another.

using (Graphics grfx = Graphics.FromImage(image))
{
    grfx.DrawImage(newImage, x, y)
}

Graphics is in the namespace System.Drawing

How do I add a user when I'm using Alpine as a base image?

Alpine uses the command adduser and addgroup for creating users and groups (rather than useradd and usergroup).

FROM alpine:latest

# Create a group and user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup

# Tell docker that all future commands should run as the appuser user
USER appuser

The flags for adduser are:

Usage: adduser [OPTIONS] USER [GROUP]

Create new user, or add USER to GROUP

        -h DIR          Home directory
        -g GECOS        GECOS field
        -s SHELL        Login shell
        -G GRP          Group
        -S              Create a system user
        -D              Don't assign a password
        -H              Don't create home directory
        -u UID          User id
        -k SKEL         Skeleton directory (/etc/skel)

Add new user official docs

How to implement a read only property

C# 6.0 adds readonly auto properties

public object MyProperty { get; }

So when you don't need to support older compilers you can have a truly readonly property with code that's just as concise as a readonly field.


Versioning:
I think it doesn't make much difference if you are only interested in source compatibility.
Using a property is better for binary compatibility since you can replace it by a property which has a setter without breaking compiled code depending on your library.

Convention:
You are following the convention. In cases like this where the differences between the two possibilities are relatively minor following the convention is better. One case where it might come back to bite you is reflection based code. It might only accept properties and not fields, for example a property editor/viewer.

Serialization
Changing from field to property will probably break a lot of serializers. And AFAIK XmlSerializer does only serialize public properties and not public fields.

Using an Autoproperty
Another common Variation is using an autoproperty with a private setter. While this is short and a property it doesn't enforce the readonlyness. So I prefer the other ones.

Readonly field is selfdocumenting
There is one advantage of the field though:
It makes it clear at a glance at the public interface that it's actually immutable (barring reflection). Whereas in case of a property you can only see that you cannot change it, so you'd have to refer to the documentation or implementation.

But to be honest I use the first one quite often in application code since I'm lazy. In libraries I'm typically more thorough and follow the convention.

How to configure PostgreSQL to accept all incoming connections

Just use 0.0.0.0/0.

host    all             all             0.0.0.0/0            md5

Make sure the listen_addresses in postgresql.conf (or ALTER SYSTEM SET) allows incoming connections on all available IP interfaces.

listen_addresses = '*'

After the changes you have to reload the configuration. One way to do this is execute this SELECT as a superuser.

SELECT pg_reload_conf();

Note: to change listen_addresses, a reload is not enough, and you have to restart the server.

Reset par to the default values at startup

This is hacky, but:

resetPar <- function() {
    dev.new()
    op <- par(no.readonly = TRUE)
    dev.off()
    op
}

works after a fashion, but it does flash a new device on screen temporarily...

E.g.:

> par(mfrow = c(2,2)) ## some random par change
> par("mfrow")
[1] 2 2
> par(resetPar())     ## reset the pars to defaults
> par("mfrow")        ## back to default
[1] 1 1

JavaScript - get the first day of the week from current date

An example of the mathematically only calculation, without any Date functions.

_x000D_
_x000D_
const date = new Date();_x000D_
const ts = +date;_x000D_
_x000D_
const mondayTS = ts - ts % (60 * 60 * 24 * (7-4) * 1000);_x000D_
_x000D_
const monday = new Date(mondayTS);_x000D_
console.log(monday.toISOString(), 'Day:', monday.getDay());
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
const formatTS = v => new Date(v).toISOString();_x000D_
const adjust = (v, d = 1) => v - v % (d * 1000);_x000D_
_x000D_
const d = new Date('2020-04-22T21:48:17.468Z');_x000D_
const ts = +d; // 1587592097468_x000D_
_x000D_
const test = v => console.log(formatTS(adjust(ts, v)));_x000D_
_x000D_
test();                     // 2020-04-22T21:48:17.000Z_x000D_
test(60);                   // 2020-04-22T21:48:00.000Z_x000D_
test(60 * 60);              // 2020-04-22T21:00:00.000Z_x000D_
test(60 * 60 * 24);         // 2020-04-22T00:00:00.000Z_x000D_
test(60 * 60 * 24 * (7-4)); // 2020-04-20T00:00:00.000Z, monday_x000D_
_x000D_
// So, what does `(7-4)` mean?_x000D_
// 7 - days number in the week_x000D_
// 4 - shifting for the weekday number of the first second of the 1970 year, the first time stamp second._x000D_
//     new Date(0)          ---> 1970-01-01T00:00:00.000Z_x000D_
//     new Date(0).getDay() ---> 4
_x000D_
_x000D_
_x000D_

How to link home brew python version and set it as default

I think you have to be precise with which version you want to link with the command brew link python like:

brew link python 3

It will give you an error like that:

Linking /usr/local/Cellar/python3/3.5.2... 
Error: Could not symlink bin/2to3-3.5
Target /usr/local/bin/2to3-3.5
already exists. 

You may want to remove it:

rm '/usr/local/bin/2to3-3.5'

To force the link and overwrite all conflicting files:

brew link --overwrite python3

To list all files that would be deleted:

brew link --overwrite --dry-run python3

but you have to copy/paste the command to force the link which is:

brew link --overwrite python3

I think that you must have the version (the newer) installed.

HTML: how to make 2 tables with different CSS

Of course, just assign seperate css classes to both tables.

<table class="style1"></table>
<table class="style2"></table>

.css

table.style1 { //your css here}
table.style2 { //your css here}

How to completely remove Python from a Windows machine?

I had window 7 (64 bit) and Python 2.7.12, I uninstalled it by clicking the python installer from the "download" directory then I selected remove python then I clicked “ finish”.
I also removed the remaining python associated directory & files from the c: drive and also from “my documents” folder, since I created some files there.

How to dump raw RTSP stream to file?

You can use mplayer.

mencoder -nocache -rtsp-stream-over-tcp rtsp://192.168.XXX.XXX/test.sdp -oac copy -ovc copy -o test.avi

The "copy" codec is just a dumb copy of the stream. Mencoder adds a header and stuff you probably want.

In the mplayer source file "stream/stream_rtsp.c" is a prebuffer_size setting of 640k and no option to change the size other then recompile. The result is that writing the stream is always delayed, which can be annoying for things like cameras, but besides this, you get an output file, and can play it back most places without a problem.

React Hooks useState() with Object

, do it like this example :

first creat state of the objects:

const [isSelected, setSelection] = useState({ id_1: false }, { id_2: false }, { id_3: false });

then change the value on of them:

// if the id_1 is false make it true or return it false.

onValueChange={() => isSelected.id_1 == false ? setSelection({ ...isSelected, id_1: true }) : setSelection({ ...isSelected, id_1: false })}

How to include quotes in a string

The Code:

string myString = "Hello " + ((char)34) + " World." + ((char)34);

Output will be:

Hello "World."

What does status=canceled for a resource mean in Chrome Developer Tools?

status=canceled may happen also on ajax requests on JavaScript events:

<script>
  $("#call_ajax").on("click", function(event){
     $.ajax({
        ...    
     });
  });
</script>

<button id="call_ajax">call</button> 

The event successfully sends the request, but is is canceled then (but processed by the server). The reason is, the elements submit forms on click events, no matter if you make any ajax requests on the same click event.

To prevent request from being cancelled, JavaScript event.preventDefault(); have to be called:

<script>
  $("#call_ajax").on("click", function(event){
     event.preventDefault();
     $.ajax({
        ...    
     });
  });
</script>

How to use document.getElementByName and getElementByTag?

It's getElementsByName() and getElementsByTagName() - note the "s" in "Elements", indicating that both functions return a list of elements, i.e., a NodeList, which you will access like an array. Note that the second function ends with "TagName" not "Tag".

Even if the function only returns one element it will still be in a NodeList of length one. So:

var els = document.getElementsByName('frmMain');
// els.length will be the number of elements returned
// els[0] will be the first element returned
// els[1] the second, etc.

Assuming your form is the first (or only) form on the page you can do this:

document.getElementsByName('frmMain')[0].elements
document.getElementsByTagName('table')[0].elements

How do I add a reference to the MySQL connector for .NET?

This is an older question, but I found it yesterday while struggling with getting the MySQL Connector reference working properly on examples I'd found on the web. I'm working with VS 2010 on Win7 64 bit but have to work with .NET 3.5.

As others have stated, you need to download the .Net & Mono versions (I don't know why this is true, but it's what I've found works). The link to the connectors is given above in the earlier answers.

  • Extract the connectors somewhere convenient.
  • Open the project in Visual Studio, then on the menu bar navigate to Solution Explorer (View > Solution Explorer), and choose Properties (first box on the far left of the toolbar. The Solution Explorer shows up in the top right pane for me, but YMMV).
  • In Properties, select References & locate the instance for mysql.data. It's likely to have a yellow bang on it (Yellow triangle with exclamation point in it). Remove it.
  • Then on the menu bar, navigate to Project > Add Reference... > Browse > point to where you downloaded the connectors. I have only been able to get the V2 version to work, but that may be a factor of my platform, not sure.
  • Clean & build your application. You should now be able to use the MySQL connectors to talk to your database.
  • You can also now downgrade your .NET instance if you need to (we're constrained to .NET 3.5, but mysql.data.dll wants 4.0 at the time of my writing this). On the menu bar, navigate to the properties of your project (Project > Properties). Choose the Application tab > Target framework > Choose which .NET framework you want to use. You have to build the application at least once before you can change the .NET framework. Once you built once the connector will no longer complain about the lower version of .NET.

How to increase font size in a plot in R?

I came across this when I wanted to make the axis labels smaller, but leave everything else the same size. The command that worked for me, was to put:

par(cex.axis=0.5)

Before the plot command. Just remember to put:

par(cex.axis=1.0)

After the plot to make sure that the fonts go back to the default size.

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

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

        int transactionDate = 20201010;
        int? transactionTime = 210000;

        var agreementDate = DateTime.Today;
        var previousDate = agreementDate.AddDays(-1);

        var agreementHour = 22;
        var agreementMinute = 0;
        var agreementSecond = 0;

        var startDate = new DateTime(previousDate.Year, previousDate.Month, previousDate.Day, agreementHour, agreementMinute, agreementSecond);
        var endDate = new DateTime(agreementDate.Year, agreementDate.Month, agreementDate.Day, agreementHour, agreementMinute, agreementSecond);

        DateTime selectedDate = Convert.ToDateTime(transactionDate.ToString().Substring(6, 2) + "/" + transactionDate.ToString().Substring(4, 2) + "/" + transactionDate.ToString().Substring(0, 4) + " " + string.Format("{0:00:00:00}", transactionTime));

        Console.WriteLine("Selected Date : " + selectedDate.ToString());
        Console.WriteLine("Start Date : " + startDate.ToString());
        Console.WriteLine("End Date : " + endDate.ToString());

        if (selectedDate > startDate && selectedDate <= endDate)
            Console.WriteLine("Between two dates..");
        else if (selectedDate <= startDate)
            Console.WriteLine("Less than or equal to the start date!");
        else if (selectedDate > endDate)
            Console.WriteLine("Greater than end date!");
        else
            Console.WriteLine("Out of date ranges!");
    }
}

Scroll RecyclerView to show selected item on top

If you are using the LinearLayoutManager or Staggered GridLayoutManager, they each have a scrollToPositionWithOffset method that takes both the position and also the offset of the start of the item from the start of the RecyclerView, which seems like it would accomplish what you need (setting the offset to 0 should align with the top).

For instance:

//Scroll item 2 to 20 pixels from the top
linearLayoutManager.scrollToPositionWithOffset(2, 20);

PHP sessions that have already been started

If you want a new one, then do session_destroy() before starting it. To check if its set before starting it, call session_status() :

$status = session_status();
if($status == PHP_SESSION_NONE){
    //There is no active session
    session_start();
}else
if($status == PHP_SESSION_DISABLED){
    //Sessions are not available
}else
if($status == PHP_SESSION_ACTIVE){
    //Destroy current and start new one
    session_destroy();
    session_start();
}

I would avoid checking the global $_SESSION instead of I am calling the session_status() method since PHP implemented this function explicitly to:

Expose session status via new function, session_status This is for (PHP >=5.4.0)

SQL Server date format yyyymmdd

SELECT TO_CHAR(created_at, 'YYYY-MM-DD') FROM table; //converts any date format to YYYY-MM-DD

How to call a method in another class of the same package?

Methods are object methods or class methods.

Object methods: it applies over an object. You have to use an instance:

instance.method(args...);

Class methods: it applies over a class. It doesn't have an implicit instance. You have to use the class itself. It's more like procedural programming.

ClassWithStaticMethod.method(args...);

Reflection

With reflection you have an API to programmatically access methods, be they object or class methods.

Instance methods: methodRef.invoke(instance, args...); Class methods: methodRef.invoke(null, args...);

.Net: How do I find the .NET version?

clrver is an excellent one. Just execute it in the .NET prompt and it will list all available framework versions.

Java Webservice Client (Best way)

You can find some resources related to developing web services client using Apache axis2 here.

http://today.java.net/pub/a/today/2006/12/13/invoking-web-services-using-apache-axis2.html

Below posts gives good explanations about developing web services using Apache axis2.

http://www.ibm.com/developerworks/opensource/library/ws-webaxis1/

http://wso2.org/library/136

Sublime Text 3, convert spaces to tabs

Use the following command to get it solved :

autopep8 -i <filename>.py

How to format numbers by prepending 0 to single-digit numbers?

or

function zpad(n,l){
   return rep(l-n.toString().length, '0') + n.toString();
}

with

function rep(len, chr) { 
   return new Array(len+1).join(chr);
}

How to move text up using CSS when nothing is working

try a negative margin.

margin-top: -10px; /* as an example */

Calculating the area under a curve given a set of coordinates, without knowing the function

If you have sklearn isntalled, a simple alternative is to use sklearn.metrics.auc

This computes the area under the curve using the trapezoidal rule given arbitrary x, and y array

import numpy as np
from sklearn.metrics import auc

dx = 5
xx = np.arange(1,100,dx)
yy = np.arange(1,100,dx)

print('computed AUC using sklearn.metrics.auc: {}'.format(auc(xx,yy)))
print('computed AUC using np.trapz: {}'.format(np.trapz(yy, dx = dx)))

both output the same area: 4607.5

the advantage of sklearn.metrics.auc is that it can accept arbitrarily-spaced 'x' array, just make sure it is ascending otherwise the results will be incorrect

Has anyone ever got a remote JMX JConsole to work?

There are already some great answers here, but, there is a slightly simpler approach that I think it is worth sharing.

sushicutta's approach is good, but is very manual as you have to get the RMI Port every time. Thankfully, we can work around that by using a SOCKS proxy rather than explicitly opening the port tunnels. The downside of this approach is JMX app you run on your machine needs to be able to be configured to use a Proxy. Most processes you can do this from adding java properties, but, some apps don't support this.

Steps:

  1. Add the JMX options to the startup script for your remote Java service:

    -Dcom.sun.management.jmxremote=true
    -Dcom.sun.management.jmxremote.port=8090
    -Dcom.sun.management.jmxremote.ssl=false
    -Dcom.sun.management.jmxremote.authenticate=false
    
  2. Set up a SOCKS proxy connection to your remote machine:

    ssh -D 9696 [email protected]
    
  3. Configure your local Java monitoring app to use the SOCKS proxy (localhost:9696). Note: You can sometimes do this from the command line, i.e.:

    jconsole -J-DsocksProxyHost=localhost -J-DsocksProxyPort=9696
    

Vim: insert the same characters across multiple lines

I would use a macro to record my actions and would then repeat it.

  1. Put your cursor on the first letter in name.
  2. Hit qq to start recording into the q buffer.
  3. Hit i to go into insert mode, type vector_, and then hit Esc to leave insert mode.
  4. Now hit 0 to go back to the beginning of the line.
  5. Now hit j to go down.
  6. Now hit q again to stop recording.

You now have a nice macro.

Type 3@q to execute your macro three times to do the rest of the lines.

How to highlight a selected row in ngRepeat?

Each row has an ID. All you have to do is to send this ID to the function setSelected(), store it (in $scope.idSelectedVote for instance), and then check for each row if the selected ID is the same as the current one. Here is a solution (see the documentation for ngClass, if needed):

$scope.idSelectedVote = null;
$scope.setSelected = function (idSelectedVote) {
   $scope.idSelectedVote = idSelectedVote;
};
<ul ng-repeat="vote in votes" ng-click="setSelected(vote.id)" ng-class="{selected: vote.id === idSelectedVote}">
    ...
</ul>

Plunker

DataTables: Cannot read property 'length' of undefined

It can happen when your view property name and name inside column section of data table is not matching . Make sure that property name and column data name are matching

Error message: (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)

Adding this to my connection string worked for me:

Trusted_Connection=true

How can you have SharePoint Link Lists default to opening in a new window?

It is not possible with the default Link List web part, but there are resources describing how to extend Sharepoint server-side to add this functionality.

Share Point Links Open in New Window
Changing Link Lists in Sharepoint 2007

Android textview usage as label and value

You can use <LinearLayout> to group elements horizontaly. Also you should use style to set margins, background and other properties. This will allow you not to repeat code for every label you use. Here is an example:

<LinearLayout
                    style="@style/FormItem"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                <TextView
                        style="@style/FormLabel"
                        android:layout_width="wrap_content"
                        android:layout_height="@dimen/default_element_height"
                        android:text="@string/name_label"
                        />

                <EditText
                        style="@style/FormText.Editable"
                        android:id="@+id/cardholderName"
                        android:layout_width="wrap_content"
                        android:layout_height="@dimen/default_element_height"
                        android:layout_weight="1"
                        android:gravity="right|center_vertical"
                        android:hint="@string/card_name_hint"
                        android:imeOptions="actionNext"
                        android:singleLine="true"
                        />
            </LinearLayout>

Also you can create a custom view base on the layout above. Have you looked at Creating custom view ?

SELECT *, COUNT(*) in SQLite

count(*) is an aggregate function. Aggregate functions need to be grouped for a meaningful results. You can read: count columns group by

PDF to byte array and vice versa

You can do it by using Apache Commons IO without worrying about internal details.

Use org.apache.commons.io.FileUtils.readFileToByteArray(File file) which return data of type byte[].

Click here for Javadoc

Error 5 : Access Denied when starting windows service

I had this issue today on a service that I was developing, and none of the other suggestions on this question worked. In my case, I had a missing .dll dependency in the folder where the service ran from.

When I added the dependencies, the issue went away.

angularjs getting previous route path

In your html :

<a href="javascript:void(0);" ng-click="go_back()">Go Back</a>

On your main controller :

$scope.go_back = function() { 
  $window.history.back();
};

When user click on Go Back link the controller function is called and it will go back to previous route.

Android fastboot waiting for devices

try to use compiler generated fastboot when this happes. the file path is out/host/linux(or other)/bin/fastboot and sudo is also needed. it works in most of the time.

What is this date format? 2011-08-12T20:17:46.384Z

There are other ways to parse it rather than the first answer. To parse it:

(1) If you want to grab information about date and time, you can parse it to a ZonedDatetime(since Java 8) or Date(old) object:

// ZonedDateTime's default format requires a zone ID(like [Australia/Sydney]) in the end.
// Here, we provide a format which can parse the string correctly.
DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE_TIME;
ZonedDateTime zdt = ZonedDateTime.parse("2011-08-12T20:17:46.384Z", dtf);

or

// 'T' is a literal.
// 'X' is ISO Zone Offset[like +01, -08]; For UTC, it is interpreted as 'Z'(Zero) literal.
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX";

// since no built-in format, we provides pattern directly.
DateFormat df = new SimpleDateFormat(pattern);

Date myDate = df.parse("2011-08-12T20:17:46.384Z");

(2) If you don't care the date and time and just want to treat the information as a moment in nanoseconds, then you can use Instant:

// The ISO format without zone ID is Instant's default.
// There is no need to pass any format.
Instant ins = Instant.parse("2011-08-12T20:17:46.384Z");

What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

It is up to the browser but they behave in similar ways.

I have tested FF, IE7, Opera and Chrome.

F5 usually updates the page only if it is modified. The browser usually tries to use all types of cache as much as possible and adds an "If-modified-since" header to the request. Opera differs by sending a "Cache-Control: no-cache".

CTRL-F5 is used to force an update, disregarding any cache. IE7 adds an "Cache-Control: no-cache", as does FF, which also adds "Pragma: no-cache". Chrome does a normal "If-modified-since" and Opera ignores the key.

If I remember correctly it was Netscape which was the first browser to add support for cache-control by adding "Pragma: No-cache" when you pressed CTRL-F5.

Edit: Updated table

The table below is updated with information on what will happen when the browser's refresh-button is clicked (after a request by Joel Coehoorn), and the "max-age=0" Cache-control-header.

Updated table, 27 September 2010

+------------------------------------------------------------+
¦  UPDATED   ¦                Firefox 3.x                    ¦
¦27 SEP 2010 ¦  +--------------------------------------------¦
¦            ¦  ¦             MSIE 8, 7                      ¦
¦ Version 3  ¦  ¦  +-----------------------------------------¦
¦            ¦  ¦  ¦          Chrome 6.0                     ¦
¦            ¦  ¦  ¦  +--------------------------------------¦
¦            ¦  ¦  ¦  ¦       Chrome 1.0                     ¦
¦            ¦  ¦  ¦  ¦  +-----------------------------------¦
¦            ¦  ¦  ¦  ¦  ¦    Opera 10, 9                    ¦
¦            ¦  ¦  ¦  ¦  ¦  +--------------------------------¦
¦            ¦  ¦  ¦  ¦  ¦  ¦                                ¦
+------------+--+--+--+--+--+--------------------------------¦
¦          F5¦IM¦I ¦IM¦IM¦C ¦                                ¦
¦    SHIFT-F5¦- ¦- ¦CP¦IM¦- ¦ Legend:                        ¦
¦     CTRL-F5¦CP¦C ¦CP¦IM¦- ¦ I = "If-Modified-Since"        ¦
¦      ALT-F5¦- ¦- ¦- ¦- ¦*2¦ P = "Pragma: No-cache"         ¦
¦    ALTGR-F5¦- ¦I ¦- ¦- ¦- ¦ C = "Cache-Control: no-cache"  ¦
+------------+--+--+--+--+--¦ M = "Cache-Control: max-age=0" ¦
¦      CTRL-R¦IM¦I ¦IM¦IM¦C ¦ - = ignored                    ¦
¦CTRL-SHIFT-R¦CP¦- ¦CP¦- ¦- ¦                                ¦
+------------+--+--+--+--+--¦                                ¦
¦       Click¦IM¦I ¦IM¦IM¦C ¦ With 'click' I refer to a      ¦
¦ Shift-Click¦CP¦I ¦CP¦IM¦C ¦ mouse click on the browsers    ¦
¦  Ctrl-Click¦*1¦C ¦CP¦IM¦C ¦ refresh-icon.                  ¦
¦   Alt-Click¦IM¦I ¦IM¦IM¦C ¦                                ¦
¦ AltGr-Click¦IM¦I ¦- ¦IM¦- ¦                                ¦
+------------------------------------------------------------+

Versions tested:

  • Firefox 3.1.6 and 3.0.6 (WINXP)
  • MSIE 8.0.6001 and 7.0.5730.11 (WINXP)
  • Chrome 6.0.472.63 and 1.0.151.48 (WINXP)
  • Opera 10.62 and 9.61 (WINXP)

Notes:

  1. Version 3.0.6 sends I and C, but 3.1.6 opens the page in a new tab, making a normal request with only "I".

  2. Version 10.62 does nothing. 9.61 might do C unless it was a typo in my old table.

Note about Chrome 6.0.472: If you do a forced reload (like CTRL-F5) it behaves like the url is internally marked to always do a forced reload. The flag is cleared if you go to the address bar and press enter.

Python Requests - No connection adapters

One more reason, maybe your url include some hiden characters, such as '\n'.

If you define your url like below, this exception will raise:

url = '''
http://google.com
'''

because there are '\n' hide in the string. The url in fact become:

\nhttp://google.com\n

Python update a key in dict if it doesn't exist

With the following you can insert multiple values and also have default values but you're creating a new dictionary.

d = {**{ key: value }, **default_values}

I've tested it with the most voted answer and on average this is faster as it can be seen in the following example, .

Speed test comparing a for loop based method with a dict comprehension with unpack operator Speed test comparing a for loop based method with a dict comprehension with unpack operator method.

if no copy (d = default_vals.copy()) is made on the first case then the most voted answer would be faster once we reach orders of magnitude of 10**5 and greater. Memory footprint of both methods are the same.

python modify item in list, save back in list

You need to use the enumerate function: python docs

for place, item in enumerate(list):
    if "foo" in item:
        item = replace_all(item, replaceDictionary)
        list[place] = item
        print item

Also, it's a bad idea to use the word list as a variable, due to it being a reserved word in python.

Since you had problems with enumerate, an alternative from the itertools library:

for place, item in itertools.zip(itertools.count(0), list):
    if "foo" in item:
        item = replace_all(item, replaceDictionary)
        list[place] = item
        print item

Compare and contrast REST and SOAP web services?

SOAP uses WSDL for communication btw consumer and provider, whereas REST just uses XML or JSON to send and receive data

WSDL defines contract between client and service and is static by its nature. In case of REST contract is somewhat complicated and is defined by HTTP, URI, Media Formats and Application Specific Coordination Protocol. It's highly dynamic unlike WSDL.

SOAP doesn't return human readable result, whilst REST result is readable with is just plain XML or JSON

This is not true. Plain XML or JSON are not RESTful at all. None of them define any controls(i.e. links and link relations, method information, encoding information etc...) which is against REST as far as messages must be self contained and coordinate interaction between agent/client and service.

With links + semantic link relations clients should be able to determine what is next interaction step and follow these links and continue communication with service.

It is not necessary that messages be human readable, it's possible to use cryptic format and build perfectly valid REST applications. It doesn't matter whether message is human readable or not.

Thus, plain XML(application/xml) or JSON(application/json) are not sufficient formats for building REST applications. It's always reasonable to use subset of these generic media types which have strong semantic meaning and offer enough control information(links etc...) to coordinate interactions between client and server.

REST is over only HTTP

Not true, HTTP is most widely used and when we talk about REST web services we just assume HTTP. HTTP defines interface with it's methods(GET, POST, PUT, DELETE, PATCH etc) and various headers which can be used uniformly for interacting with resources. This uniformity can be achieved with other protocols as well.

P.S. Very simple, yet very interesting explanation of REST: http://www.looah.com/source/view/2284

SQL update query using joins

Let me just add a warning to all the existing answers:

When using the SELECT ... FROM syntax, you should keep in mind that it is proprietary syntax for T-SQL and is non-deterministic. The worst part is, that you get no warning or error, it just executes smoothly.

Full explanation with example is in the documentation:

Use caution when specifying the FROM clause to provide the criteria for the update operation. The results of an UPDATE statement are undefined if the statement includes a FROM clause that is not specified in such a way that only one value is available for each column occurrence that is updated, that is if the UPDATE statement is not deterministic.

How to convert int to date in SQL Server 2008

You have to first convert it into datetime, then to date.

Try this, it might be helpful:

Select Convert(DATETIME, LEFT(20130101, 8))

then convert to date.

Getting the current Fragment instance in the viewpager

I know its too late but I have really simple ways of doing it,

// for fragment at 0 possition

((mFragment) viewPager.getAdapter().instantiateItem(viewPager, 0)).yourMethod();

Can I force a page break in HTML printing?

Just wanted to put an update. page-break-after is a legacy property now.

Official page states

This property has been replaced by the break-after property.

How to add multiple classes to a ReactJS Component?

Just use a comma!

const useStyles = makeStyles((theme) => ({
 rightAlign: {
  display: 'flex',
  justifyContent: 'flex-end',
 },
 customSpacing: {
  marginTop: theme.spacing(2.5),
 },
)};

<div className={(classes.rightAlign, classes.customSpacing)}>Some code</div>

setImmediate vs. nextTick

I think I can illustrate this quite nicely. Since nextTick is called at the end of the current operation, calling it recursively can end up blocking the event loop from continuing. setImmediate solves this by firing in the check phase of the event loop, allowing event loop to continue normally.

   +-----------------------+
+->¦        timers         ¦
¦  +-----------------------+
¦  +-----------------------+
¦  ¦     I/O callbacks     ¦
¦  +-----------------------+
¦  +-----------------------+
¦  ¦     idle, prepare     ¦
¦  +-----------------------+      +---------------+
¦  +-----------------------+      ¦   incoming:   ¦
¦  ¦         poll          ¦<-----¦  connections, ¦
¦  +-----------------------+      ¦   data, etc.  ¦
¦  +-----------------------+      +---------------+
¦  ¦        check          ¦
¦  +-----------------------+
¦  +-----------------------+
+--¦    close callbacks    ¦
   +-----------------------+

source: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/

Notice that the check phase is immediately after the poll phase. This is because the poll phase and I/O callbacks are the most likely places your calls to setImmediate are going to run. So ideally most of those calls will actually be pretty immediate, just not as immediate as nextTick which is checked after every operation and technically exists outside of the event loop.

Let's take a look at a little example of the difference between setImmediate and process.nextTick:

function step(iteration) {
  if (iteration === 10) return;
  setImmediate(() => {
    console.log(`setImmediate iteration: ${iteration}`);
    step(iteration + 1); // Recursive call from setImmediate handler.
  });
  process.nextTick(() => {
    console.log(`nextTick iteration: ${iteration}`);
  });
}
step(0);

Let's say we just ran this program and are stepping through the first iteration of the event loop. It will call into the step function with iteration zero. It will then register two handlers, one for setImmediate and one for process.nextTick. We then recursively call this function from the setImmediate handler which will run in the next check phase. The nextTick handler will run at the end of the current operation interrupting the event loop, so even though it was registered second it will actually run first.

The order ends up being: nextTick fires as current operation ends, next event loop begins, normal event loop phases execute, setImmediate fires and recursively calls our step function to start the process all over again. Current operation ends, nextTick fires, etc.

The output of the above code would be:

nextTick iteration: 0
setImmediate iteration: 0
nextTick iteration: 1
setImmediate iteration: 1
nextTick iteration: 2
setImmediate iteration: 2
nextTick iteration: 3
setImmediate iteration: 3
nextTick iteration: 4
setImmediate iteration: 4
nextTick iteration: 5
setImmediate iteration: 5
nextTick iteration: 6
setImmediate iteration: 6
nextTick iteration: 7
setImmediate iteration: 7
nextTick iteration: 8
setImmediate iteration: 8
nextTick iteration: 9
setImmediate iteration: 9

Now let's move our recursive call to step into our nextTick handler instead of the setImmediate.

function step(iteration) {
  if (iteration === 10) return;
  setImmediate(() => {
    console.log(`setImmediate iteration: ${iteration}`);
  });
  process.nextTick(() => {
    console.log(`nextTick iteration: ${iteration}`);
    step(iteration + 1); // Recursive call from nextTick handler.
  });
}
step(0);

Now that we have moved the recursive call to step into the nextTick handler things will behave in a different order. Our first iteration of the event loop runs and calls step registering a setImmedaite handler as well as a nextTick handler. After the current operation ends our nextTick handler fires which recursively calls step and registers another setImmediate handler as well as another nextTick handler. Since a nextTick handler fires after the current operation, registering a nextTick handler within a nextTick handler will cause the second handler to run immediately after the current handler operation finishes. The nextTick handlers will keep firing, preventing the current event loop from ever continuing. We will get through all our nextTick handlers before we see a single setImmediate handler fire.

The output of the above code ends up being:

nextTick iteration: 0
nextTick iteration: 1
nextTick iteration: 2
nextTick iteration: 3
nextTick iteration: 4
nextTick iteration: 5
nextTick iteration: 6
nextTick iteration: 7
nextTick iteration: 8
nextTick iteration: 9
setImmediate iteration: 0
setImmediate iteration: 1
setImmediate iteration: 2
setImmediate iteration: 3
setImmediate iteration: 4
setImmediate iteration: 5
setImmediate iteration: 6
setImmediate iteration: 7
setImmediate iteration: 8
setImmediate iteration: 9

Note that had we not interrupted the recursive call and aborted it after 10 iterations then the nextTick calls would keep recursing and never letting the event loop continue to the next phase. This is how nextTick can become blocking when used recursively whereas setImmediate will fire in the next event loop and setting another setImmediate handler from within one won't interrupt the current event loop at all, allowing it to continue executing phases of the event loop as normal.

Hope that helps!

PS - I agree with other commenters that the names of the two functions could easily be swapped since nextTick sounds like it's going to fire in the next event loop rather than the end of the current one, and the end of the current loop is more "immediate" than the beginning of the next loop. Oh well, that's what we get as an API matures and people come to depend on existing interfaces.

Auto start print html page using javascript

<body onload="window.print()"> or window.onload = function() { window.print(); }

Disabling the button after once click

jQuery now has the .one() function that limits any given event (such as "submit") to one occurrence.

Example:

$('#myForm').one('submit', function() {
    $(this).find('input[type="submit"]').attr('disabled','disabled');
});

This code will let you submit the form once, then disable the button. Change the selector in the find() function to whatever button you'd like to disable.

Note: Per Francisco Goldenstein, I've changed the selector to the form and the event type to submit. This allows you to submit the form from anywhere (places other than the button) while still disabling the button on submit.

Note 2: Per gorelog, using attr('disabled','disabled') will prevent your form from sending the value of the submit button. If you want to pass the button value, use attr('onclick','this.style.opacity = "0.6"; return false;') instead.

Java character array initializer

You initialized and declared your String to "Hi there", initialized your char[] array with the correct size, and you began a loop over the length of the array which prints an empty string combined with a given element being looked at in the array. At which point did you factor in the functionality to put in the characters from the String into the array?

When you attempt to print each element in the array, you print an empty String, since you're adding 'nothing' to an empty String, and since there was no functionality to add in the characters from the input String to the array. You have everything around it correctly implemented, though. This is the code that should go after you initialize the array, but before the for-loop that iterates over the array to print out the elements.

for (int count = 0; count < ini.length(); count++) {
  array[count] = ini.charAt(count);
}

It would be more efficient to just combine the for-loops to print each character out right after you put it into the array.

for (int count = 0; count < ini.length(); count++) {
  array[count] = ini.charAt(count);
  System.out.println(array[count]);
}

At this point, you're probably wondering why even put it in a char[] when I can just print them using the reference to the String object ini itself.

String ini = "Hi there";

for (int count = 0; count < ini.length(); count++) {
   System.out.println(ini.charAt(count));
}

Definitely read about Java Strings. They're fascinating and work pretty well, in my opinion. Here's a decent link: https://www.javatpoint.com/java-string

String ini = "Hi there"; // stored in String constant pool

is stored differently in memory than

String ini = new String("Hi there"); // stored in heap memory and String constant pool

, which is stored differently than

char[] inichar = new char[]{"H", "i", " ", "t", "h", "e", "r", "e"};
String ini = new String(inichar); // converts from char array to string

.

Storing an object in state of a React component?

  1. this.setState({ abc.xyz: 'new value' }); syntax is not allowed. You have to pass the whole object.

    this.setState({abc: {xyz: 'new value'}});
    

    If you have other variables in abc

    var abc = this.state.abc;
    abc.xyz = 'new value';
    this.setState({abc: abc});
    
  2. You can have ordinary variables, if they don't rely on this.props and this.state.

Python urllib2 Basic Auth Problem

The problem could be that the Python libraries, per HTTP-Standard, first send an unauthenticated request, and then only if it's answered with a 401 retry, are the correct credentials sent. If the Foursquare servers don't do "totally standard authentication" then the libraries won't work.

Try using headers to do authentication:

import urllib2, base64

request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.b64encode('%s:%s' % (username, password))
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)

Had the same problem as you and found the solution from this thread: http://forums.shopify.com/categories/9/posts/27662

Joining 2 SQL SELECT result sets into one

SELECT table1.col_a, table1.col_b, table2.col_c 
  FROM table1 
  INNER JOIN table2 ON table1.col_a = table2.col_a

Creating an Array from a Range in VBA

Adding to @Vityata 's answer, below is the function I use to convert a row / column vector in a 1D array:

Function convertVecToArr(ByVal rng As Range) As Variant
'convert two dimension array into a one dimension array
    
    Dim arr() As Variant, slicedArr() As Variant
    arr = rng.value   'arr = rng works too (https://bettersolutions.com/excel/cells-ranges/vba-working-with-arrays.htm)
    
    If UBound(arr, 1) > UBound(arr, 2) Then
        slicedArr = Application.WorksheetFunction.Transpose(arr)
    Else
        slicedArr = Application.WorksheetFunction.index(arr, 1, 0)  'If you set row_num or column_num to 0 (zero), Index returns the array of values for the entire column or row, respectively._
                                                                   'To use values returned as an array, enter the Index function as an array formula in a horizontal range of cells for a row,_
                                                                   'and in a vertical range of cells for a column.
                                                                   'https://usefulgyaan.wordpress.com/2013/06/12/vba-trick-of-the-week-slicing-an-array-without-loop-application-index/
    End If
convertVecToArr = slicedArr
End Function

How to change the href for a hyperlink using jQuery

With jQuery 1.6 and above you should use:

$("a").prop("href", "http://www.jakcms.com")

The difference between prop and attr is that attr grabs the HTML attribute whereas prop grabs the DOM property.

You can find more details in this post: .prop() vs .attr()

jQuery - on change input text

This works for me on all browsers and Jquery <= v1.10

$('#kat').on('keyup', function () {
    alert("Hello");
});

or as it seems you want

$('#kat').on('click', function () {
    alert("Hello");
});

Textbox input field change event fires as you would expect it to, the jQuery .Change event only works correctly on html5 supported browsers

Center align "span" text inside a div

You are giving the span a 100% width resulting in it expanding to the size of the parent. This means you can’t center-align it, as there is no room to move it.

You could give the span a set width, then add the margin:0 auto again. This would center-align it.

.left 
{
   background-color: #999999;
   height: 50px;
   width: 24.5%;
}
span.panelTitleTxt 
{
   display:block;
   width:100px;
   height: 100%;
   margin: 0 auto;
}

How to override maven property in command line?

See Introduction to the POM

finalName is created as:

<build>
    <finalName>${project.artifactId}-${project.version}</finalName>
</build>

One of the solutions is to add own property:

<properties>
    <finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
    <finalName>${finalName}</finalName>
 </build>

And now try:

mvn -DfinalName=build clean package

Command line .cmd/.bat script, how to get directory of running script

for /F "eol= delims=~" %%d in ('CD') do set curdir=%%d

pushd %curdir%

Source

How to take last four characters from a varchar?

Right should do:

select RIGHT('abcdeffff',4)

How to display a json array in table format?

DEMO

var obj=[
        {
            id : "001",
            name : "apple",
            category : "fruit",
            color : "red"
        },
        {
            id : "002",
            name : "melon",
            category : "fruit",
            color : "green"
        },
        {
            id : "003",
            name : "banana",
            category : "fruit",
            color : "yellow"
        }
    ]
    var tbl=$("<table/>").attr("id","mytable");
    $("#div1").append(tbl);
    for(var i=0;i<obj.length;i++)
    {
        var tr="<tr>";
        var td1="<td>"+obj[i]["id"]+"</td>";
        var td2="<td>"+obj[i]["name"]+"</td>";
        var td3="<td>"+obj[i]["color"]+"</td></tr>";

       $("#mytable").append(tr+td1+td2+td3); 

    }   

Add hover text without javascript like we hover on a user's reputation

Use the title attribute, for example:

_x000D_
_x000D_
<div title="them's hoverin' words">hover me</div>
_x000D_
_x000D_
_x000D_

or:

_x000D_
_x000D_
<span title="them's hoverin' words">hover me</span>
_x000D_
_x000D_
_x000D_

What is the Difference Between read() and recv() , and Between send() and write()?

I just noticed recently that when I used write() on a socket in Windows, it almost works (the FD passed to write() isn't the same as the one passed to send(); I used _open_osfhandle() to get the FD to pass to write()). However, it didn't work when I tried to send binary data that included character 10. write() somewhere inserted character 13 before this. Changing it to send() with a flags parameter of 0 fixed that problem. read() could have the reverse problem if 13-10 are consecutive in the binary data, but I haven't tested it. But that appears to be another possible difference between send() and write().

With form validation: why onsubmit="return functionname()" instead of onsubmit="functionname()"?

HTML event handler code behaves like the body of a JavaScript function. Many languages such as C or Perl implicitly return the value of the last expression evaluated in the function body. JavaScript doesn't, it discards it and returns undefined unless you write an explicit returnEXPR.

CSS / HTML Navigation and Logo on same line

Firstly, let's use some semantic HTML.

<nav class="navigation-bar">
    <img class="logo" src="logo.png">
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">Projects</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Services</a></li>
        <li><a href="#">Get in Touch</a></li>
    </ul>
</nav>

In fact, you can even get away with the more minimalist:

<nav class="navigation-bar">
    <img class="logo" src="logo.png">
    <a href="#">Home</a>
    <a href="#">Projects</a>
    <a href="#">About</a>
    <a href="#">Services</a>
    <a href="#">Get in Touch</a>
</nav>

Then add some CSS:

.navigation-bar {
    width: 100%;  /* i'm assuming full width */
    height: 80px; /* change it to desired width */
    background-color: red; /* change to desired color */
}
.logo {
    display: inline-block;
    vertical-align: top;
    width: 50px;
    height: 50px;
    margin-right: 20px;
    margin-top: 15px;    /* if you want it vertically middle of the navbar. */
}
.navigation-bar > a {
    display: inline-block;
    vertical-align: top;
    margin-right: 20px;
    height: 80px;        /* if you want it to take the full height of the bar */
    line-height: 80px;    /* if you want it vertically middle of the navbar */
}

Obviously, the actual margins, heights and line-heights etc. depend on your design.

Other options are to use tables or floats for layout, but these are generally frowned upon.

Last but not least, I hope you get cured of div-itis.

Bash script to check running process

Despite some success with the /dev/null approach in bash. When I pushed the solution to cron it failed. Checking the size of a returned command worked perfectly though. The ampersrand allows bash to exit.

#!/bin/bash
SERVICE=/path/to/my/service
result=$(ps ax|grep -v grep|grep $SERVICE)
echo ${#result}
if  ${#result}> 0 
then
        echo " Working!"
else
        echo "Not Working.....Restarting"
        /usr/bin/xvfb-run -a /opt/python27/bin/python2.7 SERVICE &
fi

Enabling SSL with XAMPP

You can also configure your SSL in xampp/apache/conf/extra/httpd-vhost.conf like this:

<VirtualHost *:443>
    DocumentRoot C:/xampp/htdocs/yourProject
    ServerName yourProject.whatever
    SSLEngine on
    SSLCertificateFile "conf/ssl.crt/server.crt"
    SSLCertificateKeyFile "conf/ssl.key/server.key"
</VirtualHost>

I guess, it's better not change it in the httpd-ssl.conf if you have more than one project and you need SSL on more than one of them

Check variable equality against a list of values

You can write if(foo in L(10,20,30)) if you define L to be

var L = function()
{
    var obj = {};
    for(var i=0; i<arguments.length; i++)
        obj[arguments[i]] = null;

    return obj;
};

APT command line interface-like yes/no input?

One-liner with Python 3.8 and above:

while res:= input("When correct, press enter to continue...").lower() not in {'y','yes','Y','YES',''}: pass

How to use confirm using sweet alert?

_x000D_
_x000D_
document.querySelector('#from1').onsubmit = function(e){_x000D_
_x000D_
 swal({_x000D_
    title: "Are you sure?",_x000D_
    text: "You will not be able to recover this imaginary file!",_x000D_
    type: "warning",_x000D_
    showCancelButton: true,_x000D_
    confirmButtonColor: '#DD6B55',_x000D_
    confirmButtonText: 'Yes, I am sure!',_x000D_
    cancelButtonText: "No, cancel it!",_x000D_
    closeOnConfirm: false,_x000D_
    closeOnCancel: false_x000D_
 },_x000D_
 function(isConfirm){_x000D_
_x000D_
   if (isConfirm.value){_x000D_
     swal("Shortlisted!", "Candidates are successfully shortlisted!", "success");_x000D_
_x000D_
    } else {_x000D_
      swal("Cancelled", "Your imaginary file is safe :)", "error");_x000D_
         e.preventDefault();_x000D_
    }_x000D_
 });_x000D_
};
_x000D_
_x000D_
_x000D_

What is the best way to tell if a character is a letter or number in Java without using regexes?

As the answers indicate (if you examine them carefully!), your question is ambiguous. What do you mean by "an A-z letter" or a digit?

  • If you want to know if a character is a Unicode letter or digit, then use the Character.isLetter and Character.isDigit methods.

  • If you want to know if a character is an ASCII letter or digit, then the best thing to do is to test by comparing with the character ranges 'a' to 'z', 'A' to 'Z' and '0' to '9'.

Note that all ASCII letters / digits are Unicode letters / digits ... but there are many Unicode letters / digits characters that are not ASCII. For example, accented letters, cyrillic, sanskrit, ...


The general solution is to do this:

Character.UnicodeBlock block = Character.UnicodeBlock.of(someCodePoint);

and then test to see if the block is one of the ones that you are interested in. In some cases you will need to test for multiple blocks. For example, there are (at least) 4 code blocks for Cyrillic characters and 7 for Latin. The Character.UnicodeBlock class defines static constants for well-known blocks; see the javadocs.

Note that any code point will be in at most one block.

how to show alternate image if source image is not found? (onerror working in IE but not in mozilla)

I have got the solution for my query:

i have done something like this:

cell.innerHTML="<img height=40 width=40 alt='' src='<%=request.getContextPath()%>/writeImage.htm?' onerror='onImgError(this);' onLoad='setDefaultImage(this);'>"

function setDefaultImage(source){
        var badImg = new Image();
        badImg.src = "video.png";
        var cpyImg = new Image();
        cpyImg.src = source.src;

        if(!cpyImg.width)
        {
            source.src = badImg.src;
        }

    }


    function onImgError(source){
        source.src = "video.png";
        source.onerror = ""; 
        return true; 
    } 

This way it's working in all browsers.

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

If you are using management studio and have the query analyzer window open you can drag the table name to the query analyzer window and ... bingo! you get the table script. I've not tried this in SQL2008

how to find array size in angularjs

You can find the number of members in a Javascript array by using its length property:

var number = $scope.names.length;

Docs - Array.prototype.length

Add line break to 'git commit -m' from the command line

I don't see anyone mentioning that if you don't provide a message it will open nano for you (at least in Linux) where you can write multiple lines...

Only this is needed:

git commit

How to use a FolderBrowserDialog from a WPF application

You should be able to get an IWin32Window by by using PresentationSource.FromVisual and casting the result to HwndSource which implements IWin32Window.

Also in the comments here:

jQuery: read text file from file system

A workaround for this I used was to include the data as a js file, that implements a function returning the raw data as a string:

html:

<!DOCTYPE html>
<html>

<head>
  <script src="script.js"></script>
  <script type="text/javascript">
    function loadData() {
      // getData() will return the string of data...
      document.getElementById('data').innerHTML = getData().replace('\n', '<br>');
    }
  </script>
</head>

<body onload='loadData()'>
  <h1>check out the data!</h1>
  <div id='data'></div>
</body>

</html>

script.js:

// function wrapper, just return the string of data (csv etc)
function getData () {
    return 'look at this line of data\n\
oh, look at this line'
}

See it in action here- http://plnkr.co/edit/EllyY7nsEjhLMIZ4clyv?p=preview The downside is you have to do some preprocessing on the file to support multilines (append each line in the string with '\n\').

Setting Windows PowerShell environment variables

To be clear, the 1990's Windows way of click on Start, right click on This PC, and choose Properties, and then select Advanced system settings, and then in the dialog box that pops up, select Environment Variables, and in the list double clicking on PATH and then using the New, Edit, Move Up and Move Down all still work for changing the PATH. Power shell, and the rest of Windows get whatever you set here.

Yes you can use these new methods, but the old one still works. And at the base level all of the permanent change methods are controlled ways of editing your registry files.

Display only 10 characters of a long string?

If I understand correctly you want to limit a string to 10 characters?

var str = 'Some very long string';
if(str.length > 10) str = str.substring(0,10);

Something like that?

ReferenceError: $ is not defined

Your widget has Underscore.js/LoDash.js as dependency.

You can get them here: underscore, lodash

Try prepending this to your code, so you can see if it works:

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>

How can I set the max-width of a table cell using percentages?

I know this is literally a year later, but I figured I'd share. I was trying to do the same thing and came across this solution that worked for me. We set a max width for the entire table, then worked with the cell sizes for the desired effect.

Put the table in its own div, then set the width, min-width, and/or max-width of the div as desired for the entire table. Then, you can work and set width and min-widths for other cells, and max width for the div effectively working around and backwards to achieve the max width we wanted.

_x000D_
_x000D_
#tablediv {
    width:90%;
    min-width:800px
    max-width:1500px;
}

.tdleft {
    width:20%;
    min-width:200px;
}
_x000D_
<div id="tablediv">
  <table width="100%" border="1">
    <tr>
      <td class="tdleft">Test</td>
      <td>A long string blah blah blah</td>
    </tr>
  </table>
</div>
_x000D_
_x000D_
_x000D_

Admittedly, this does not give you a "max" width of a cell per se, but it does allow some control that might work in-lieu of such an option. Not sure if it will work for your needs. I know it worked for our situation where we want the navigation side in the page to scale up and down to a point but for all the wide screens these days.

How do I replace a character at a particular index in JavaScript?

This works similar to Array.splice:

String.prototype.splice = function (i, j, str) {
    return this.substr(0, i) + str + this.substr(j, this.length);
};

Fastest way to get the first n elements of a List into an Array

Assumption:

list - List<String>

Using Java 8 Streams,

  • to get first N elements from a list into a list,

    List<String> firstNElementsList = list.stream().limit(n).collect(Collectors.toList());

  • to get first N elements from a list into an Array,

    String[] firstNElementsArray = list.stream().limit(n).collect(Collectors.toList()).toArray(new String[n]);

nuget 'packages' element is not declared warning

This happens because VS doesn't know the schema of this file. Note that this file is more of an implementation detail, and not something you normally need to open directly. Instead, you can use the NuGet dialog to manage the packages installed in a project.

How to center form in bootstrap 3

I tried this and it worked

_x000D_
_x000D_
<div class="container">_x000D_
 <div class="row justify-content-center">_x000D_
  <div class="form-group col-md-4 col-md-offset-5 align-center ">_x000D_
       <input type="text" name="username" placeholder="Username" >_x000D_
  </div>_x000D_
 </div> _x000D_
</div>
_x000D_
_x000D_
_x000D_

How do you set your pythonpath in an already-created virtualenv?

It's already answered here -> Is my virtual environment (python) causing my PYTHONPATH to break?

UNIX/LINUX

Add "export PYTHONPATH=/usr/local/lib/python2.0" this to ~/.bashrc file and source it by typing "source ~/.bashrc" OR ". ~/.bashrc".

WINDOWS XP

1) Go to the Control panel 2) Double click System 3) Go to the Advanced tab 4) Click on Environment Variables

In the System Variables window, check if you have a variable named PYTHONPATH. If you have one already, check that it points to the right directories. If you don't have one already, click the New button and create it.

PYTHON CODE

Alternatively, you can also do below your code:-

import sys
sys.path.append("/home/me/mypy") 

Forking / Multi-Threaded Processes | Bash

haridsv's approach is great, it gives the flexibility to run a processor slots setup where a number of processes can be kept running with new jobs submitting as jobs complete, keeping the overall load up. Here are my mods to haridsv's code for an n-slot processor for a 'grid' of ngrid 'jobs' ( I use it for grids of simulation models ) Followed by test output for 8 jobs 3 at a time, with running totals of running, submitted, completed and remaining

#!/bin/bash
########################################################################
# see haridsv on forking-multi-threaded-processes-bash
# loop over grid, submitting jobs in the background.
# As jobs complete new ones are set going to keep the number running
# up to n as much as possible, until it tapers off at the end.
#
# 8 jobs
ngrid=8
# 3 at a time
n=3
# running counts
running=0
completed=0
# previous values
prunning=0
pcompleted=0
#
########################################################################
# process monitoring functions
#
declare -a pids
#
function checkPids() {
echo  ${#pids[@]}
if [ ${#pids[@]} -ne 0 ]
then
    echo "Checking for pids: ${pids[@]}"
    local range=$(eval echo {0..$((${#pids[@]}-1))})
    local i
    for i in $range; do
        if ! kill -0 ${pids[$i]} 2> /dev/null; then
            echo "Done -- ${pids[$i]}"
            unset pids[$i]
            completed=$(expr $completed + 1)
        fi
    done
    pids=("${pids[@]}") # Expunge nulls created by unset.
    running=$((${#pids[@]}))
    echo "#PIDS :"$running
fi
}
#
function addPid() {
    desc=$1
    pid=$2
    echo " ${desc} - "$pid
    pids=(${pids[@]} $pid)
}
########################################################################
#
# Loop and report when job changes happen,
# keep going until all are completed.
#
idx=0
while [ $completed -lt ${ngrid} ]
do
#
    if [ $running -lt $n ] && [ $idx -lt ${ngrid} ]
    then
####################################################################
#
# submit a new process if less than n
# are running and we haven't finished...
#
# get desc for process
#
        name="job_"${idx}
# background execution
        sleep 3 &
        addPid $name $!
        idx=$(expr $idx + 1)
#
####################################################################
#
    fi
#
    checkPids
# if something changes...
    if [ ${running} -gt ${prunning} ] || \
       [ ${completed} -gt ${pcompleted} ]
    then
        remain=$(expr $ngrid - $completed)
        echo  " Running: "${running}" Submitted: "${idx}\
              " Completed: "$completed" Remaining: "$remain
    fi
# save counts to prev values
    prunning=${running}
    pcompleted=${completed}
#
    sleep 1
#
done
#
########################################################################

Test output:

 job_0 - 75257
1
Checking for pids: 75257
#PIDS :1
 Running: 1 Submitted: 1  Completed: 0 Remaining: 8
 job_1 - 75262
2
Checking for pids: 75257 75262
#PIDS :2
 Running: 2 Submitted: 2  Completed: 0 Remaining: 8
 job_2 - 75267
3
Checking for pids: 75257 75262 75267
#PIDS :3
 Running: 3 Submitted: 3  Completed: 0 Remaining: 8
3
Checking for pids: 75257 75262 75267
Done -- 75257
#PIDS :2
 Running: 2 Submitted: 3  Completed: 1 Remaining: 7
 job_3 - 75277
3
Checking for pids: 75262 75267 75277
Done -- 75262
#PIDS :2
 Running: 2 Submitted: 4  Completed: 2 Remaining: 6
 job_4 - 75283
3
Checking for pids: 75267 75277 75283
Done -- 75267
#PIDS :2
 Running: 2 Submitted: 5  Completed: 3 Remaining: 5
 job_5 - 75289
3
Checking for pids: 75277 75283 75289
#PIDS :3
 Running: 3 Submitted: 6  Completed: 3 Remaining: 5
3
Checking for pids: 75277 75283 75289
Done -- 75277
#PIDS :2
 Running: 2 Submitted: 6  Completed: 4 Remaining: 4
 job_6 - 75298
3
Checking for pids: 75283 75289 75298
Done -- 75283
#PIDS :2
 Running: 2 Submitted: 7  Completed: 5 Remaining: 3
 job_7 - 75304
3
Checking for pids: 75289 75298 75304
Done -- 75289
#PIDS :2
 Running: 2 Submitted: 8  Completed: 6 Remaining: 2
2
Checking for pids: 75298 75304
#PIDS :2
2
Checking for pids: 75298 75304
Done -- 75298
#PIDS :1
 Running: 1 Submitted: 8  Completed: 7 Remaining: 1
1
Checking for pids: 75304
Done -- 75304
#PIDS :0
 Running: 0 Submitted: 8  Completed: 8 Remaining: 0

How does the Python's range function work?

A "for loop" in most, if not all, programming languages is a mechanism to run a piece of code more than once.

This code:

for i in range(5):
    print i

can be thought of working like this:

i = 0
print i
i = 1
print i
i = 2
print i
i = 3
print i
i = 4
print i

So you see, what happens is not that i gets the value 0, 1, 2, 3, 4 at the same time, but rather sequentially.

I assume that when you say "call a, it gives only 5", you mean like this:

for i in range(5):
    a=i+1
print a

this will print the last value that a was given. Every time the loop iterates, the statement a=i+1 will overwrite the last value a had with the new value.

Code basically runs sequentially, from top to bottom, and a for loop is a way to make the code go back and something again, with a different value for one of the variables.

I hope this answered your question.

Arithmetic overflow error converting numeric to data type numeric

My guess is that you're trying to squeeze a number greater than 99999.99 into your decimal fields. Changing it to (8,3) isn't going to do anything if it's greater than 99999.999 - you need to increase the number of digits before the decimal. You can do this by increasing the precision (which is the total number of digits before and after the decimal). You can leave the scale the same unless you need to alter how many decimal places to store. Try decimal(9,2) or decimal(10,2) or whatever.

You can test this by commenting out the insert #temp and see what numbers the select statement is giving you and see if they are bigger than your column can handle.

Can we update primary key values of a table?

It is commonly agreed that primary keys should be immutable (or as stable as possible since immutability can not be enforced in the DB). While there is nothing that will prevent you from updating a primary key (except integrity constraint), it may not be a good idea:

From a performance point of view:

  • You will need to update all foreign keys that reference the updated key. A single update can lead to the update of potentially lots of tables/rows.
  • If the foreign keys are unindexed (!!) you will have to maintain a lock on the children table to ensure integrity. Oracle will only hold the lock for a short time but still, this is scary.
  • If your foreign keys are indexed (as they should be), the update will lead to the update of the index (delete+insert in the index structure), this is generally more expensive than the actual update of the base table.
  • In ORGANIZATION INDEX tables (in other RDBMS, see clustered primary key), the rows are physically sorted by the primary key. A logical update will result in a physical delete+insert (more expensive)

Other considerations:

  • If this key is referenced in any external system (application cache, another DB, export...), the reference will be broken upon update.
  • additionaly, some RDBMS don't support CASCADE UPDATE, in particular Oracle.

In conclusion, during design, it is generally safer to use a surrogate key in lieu of a natural primary key that is supposed not to change -- but may eventually need to be updated because of changed requirements or even data entry error.

If you absolutely have to update a primary key with children table, see this post by Tom Kyte for a solution.

plot a circle with pyplot

I see plots with the use of (.circle) but based on what you might want to do you can also try this out:

import matplotlib.pyplot as plt
import numpy as np

x = list(range(1,6))
y = list(range(10, 20, 2))

print(x, y)

for i, data in enumerate(zip(x,y)):
    j, k = data
    plt.scatter(j,k, marker = "o", s = ((i+1)**4)*50, alpha = 0.3)

Simple concentric circle plot using linear progressing points

centers = np.array([[5,18], [3,14], [7,6]])
m, n = make_blobs(n_samples=20, centers=[[5,18], [3,14], [7,6]], n_features=2, 
cluster_std = 0.4)
colors = ['g', 'b', 'r', 'm']

plt.figure(num=None, figsize=(7,6), facecolor='w', edgecolor='k')
plt.scatter(m[:,0], m[:,1])

for i in range(len(centers)):

    plt.scatter(centers[i,0], centers[i,1], color = colors[i], marker = 'o', s = 13000, alpha = 0.2)
    plt.scatter(centers[i,0], centers[i,1], color = 'k', marker = 'x', s = 50)

plt.savefig('plot.png')

Circled points of a classification problem.

webpack command not working

I had to reinstall webpack to get it working with my local version of webpack, e.g:

$ npm uninstall webpack
$ npm i -D webpack

Change language of Visual Studio 2017 RC

  1. Go to Tools -> Options
  2. Select International Settings in Environment and on the right side of a screen you should see a combo with the list of installed language packages. (so in my case Czech, English and same as on MS Windows )
  3. Click on Ok

You have to restart Visual Studio to see the change...

If you are polish (and got polish language settings)

  1. Narzedzia -> Opcje
  2. Ustawienia miedzynarodowe in Srodowisko

Hope this helps! Have a great time in Poland!

HTML Tags in Javascript Alert() method

You can use all Unicode characters and the escape characters \n and \t. An example:

_x000D_
_x000D_
document.getElementById("test").onclick = function() {_x000D_
  alert(_x000D_
    'This is an alert with basic formatting\n\n' _x000D_
    + "\t• list item 1\n" _x000D_
    + '\t• list item 2\n' _x000D_
    + '\t• list item 3\n\n' _x000D_
    + '???????????????????????\n\n' _x000D_
    + 'Simple table\n\n' _x000D_
    + 'Char\t| Result\n' _x000D_
    + '\\n\t| line break\n' _x000D_
    + '\\t\t| tab space'_x000D_
  );_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<title>Alert formatting</title>_x000D_
<meta charset=utf-8>_x000D_
<button id=test>Click</button>
_x000D_
_x000D_
_x000D_

Result in Firefox:

screenshot Firefox

You get the same look in almost all browsers.

bind/unbind service example (android)

You can try using this code:

protected ServiceConnection mServerConn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        Log.d(LOG_TAG, "onServiceConnected");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(LOG_TAG, "onServiceDisconnected");
    }
}

public void start() {
    // mContext is defined upper in code, I think it is not necessary to explain what is it 
    mContext.bindService(intent, mServerConn, Context.BIND_AUTO_CREATE);
    mContext.startService(intent);
}

public void stop() {
    mContext.stopService(new Intent(mContext, ServiceRemote.class));
    mContext.unbindService(mServerConn);
}

How to write a simple Java program that finds the greatest common divisor between two numbers?

A recursive method would be:

static int gcd(int a, int b)
{
  if(a == 0 || b == 0) return a+b; // base case
  return gcd(b,a%b);
}

Using a while loop:

static int gcd(int a, int b)
{
  while(a!=0 && b!=0) // until either one of them is 0
  {
     int c = b;
     b = a%b;
     a = c;
  }
  return a+b; // either one is 0, so return the non-zero value
}

When I'm returning a+b, I'm actually returning the non-zero number assuming one of them is 0.

How to make a Bootstrap accordion collapse when clicking the header div?

I've noticed a couple of minor flaws in grim's jsfiddle.

To get the pointer to change to a hand for the whole of the panel use:

.panel-heading {
   cursor: pointer;
}

I've removed the <a> tag (a style issue) and kept data-toggle="collapse" data-parent="#accordion" data-target="#collapse..." on panel-heading throughout.

I've added a CSS method for displaying chevron, using font-awesome.css in my jsfiddle:

http://jsfiddle.net/weaversnap/7FqsX/1/

How to implement swipe gestures for mobile devices?

I made this function for my needs.

Feel free to use it. Works great on mobile devices.

function detectswipe(el,func) {
  swipe_det = new Object();
  swipe_det.sX = 0; swipe_det.sY = 0; swipe_det.eX = 0; swipe_det.eY = 0;
  var min_x = 30;  //min x swipe for horizontal swipe
  var max_x = 30;  //max x difference for vertical swipe
  var min_y = 50;  //min y swipe for vertical swipe
  var max_y = 60;  //max y difference for horizontal swipe
  var direc = "";
  ele = document.getElementById(el);
  ele.addEventListener('touchstart',function(e){
    var t = e.touches[0];
    swipe_det.sX = t.screenX; 
    swipe_det.sY = t.screenY;
  },false);
  ele.addEventListener('touchmove',function(e){
    e.preventDefault();
    var t = e.touches[0];
    swipe_det.eX = t.screenX; 
    swipe_det.eY = t.screenY;    
  },false);
  ele.addEventListener('touchend',function(e){
    //horizontal detection
    if ((((swipe_det.eX - min_x > swipe_det.sX) || (swipe_det.eX + min_x < swipe_det.sX)) && ((swipe_det.eY < swipe_det.sY + max_y) && (swipe_det.sY > swipe_det.eY - max_y) && (swipe_det.eX > 0)))) {
      if(swipe_det.eX > swipe_det.sX) direc = "r";
      else direc = "l";
    }
    //vertical detection
    else if ((((swipe_det.eY - min_y > swipe_det.sY) || (swipe_det.eY + min_y < swipe_det.sY)) && ((swipe_det.eX < swipe_det.sX + max_x) && (swipe_det.sX > swipe_det.eX - max_x) && (swipe_det.eY > 0)))) {
      if(swipe_det.eY > swipe_det.sY) direc = "d";
      else direc = "u";
    }

    if (direc != "") {
      if(typeof func == 'function') func(el,direc);
    }
    direc = "";
    swipe_det.sX = 0; swipe_det.sY = 0; swipe_det.eX = 0; swipe_det.eY = 0;
  },false);  
}

function myfunction(el,d) {
  alert("you swiped on element with id '"+el+"' to "+d+" direction");
}

To use the function just use it like

detectswipe('an_element_id',myfunction);

detectswipe('an_other_element_id',my_other_function);

If a swipe is detected the function "myfunction" is called with parameter element-id and "l,r,u,d" (left,right,up,down).

Example: http://jsfiddle.net/rvuayqeo/1/


I (UlysseBN) made a new version of this script based on this one which use more modern JavaScript, it looks like it behaves better on some cases. If you think it should rather be an edit of this answer let me know, if you are the original author and you end up editing, I'll delete my answer.

Add custom headers to WebView resource requests - android

You should be able to control all your headers by skipping loadUrl and writing your own loadPage using Java's HttpURLConnection. Then use the webview's loadData to display the response.

There is no access to the headers which Google provides. They are in a JNI call, deep in the WebView source.

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

Un-tick the Prevent saving changes that require table re-creation box from Tools ? Options ? Designers tab.

SQL Server 2012 example:

enter image description here

Change Color of Fonts in DIV (CSS)

Your first CSS selector—social.h2—is looking for the "social" element in the "h2", class, e.g.:

<social class="h2">

Class selectors are proceeded with a dot (.). Also, use a space () to indicate that one element is inside of another. To find an <h2> descendant of an element in the social class, try something like:

.social h2 {
  color: pink;
  font-size: 14px;
}

To get a better understanding of CSS selectors and how they are used to reference your HTML, I suggest going through the interactive HTML and CSS tutorials from CodeAcademy. I hope that this helps point you in the right direction.

How do you read a CSV file and display the results in a grid in Visual Basic 2010?

Consider this snippet of code. Modify as you see fit, or to fit your requirements. You'll need to have Imports statements for System.IO and System.Data.OleDb.

Dim fi As New FileInfo("c:\foo.csv")
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Text;Data Source=" & fi.DirectoryName

Dim conn As New OleDbConnection(connectionString)
conn.Open()

'the SELECT statement is important here, 
'and requires some formatting to pull dates and deal with headers with spaces.
Dim cmdSelect As New OleDbCommand("SELECT Foo, Bar, FORMAT(""SomeDate"",'YYYY/MM/DD') AS SomeDate, ""SOME MULTI WORD COL"", FROM " & fi.Name, conn)

Dim adapter1 As New OleDbDataAdapter
adapter1.SelectCommand = cmdSelect

Dim ds As New DataSet
adapter1.Fill(ds, "DATA")

myDataGridView.DataSource = ds.Tables(0).DefaultView 
myDataGridView.DataBind
conn.Close()

Generate random 5 characters string

Here are my random 5 cents ...

$random=function($a, $b) {
    return(
        substr(str_shuffle(('\\`)/|@'.
        password_hash(mt_rand(0,999999),
        PASSWORD_DEFAULT).'!*^&~(')),
        $a, $b)
    );
};

echo($random(0,5));

PHP's new password_hash() (* >= PHP 5.5) function is doing the job for generation of decently long set of uppercase and lowercase characters and numbers.

Two concat. strings before and after password_hash within $random function are suitable for change.

Paramteres for $random() *($a,$b) are actually substr() parameters. :)

NOTE: this doesn't need to be a function, it can be normal variable as well .. as one nasty singleliner, like this:

$random=(substr(str_shuffle(('\\`)/|@'.password_hash(mt_rand(0,999999), PASSWORD_DEFAULT).'!*^&~(')), 0, 5));

echo($random);

How do I get the Git commit count?

git shortlog by itself does not address the original question of total number of commits (not grouped by author)

That is true, and git rev-list HEAD --count remains the simplest answer.

However, with Git 2.29 (Q4 2020), "git shortlog"(man) has become more precise.
It has been taught to group commits by the contents of the trailer lines, like "Reviewed-by:", "Coauthored-by:", etc.

See commit 63d24fa, commit 56d5dde, commit 87abb96, commit f17b0b9, commit 47beb37, commit f0939a0, commit 92338c4 (27 Sep 2020), and commit 45d93eb (25 Sep 2020) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 2fa8aac, 04 Oct 2020)

shortlog: allow multiple groups to be specified

Signed-off-by: Jeff King

Now that shortlog supports reading from trailers, it can be useful to combine counts from multiple trailers, or between trailers and authors.
This can be done manually by post-processing the output from multiple runs, but it's non-trivial to make sure that each name/commit pair is counted only once.

This patch teaches shortlog to accept multiple --group options on the command line, and pull data from all of them.

That makes it possible to run:

git shortlog -ns --group=author --group=trailer:co-authored-by  

to get a shortlog that counts authors and co-authors equally.

The implementation is mostly straightforward. The "group" enum becomes a bitfield, and the trailer key becomes a list.
I didn't bother implementing the multi-group semantics for reading from stdin. It would be possible to do, but the existing matching code makes it awkward, and I doubt anybody cares.

The duplicate suppression we used for trailers now covers authors and committers as well (though in non-trailer single-group mode we can skip the hash insertion and lookup, since we only see one value per commit).

There is one subtlety: we now care about the case when no group bit is set (in which case we default to showing the author).
The caller in builtin/log.c needs to be adapted to ask explicitly for authors, rather than relying on shortlog_init(). It would be possible with some gymnastics to make this keep working as-is, but it's not worth it for a single caller.

git shortlog now includes in its man page:

--group=<type>

Group commits based on <type>. If no --group option is specified, the default is author. <type> is one of:

  • author, commits are grouped by author
  • committer, commits are grouped by committer (the same as -c)

This is an alias for --group=committer.

git shortlog now also includes in its man page:

If --group is specified multiple times, commits are counted under each value (but again, only once per unique value in that commit). For example, git shortlog --group=author --group=trailer:co-authored-by counts both authors and co-authors.

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

Make sure to target x86 on your project in Visual Studio. This should fix your trouble.

Regex Last occurrence?

A negative look ahead is a correct answer, but it can be written more cleanly like:

(\\)(?!.*\\)

This looks for an occurrence of \ and then in a check that does not get matched, it looks for any number of characters followed by the character you don't want to see after it. Because it's negative, it only matches if it does not find a match.

How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

The warning comes up because Tomcat scans all Jars for TLDs (Tagging Library Definitions).

Step1: To see which JARs are throwing up this warning, insert he following line to tomcat/conf/logging.properties

org.apache.jasper.servlet.TldScanner.level = FINE

Now you should be able to see warnings with a detail of which JARs are causing the intial warning

Step2 Since skipping unneeded JARs during scanning can improve startup time and JSP compilation time, we will skip un-needed JARS in the catalina.properties file. You have two options here -

  1. List all the JARs under the tomcat.util.scan.StandardJarScanFilter.jarsToSkip. But this can get cumbersome if you have a lot jars or if the jars keep changing.
  2. Alternatively, Insert tomcat.util.scan.StandardJarScanFilter.jarsToSkip=* to skip all the jars

You should now not see the above warnings and if you have a considerably large application, it should save you significant time in deploying an application.

Note: Tested in Tomcat8

How to allow CORS in react.js?

Possible repeated question from How to overcome the CORS issue in ReactJS

CORS works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. This must be configured in the server to allow cross domain.

You can temporary solve this issue by a chrome plugin called CORS.

How to resize an image to fit in the browser window?

html, body{width: 99%; height: 99%; overflow: hidden}
img.fit{width: 100%; height: 100%;}

Or maybe check this out: http://css-tricks.com/how-to-resizeable-background-image/

Using group by and having clause

The semantics of Having

To better understand having, you need to see it from a theoretical point of view.

A group by is a query that takes a table and summarizes it into another table. You summarize the original table by grouping the original table into subsets (based upon the attributes that you specify in the group by). Each of these groups will yield one tuple.

The Having is simply equivalent to a WHERE clause after the group by has executed and before the select part of the query is computed.

Lets say your query is:

select a, b, count(*) 
from Table 
where c > 100 
group by a, b 
having count(*) > 10;

The evaluation of this query can be seen as the following steps:

  1. Perform the WHERE, eliminating rows that do not satisfy it.
  2. Group the table into subsets based upon the values of a and b (each tuple in each subset has the same values of a and b).
  3. Eliminate subsets that do not satisfy the HAVING condition
  4. Process each subset outputting the values as indicated in the SELECT part of the query. This creates one output tuple per subset left after step 3.

You can extend this to any complex query there Table can be any complex query that return a table (a cross product, a join, a UNION, etc).

In fact, having is syntactic sugar and does not extend the power of SQL. Any given query:

SELECT list 
FROM table
GROUP BY attrList
HAVING condition;

can be rewritten as:

SELECT list from (
   SELECT listatt 
   FROM table 
   GROUP BY attrList) as Name
WHERE condition;

The listatt is a list that includes the GROUP BY attributes and the expressions used in list and condition. It might be necessary to name some expressions in this list (with AS). For instance, the example query above can be rewritten as:

select a, b, count 
from (select a, b, count(*) as count
      from Table 
      where c > 100
      group by a, b) as someName
where count > 10;

The solution you need

Your solution seems to be correct:

SELECT s.sid, s.name
FROM Supplier s, Supplies su, Project pr
WHERE s.sid = su.sid AND su.jid = pr.jid
GROUP BY s.sid, s.name
HAVING COUNT (DISTINCT pr.jid) >= 2 

You join the three tables, then using sid as a grouping attribute (sname is functionally dependent on it, so it does not have an impact on the number of groups, but you must include it, otherwise it cannot be part of the select part of the statement). Then you are removing those that do not satisfy your condition: the satisfy pr.jid is >= 2, which is that you wanted originally.

Best solution to your problem

I personally prefer a simpler cleaner solution:

  1. You need to only group by Supplies (sid, pid, jid**, quantity) to find the sid of those that supply at least to two projects.
  2. Then join it to the Suppliers table to get the supplier same.

 SELECT sid, sname from
    (SELECT sid from supplies 
    GROUP BY sid, pid 
    HAVING count(DISTINCT jid) >= 2
    ) AS T1
NATURAL JOIN 
Supliers;

It will also be faster to execute, because the join is only done when needed, not all the times.

--dmg

ASP.NET MVC - passing parameters to the controller

you can change firstItem to id and it will work

you can change the routing on global.asax (i do not recommed that)

and, can't believe no one mentioned this, you can call :

http://localhost:2316/Inventory/ViewStockNext?firstItem=11

In a @Url.Action would be :

@Url.Action("ViewStockNext", "Inventory", new {firstItem=11});

depending on the type of what you are doing, the last will be more suitable. Also you should consider not doing ViewStockNext action and instead a ViewStock action with index. (my 2cents)

Eclipse reported "Failed to load JNI shared library"

Installing a 64-bit version of Java will solve the issue. Go to page Java Downloads for All Operating Systems

This is a problem due to the incompatibility of the Java version and the Eclipse version both should be 64 bit if you are using a 64-bit system.

How do I use raw_input in Python 3

As others have indicated, the raw_input function has been renamed to input in Python 3.0, and you really would be better served by a more up-to-date book, but I want to point out that there are better ways to see the output of your script.

From your description, I think you're using Windows, you've saved a .py file and then you're double-clicking on it to run it. The terminal window that pops up closes as soon as your program ends, so you can't see what the result of your program was. To solve this, your book recommends adding a raw_input / input statement to wait until the user presses enter. However, as you've seen, if something goes wrong, such as an error in your program, that statement won't be executed and the window will close without you being able to see what went wrong. You might find it easier to use a command-prompt or IDLE.

Use a command-prompt

When you're looking at the folder window that contains your Python program, hold down shift and right-click anywhere in the white background area of the window. The menu that pops up should contain an entry "Open command window here". (I think this works on Windows Vista and Windows 7.) This will open a command-prompt window that looks something like this:

    Microsoft Windows [Version 6.1.7601]
    Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

    C:\Users\Weeble\My Python Program>_

To run your program, type the following (substituting your script name):

    python myscript.py

...and press enter. (If you get an error that "python" is not a recognized command, see http://showmedo.com/videotutorials/video?name=960000&fromSeriesID=96 ) When your program finishes running, whether it completes successfully or not, the window will remain open and the command-prompt will appear again for you to type another command. If you want to run your program again, you can press the up arrow to recall the previous command you entered and press enter to run it again, rather than having to type out the file name every time.

Use IDLE

IDLE is a simple program editor that comes installed with Python. Among other features it can run your programs in a window. Right-click on your .py file and choose "Edit in IDLE". When your program appears in the editor, press F5 or choose "Run module" from the "Run" menu. Your program will run in a window that stays open after your program ends, and in which you can enter Python commands to run immediately.

Getting a count of rows in a datatable that meet certain criteria

Not sure if this is faster, but at least it's shorter :)

int rows = new DataView(dtFoo, "IsActive = 'Y'", "IsActive",
    DataViewRowState.CurrentRows).Table.Rows.Count;

C# Public Enums in Classes

You need to define the enum outside of the class.

public enum card_suits
{
    Clubs,
    Hearts,
    Spades,
    Diamonds
}

public class Card
{
     // ...

That being said, you may also want to consider using the standard naming guidelines for Enums, which would be CardSuit instead of card_suits, since Pascal Casing is suggested, and the enum is not marked with the FlagsAttribute, suggesting multiple values are appropriate in a single variable.

How to add headers to OkHttp request interceptor?

you can do it this way

private String GET(String url, Map<String, String> header) throws IOException {
        Headers headerbuild = Headers.of(header);
        Request request = new Request.Builder().url(url).headers(headerbuild).
                        build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

jQuery Validation using the class instead of the name value

Here's my solution (requires no jQuery... just JavaScript):

function argsToArray(args) {
  var r = []; for (var i = 0; i < args.length; i++)
    r.push(args[i]);
  return r;
}
function bind() {
  var initArgs = argsToArray(arguments);
  var fx =        initArgs.shift();
  var tObj =      initArgs.shift();
  var args =      initArgs;
  return function() {
    return fx.apply(tObj, args.concat(argsToArray(arguments)));
  };
}
var salutation = argsToArray(document.getElementsByClassName('salutation'));
salutation.forEach(function(checkbox) {
  checkbox.addEventListener('change', bind(function(checkbox, salutation) {
    var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
    if (numChecked >= 4)
      checkbox.checked = false;
  }, null, checkbox, salutation), false);
});

Put this in a script block at the end of <body> and the snippet will do its magic, limiting the number of checkboxes checked in maximum to three (or whatever number you specify).

Here, I'll even give you a test page (paste it into a file and try it):

<!DOCTYPE html><html><body>
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<script>
    function argsToArray(args) {
      var r = []; for (var i = 0; i < args.length; i++)
        r.push(args[i]);
      return r;
    }
    function bind() {
      var initArgs = argsToArray(arguments);
      var fx =        initArgs.shift();
      var tObj =      initArgs.shift();
      var args =      initArgs;
      return function() {
        return fx.apply(tObj, args.concat(argsToArray(arguments)));
      };
    }
    var salutation = argsToArray(document.getElementsByClassName('salutation'));
    salutation.forEach(function(checkbox) {
      checkbox.addEventListener('change', bind(function(checkbox, salutation) {
        var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
        if (numChecked >= 3)
          checkbox.checked = false;
      }, null, checkbox, salutation), false);
    });
</script></body></html>

PHP - Notice: Undefined index:

You're getting errors because you're attempting to read post variables that haven't been set, they only get set on form submission. Wrap your php code at the bottom in an

if ($_SERVER['REQUEST_METHOD'] === 'POST') { ... }

Also, your code is ripe for SQL injection. At the very least use mysql_real_escape_string on the post vars before using them in SQL queries. mysql_real_escape_string is not good enough for a production site, but should score you extra points in class.

When does socket.recv(recv_size) return?

Yes, your conclusion is correct. socket.recv is a blocking call.

socket.recv(1024) will read at most 1024 bytes, blocking if no data is waiting to be read. If you don't read all data, an other call to socket.recv won't block.

socket.recv will also end with an empty string if the connection is closed or there is an error.

If you want a non-blocking socket, you can use the select module (a bit more complicated than just using sockets) or you can use socket.setblocking.

I had issues with socket.setblocking in the past, but feel free to try it if you want.

Laravel: Using try...catch with DB::transaction()

In the case you need to manually 'exit' a transaction through code (be it through an exception or simply checking an error state) you shouldn't use DB::transaction() but instead wrap your code in DB::beginTransaction and DB::commit/DB::rollback():

DB::beginTransaction();

try {
    DB::insert(...);
    DB::insert(...);
    DB::insert(...);

    DB::commit();
    // all good
} catch (\Exception $e) {
    DB::rollback();
    // something went wrong
}

See the transaction docs.

How do I import/include MATLAB functions?

If the folder just contains functions then adding the folders to the path at the start of the script will suffice.

addpath('../folder_x/');
addpath('../folder_y/');

If they are Packages, folders starting with a '+' then they also need to be imported.

import package_x.*
import package_y.*

You need to add the package folders parent to the search path.

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

For me, these two things helped on different occasions:

1) If you've just installed the MS Access runtime, reboot the server. Bouncing the database instance isn't enough.

2) As well as making sure the Excel file isn't open, check you haven't got Windows Explorer open with the preview pane switched on - that locks it too.

How to speed up insertion performance in PostgreSQL

I encountered this insertion performance problem as well. My solution is spawn some go routines to finish the insertion work. In the meantime, SetMaxOpenConns should be given a proper number otherwise too many open connection error would be alerted.

db, _ := sql.open() 
db.SetMaxOpenConns(SOME CONFIG INTEGER NUMBER) 
var wg sync.WaitGroup
for _, query := range queries {
    wg.Add(1)
    go func(msg string) {
        defer wg.Done()
        _, err := db.Exec(msg)
        if err != nil {
            fmt.Println(err)
        }
    }(query)
}
wg.Wait()

The loading speed is much faster for my project. This code snippet just gave an idea how it works. Readers should be able to modify it easily.

Read remote file with node.js (http.get)

http.get(options).on('response', function (response) {
    var body = '';
    var i = 0;
    response.on('data', function (chunk) {
        i++;
        body += chunk;
        console.log('BODY Part: ' + i);
    });
    response.on('end', function () {

        console.log(body);
        console.log('Finished');
    });
});

Changes to this, which works. Any comments?

Checking whether the pip is installed?

If you are on a linux machine running Python 2 you can run this commands:

1st make sure python 2 is installed:

python2 --version

2nd check to see if pip is installed:

pip --version

If you are running Python 3 you can run this command:

1st make sure python 3 is installed:

python3 --version

2nd check to see if pip3 is installed:

pip3 --version

If you do not have pip installed you can run these commands to install pip (it is recommended you install pip for Python 2 and Python 3):

Install pip for Python 2:

sudo apt install python-pip

Then verify if it is installed correctly:

pip --version

Install pip for Python 3:

sudo apt install python3-pip

Then verify if it is installed correctly:

pip3 --version

For more info see: https://itsfoss.com/install-pip-ubuntu/

UPDATE I would like to mention a few things. When working with Django I learned that my Linux install requires me to use python 2.7, so switching my default python version for the python and pip command alias's to python 3 with alias python=python3 is not recommended. Therefore I use the python3 and pip3 commands when installing software like Django 3.0, which works better with Python 3. And I keep their alias's pointed towards whatever Python 3 version I want like so alias python3=python3.8.

Keep In Mind When you are going to use your package in the future you will want to use the pip or pip3 command depending on which one you used to initially install the package. So for example if I wanted to change my change my Django package version I would use the pip3 command and not pip like so, pip3 install Django==3.0.11.

Notice When running checking the packages version for python: $ python -m django --version and python3: $ python3 -m django --version, two different versions of django will show because I installed django v3.0.11 with pip3 and django v1.11.29 with pip.

Calculating a directory's size using Python?

This walks all sub-directories; summing file sizes:

import os

def get_size(start_path = '.'):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            # skip if it is symbolic link
            if not os.path.islink(fp):
                total_size += os.path.getsize(fp)

    return total_size

print(get_size(), 'bytes')

And a oneliner for fun using os.listdir (Does not include sub-directories):

import os
sum(os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f))

Reference:

Updated To use os.path.getsize, this is clearer than using the os.stat().st_size method.

Thanks to ghostdog74 for pointing this out!

os.stat - st_size Gives the size in bytes. Can also be used to get file size and other file related information.

import os

nbytes = sum(d.stat().st_size for d in os.scandir('.') if d.is_file())

Update 2018

If you use Python 3.4 or previous then you may consider using the more efficient walk method provided by the third-party scandir package. In Python 3.5 and later, this package has been incorporated into the standard library and os.walk has received the corresponding increase in performance.

Update 2019

Recently I've been using pathlib more and more, here's a pathlib solution:

from pathlib import Path

root_directory = Path('.')
sum(f.stat().st_size for f in root_directory.glob('**/*') if f.is_file())

Pure css close button

Edit: Updated css to match with what you have..

DEMO

HTML

<div>
    <span class="close-btn"><a href="#">X</a></span>
</div>

CSS

.close-btn {
    border: 2px solid #c2c2c2;
    position: relative;
    padding: 1px 5px;
    top: -20px;
    background-color: #605F61;
    left: 198px;
    border-radius: 20px;
}

.close-btn a {
    font-size: 15px;
    font-weight: bold;
    color: white;
    text-decoration: none;
}

Node.js Logging

Winston is a pretty good logging library. You can write logs out to a file using it.

Code would look something like:

var winston = require('winston');

var logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)({ json: false, timestamp: true }),
    new winston.transports.File({ filename: __dirname + '/debug.log', json: false })
  ],
  exceptionHandlers: [
    new (winston.transports.Console)({ json: false, timestamp: true }),
    new winston.transports.File({ filename: __dirname + '/exceptions.log', json: false })
  ],
  exitOnError: false
});

module.exports = logger;

You can then use this like:

var logger = require('./log');

logger.info('log to file');

How to Display blob (.pdf) in an AngularJS app

A suggestion of code that I just used in my project using AngularJS v1.7.2

$http.get('LabelsPDF?ids=' + ids, { responseType: 'arraybuffer' })
            .then(function (response) {
                var file = new Blob([response.data], { type: 'application/pdf' });
                var fileURL = URL.createObjectURL(file);
                $scope.ContentPDF = $sce.trustAsResourceUrl(fileURL);
            });

<embed ng-src="{{ContentPDF}}" type="application/pdf" class="col-xs-12" style="height:100px; text-align:center;" />

how to activate a textbox if I select an other option in drop down box

Below is the core JavaScript you need to write:

<html> 
<head>  
<script type="text/javascript">
function CheckColors(val){
 var element=document.getElementById('color');
 if(val=='pick a color'||val=='others')
   element.style.display='block';
 else  
   element.style.display='none';
}

</script> 
</head>
<body>
  <select name="color" onchange='CheckColors(this.value);'> 
    <option>pick a color</option>  
    <option value="red">RED</option>
    <option value="blue">BLUE</option>
    <option value="others">others</option>
  </select>
<input type="text" name="color" id="color" style='display:none;'/>
</body>
</html>

Permission denied error while writing to a file in Python

If you are executing the python script via terminal pass --user to provide admin permissions.

Worked for me!

If you are using windows run the file as admin.

If you are executing via cmd, run cmd as admin and execute the python script.

Repeat a task with a time delay?

Using kotlin and its Coroutine its quite easy, first declare a job in your class (better in your viewModel) like this:

private var repeatableJob: Job? = null

then when you want to create and start it do this:

repeatableJob = viewModelScope.launch {
    while (isActive) {
         delay(5_000)
         loadAlbums(iImageAPI, titleHeader, true)
    }
}
repeatableJob?.start()

and if you want to finish it:

repeatableJob?.cancel()

PS: viewModelScope is only available in view models, you can use other Coroutine scopes such as withContext(Dispatchers.IO)

More information: Here

Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'"

This worked for me.

pip3 install --user package-name  # for Python3
pip install --user package-name   # for Python2

The --user flag tells Python to install in the user home directory. By default it will go to system locations. credit

How to Call a JS function using OnClick event

You are attempting to attach an event listener function before the element is loaded. Place fun() inside an onload event listener function. Call f1() within this function, as the onclick attribute will be ignored.

function f1() {
    alert("f1 called");
    //form validation that recalls the page showing with supplied inputs.    
}
window.onload = function() {
    document.getElementById("Save").onclick = function fun() {
        alert("hello");
        f1();
        //validation code to see State field is mandatory.  
    }
}

JSFiddle

VBA check if object is set

If obj Is Nothing Then
    ' need to initialize obj: '
    Set obj = ...
Else
    ' obj already set / initialized. '
End If

Or, if you prefer it the other way around:

If Not obj Is Nothing Then
    ' obj already set / initialized. '
Else
    ' need to initialize obj: '
    Set obj = ...
End If

MongoDB - admin user not authorized

It's a bit confusing - I believe you will need to grant yourself readWrite to query a database. A user with dbadmin or useradmin can admin the database (including granting yourself additional rights) but cannot perform queries or write data.

so grant yourself readWrite and you should be fine -

http://docs.mongodb.org/manual/reference/built-in-roles/#readWrite

VBA: Selecting range by variables

I ran into something similar - I wanted to create a range based on some variables. Using the Worksheet.Cells did not work directly since I think the cell's values were passed to Range.

This did work though:

Range(Cells(1, 1).Address(), Cells(lastRow, lastColumn).Address()).Select

That took care of converting the cell's numerical location to what Range expects, which is the A1 format.

1 = false and 0 = true?

I suspect it's just following the Linux / Unix standard for returning 0 on success.

Does it really say "1" is false and "0" is true?

How do I increase the scrollback buffer in a running screen session?

There is a minimal amount of "default" buffer when you startup a 'screen' session within your 'putty session'. I use screens a lot in my work, so I can tell you that you will not have a combination of 'screen' buffer & 'putty' buffer within your 'screen' session.

Setting the default number of scrollback lines by adding defscrollback 10000 to your ~/.screenrc file is the correct solution.

By the way, I use "defscrollback 200000" in my ./screenrc file.

How do I convert a list into a string with spaces in Python?

For Non String list we can do like this as well

" ".join(map(str, my_list))

How to check string length with JavaScript

 var myString = 'sample String';   var length = myString.length ;

first you need to defined a keypressed handler or some kind of a event trigger to listen , btw , getting the length is really simple like mentioned above

How to align an indented line in a span that wraps into multiple lines?

try to add display: block; (or replace the <span> by a <div>) (note that this could cause other problems becuase a <span> is inline by default - but you havn't posted the rest of your html)

Attach (open) mdf file database with SQL Server Management Studio

You may need to repair your mdf file first using some tools. There are lot of tool available in the market. There is tool called SQL Database Recovery Tool Repairs which is very useful to repair the mdf files.

The issue might me because of corrupted transaction logs, you may use tool SQL Database Recovery Tool Repairs to repair your corrupted mdf file.

Node.js https pem error: routines:PEM_read_bio:no start line

I removed this error by write the following code

Open Terminal

  1. openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem

  2. openssl x509 -req -days 365 -in csr.pem -signkey key.pem -out server.crt

Now use the server.crt and key.pem file

app.js or server.js file

var https = require('https');
var https_options = {
  key: fs.readFileSync('key.pem', 'utf8'),
  cert: fs.readFileSync('server.crt', 'utf8')
};

var server = https.createServer(https_options, app).listen(PORT);
console.log('HTTPS Server listening on %s:%s', HOST, PORT);

It works but the certificate is not trusted. You can view the image in image file.

enter image description here

Change image source in code behind - Wpf

None of the methods worked for me as i needed to pull the image from a folder instead of adding it to the application. The below code worked:

TestImage.Source = GetImage("/Content/Images/test.png")

private static BitmapImage GetImage(string imageUri)
{
    var bitmapImage = new BitmapImage();
    
    bitmapImage.BeginInit();
    bitmapImage.UriSource = new Uri("pack://siteoforigin:,,,/" + imageUri,             UriKind.RelativeOrAbsolute);
    bitmapImage.EndInit();
    
    return bitmapImage;
} 

Convert Rtf to HTML

If you don't mind getting your hands dirty, it isn't that difficult to write an RTF to HTML converter.

Writing a general purpose RTF->HTML converter would be somewhat complicated because you would need to deal with hundreds of RTF verbs. However, in your case you are only dealing with those verbs used specifically by Crystal Reports. I'll bet the standard RTF coding generated by Crystal doesn't vary much from report to report.

I wrote an RTF to HTML converter in C++, but it only deals with basic formatting like fonts, paragraph alignments, etc. My translator basically strips out any specialized formatting that it isn't prepared to deal with. It took about 400 lines of C++. It basically scans the text for RTF tags and replaces them with equivalent HTML tags. RTF tags that aren't in my list are simply stripped out. A regex function is really helpful when writing such a converter.

403 - Forbidden: Access is denied. ASP.Net MVC

In addition to the answers above, you may also get that error when you have Windows Authenticaton set and :

  • IIS is pointing to an empty folder.
  • You do not have a default document set.

HTML text input field with currency symbol

I just used :before with the input and passed $ as the content

input{ 
   margin-left: 20px;
 }
input:before {
  content: "$";
  position: absolute;
}

.htaccess or .htpasswd equivalent on IIS?

There isn't a direct 1:1 equivalent.

You can password protect a folder or file using file system permissions. If you are using ASP.Net you can also use some of its built in functions to protect various urls.

If you are trying to port .htaccess files used for url rewriting, check out ISAPI Rewrite: http://www.isapirewrite.com/

Swift Beta performance: sorting arrays

The main issue that is mentioned by others but not called out enough is that -O3 does nothing at all in Swift (and never has) so when compiled with that it is effectively non-optimised (-Onone).

Option names have changed over time so some other answers have obsolete flags for the build options. Correct current options (Swift 2.2) are:

-Onone // Debug - slow
-O     // Optimised
-O -whole-module-optimization //Optimised across files

Whole module optimisation has a slower compile but can optimise across files within the module i.e. within each framework and within the actual application code but not between them. You should use this for anything performance critical)

You can also disable safety checks for even more speed but with all assertions and preconditions not just disabled but optimised on the basis that they are correct. If you ever hit an assertion this means that you are into undefined behaviour. Use with extreme caution and only if you determine that the speed boost is worthwhile for you (by testing). If you do find it valuable for some code I recommend separating that code into a separate framework and only disabling the safety checks for that module.

Foreach loop in C++ equivalent of C#

Just for fun (new lambda functions):

      static std::list<string> some_list;

      vector<string> s; 
      s.push_back("a");
      s.push_back("b");
      s.push_back("c");

      for_each( s.begin(), s.end(), [=](string str) 
        {
          some_list.push_back(str);
        }

  );

  for_each( some_list.begin(), some_list.end(), [](string ss) { cout << ss; } );

Although doing a simple loop is recommended :-)

Java - Change int to ascii

The most simple way is using type casting:

public char toChar(int c) {
    return (char)c;
}

Extracting a parameter from a URL in WordPress

Why not just use the WordPress get_query_var() function? WordPress Code Reference

// Test if the query exists at the URL
if ( get_query_var('ppc') ) {

    // If so echo the value
    echo get_query_var('ppc');

}

Since get_query_var can only access query parameters available to WP_Query, in order to access a custom query var like 'ppc', you will also need to register this query variable within your plugin or functions.php by adding an action during initialization:

add_action('init','add_get_val');
function add_get_val() { 
    global $wp; 
    $wp->add_query_var('ppc'); 
}

Or by adding a hook to the query_vars filter:

function add_query_vars_filter( $vars ){
  $vars[] = "ppc";
  return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );

Mongoose (mongodb) batch insert?

Indeed, you can use the "create" method of Mongoose, it can contain an array of documents, see this example:

Candy.create({ candy: 'jelly bean' }, { candy: 'snickers' }, function (err, jellybean, snickers) {
});

The callback function contains the inserted documents. You do not always know how many items has to be inserted (fixed argument length like above) so you can loop through them:

var insertedDocs = [];
for (var i=1; i<arguments.length; ++i) {
    insertedDocs.push(arguments[i]);
}

Update: A better solution

A better solution would to use Candy.collection.insert() instead of Candy.create() - used in the example above - because it's faster (create() is calling Model.save() on each item so it's slower).

See the Mongo documentation for more information: http://docs.mongodb.org/manual/reference/method/db.collection.insert/

(thanks to arcseldon for pointing this out)

How to fit in an image inside span tag?

Try this.

<span style="padding-right:3px; padding-top: 3px; display:inline-block;">

<img class="manImg" src="images/ico_mandatory.gif"></img>

</span>

What is the best workaround for the WCF client `using` block issue?

Use an extension method:

public static class CommunicationObjectExtensions
{
    public static TResult MakeSafeServiceCall<TResult, TService>(this TService client, Func<TService, TResult> method) where TService : ICommunicationObject
    {
        TResult result;

        try
        {
            result = method(client);
        }
        finally
        {
            try
            {
                client.Close();
            }
            catch (CommunicationException)
            {
                client.Abort(); // Don't care about these exceptions. The call has completed anyway.
            }
            catch (TimeoutException)
            {
                client.Abort(); // Don't care about these exceptions. The call has completed anyway.
            }
            catch (Exception)
            {
                client.Abort();
                throw;
            }
        }

        return result;
    }
}

How to Convert the value in DataTable into a string array in c#

Perhaps something like this, assuming that there are many of these rows inside of the datatable and that each row is row:

List<string[]> MyStringArrays = new List<string[]>();
foreach( var row in datatable.rows )//or similar
{
 MyStringArrays.Add( new string[]{row.Name,row.Address,row.Age.ToString()} );
}

You could then access one:

MyStringArrays.ElementAt(0)[1]

If you use linqpad, here is a very simple scenario of your example:

class Datatable
{
 public List<data> rows { get; set; }
 public Datatable(){
  rows = new List<data>();
 }
}

class data
{
 public string Name { get; set; }
 public string Address { get; set; }
 public int Age { get; set; }
}

void Main()
{
 var datatable = new Datatable();
 var r = new data();
 r.Name = "Jim";
 r.Address = "USA";
 r.Age = 23;
 datatable.rows.Add(r);
 List<string[]> MyStringArrays = new List<string[]>();
 foreach( var row in datatable.rows )//or similar
 {
  MyStringArrays.Add( new string[]{row.Name,row.Address,row.Age.ToString()} );
 }
 var s = MyStringArrays.ElementAt(0)[1];
 Console.Write(s);//"USA"
}

How do you Encrypt and Decrypt a PHP String?

I'm late to the party, but searching for the correct way to do it I came across this page it was one of the top Google search returns, so I will like to share my view on the problem, which I consider it to be up to date at the time of writing this post (beginning of 2017). From PHP 7.1.0 the mcrypt_decrypt and mcrypt_encrypt is going to be deprecated, so building future proof code should use openssl_encrypt and openssl_decrypt

You can do something like:

$string_to_encrypt="Test";
$password="password";
$encrypted_string=openssl_encrypt($string_to_encrypt,"AES-128-ECB",$password);
$decrypted_string=openssl_decrypt($encrypted_string,"AES-128-ECB",$password);

Important: This uses ECB mode, which isn't secure. If you want a simple solution without taking a crash course in cryptography engineering, don't write it yourself, just use a library.

You can use any other chipper methods as well, depending on your security need. To find out the available chipper methods please see the openssl_get_cipher_methods function.

How does one check if a table exists in an Android SQLite database?

You mentioned that you've created an class that extends SQLiteOpenHelper and implemented the onCreate method. Are you making sure that you're performing all your database acquire calls with that class? You should only be getting SQLiteDatabase objects via the SQLiteOpenHelper#getWritableDatabase and getReadableDatabase otherwise the onCreate method will not be called when necessary. If you are doing that already check and see if th SQLiteOpenHelper#onUpgrade method is being called instead. If so, then the database version number was changed at some point in time but the table was never created properly when that happened.

As an aside, you can force the recreation of the database by making sure all connections to it are closed and calling Context#deleteDatabase and then using the SQLiteOpenHelper to give you a new db object.

How to get full REST request body using Jersey?

Since you're transferring data in xml, you could also (un)marshal directly from/to pojos.

There's an example (and more info) in the jersey user guide, which I copy here:

POJO with JAXB annotations:

@XmlRootElement
public class Planet {
    public int id;
    public String name;
    public double radius;
}

Resource:

@Path("planet")
public class Resource {

    @GET
    @Produces(MediaType.APPLICATION_XML)
    public Planet getPlanet() {
        Planet p = new Planet();
        p.id = 1;
        p.name = "Earth";
        p.radius = 1.0;

        return p;
    }

    @POST
    @Consumes(MediaType.APPLICATION_XML)
    public void setPlanet(Planet p) {
        System.out.println("setPlanet " + p.name);
    }

}      

The xml that gets produced/consumed:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<planet>
    <id>1</id>
    <name>Earth</name>
    <radius>1.0</radius>
</planet>

Execute a SQL Stored Procedure and process the results

From MSDN

To execute a stored procedure returning rows programmatically using a command object

Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand
Dim reader As SqlDataReader

cmd.CommandText = "StoredProcedureName"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1

sqlConnection1.Open()

reader = cmd.ExecuteReader()
' Data is accessible through the DataReader object here.
' Use Read method (true/false) to see if reader has records and advance to next record
' You can use a While loop for multiple records (While reader.Read() ... End While)
If reader.Read() Then
  someVar = reader(0)
  someVar2 = reader(1)
  someVar3 = reader("NamedField")
End If    

sqlConnection1.Close()

Google Maps: how to get country, state/province/region, city given a lat/long value?

I wrote this function that extracts what you are looking for based on the address_components returned from the gmaps API. This is the city (for example).

export const getAddressCity = (address, length) => {
  const findType = type => type.types[0] === "locality"
  const location = address.map(obj => obj)
  const rr = location.filter(findType)[0]

  return (
    length === 'short'
      ? rr.short_name
      : rr.long_name
  )
}

Change locality to administrative_area_level_1 for the State etc.

In my js code I am using like so:

const location =`${getAddressCity(address_components, 'short')}, ${getAddressState(address_components, 'short')}`

Will return: Waltham, MA

What is the best way to parse html in C#?

I've used ZetaHtmlTidy in the past to load random websites and then hit against various parts of the content with xpath (eg /html/body//p[@class='textblock']). It worked well but there were some exceptional sites that it had problems with, so I don't know if it's the absolute best solution.

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

It is used to find the how many rows contain data in a worksheet that contains data in the column "A". The full usage is

 lastRowIndex = ws.Cells(ws.Rows.Count, "A").End(xlUp).row

Where ws is a Worksheet object. In the questions example it was implied that the statement was inside a With block

With ws
    lastRowIndex = .Cells(.Rows.Count, "A").End(xlUp).row
End With
  1. ws.Rows.Count returns the total count of rows in the worksheet (1048576 in Excel 2010).
  2. .Cells(.Rows.Count, "A") returns the bottom most cell in column "A" in the worksheet

Then there is the End method. The documentation is ambiguous as to what it does.

Returns a Range object that represents the cell at the end of the region that contains the source range

Particularly it doesn't define what a "region" is. My understanding is a region is a contiguous range of non-empty cells. So the expected usage is to start from a cell in a region and find the last cell in that region in that direction from the original cell. However there are multiple exceptions for when you don't use it like that:

  • If the range is multiple cells, it will use the region of rng.cells(1,1).
  • If the range isn't in a region, or the range is already at the end of the region, then it will travel along the direction until it enters a region and return the first encountered cell in that region.
  • If it encounters the edge of the worksheet it will return the cell on the edge of that worksheet.

So Range.End is not a trivial function.

  1. .row returns the row index of that cell.

HTTP Status 405 - Method Not Allowed Error for Rest API

Add

@Produces({"image/jpeg,image/png"})

to

@POST
@Path("/pdf")
@Consumes({ MediaType.MULTIPART_FORM_DATA })
@Produces({"image/jpeg,image/png"})
//@Produces("text/plain")
public Response uploadPdfFile(@FormDataParam("file") InputStream fileInputStream,@FormDataParam("file") FormDataContentDisposition fileMetaData) throws Exception {
    ...
}

How do CORS and Access-Control-Allow-Headers work?

Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000 or Access-Control-Allow-Origin: * on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true on the POST response as well.

Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept to match the requested header.

Find the day of a week

start = as.POSIXct("2017-09-01")
end = as.POSIXct("2017-09-06")

dat = data.frame(Date = seq.POSIXt(from = start,
                                   to = end,
                                   by = "DSTday"))

# see ?strptime for details of formats you can extract

# day of the week as numeric (Monday is 1)
dat$weekday1 = as.numeric(format(dat$Date, format = "%u"))

# abbreviated weekday name
dat$weekday2 = format(dat$Date, format = "%a")

# full weekday name
dat$weekday3 = format(dat$Date, format = "%A")

dat
# returns
    Date       weekday1 weekday2  weekday3
1 2017-09-01        5      Fri    Friday
2 2017-09-02        6      Sat    Saturday
3 2017-09-03        7      Sun    Sunday
4 2017-09-04        1      Mon    Monday
5 2017-09-05        2      Tue    Tuesday
6 2017-09-06        3      Wed    Wednesday

Add image in pdf using jspdf

Though I'm not sure, the image might not be added because you create the output before you add it. Try:

function convert(){
    var doc = new jsPDF();
    var imgData = 'data:image/jpeg;base64,'+ Base64.encode('Koala.jpeg');
    console.log(imgData);
    doc.setFontSize(40);
    doc.text(30, 20, 'Hello world!');
    doc.addImage(imgData, 'JPEG', 15, 40, 180, 160);
    doc.output('datauri');
}

how to get the last part of a string before a certain character?

You are looking for str.rsplit(), with a limit:

print x.rsplit('-', 1)[0]

.rsplit() searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once.

Another option is to use str.rpartition(), which will only ever split just once:

print x.rpartition('-')[0]

For splitting just once, str.rpartition() is the faster method as well; if you need to split more than once you can only use str.rsplit().

Demo:

>>> x = 'http://test.com/lalala-134'
>>> print x.rsplit('-', 1)[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]
'something-with-a-lot-of'

and the same with str.rpartition()

>>> print x.rpartition('-')[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
'something-with-a-lot-of'

Disabling submit button until all fields have values

Check out this jsfiddle.

HTML

// note the change... I set the disabled property right away
<input type="submit" id="register" value="Register" disabled="disabled" />

JavaScript

(function() {
    $('form > input').keyup(function() {

        var empty = false;
        $('form > input').each(function() {
            if ($(this).val() == '') {
                empty = true;
            }
        });

        if (empty) {
            $('#register').attr('disabled', 'disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
        } else {
            $('#register').removeAttr('disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
        }
    });
})()

The nice thing about this is that it doesn't matter how many input fields you have in your form, it will always keep the button disabled if there is at least 1 that is empty. It also checks emptiness on the .keyup() which I think makes it more convenient for usability.

SQL-Server: Error - Exclusive access could not be obtained because the database is in use

execute this query before restoring database:

alter database [YourDBName] 
set offline with rollback immediate

and this one after restoring:

  alter database [YourDBName] 
  set online