Programs & Examples On #Design time data

grep's at sign caught as whitespace

After some time with Google I asked on the ask ubuntu chat room.

A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:

grep -P "(^|\s)abc(\s|$)" gives the result I was looking for. -P is an experimental implementation of perl regexps.

grepping for abc and then using filters like grep -v '@abc' (this is far from perfect...) should also work, but my patch does something similar.

How to run python script with elevated privilege on windows

in comments to the answer you took the code from someone says ShellExecuteEx doesn't post its STDOUT back to the originating shell. so you will not see "I am root now", even though the code is probably working fine.

instead of printing something, try writing to a file:

import os
import sys
import win32com.shell.shell as shell
ASADMIN = 'asadmin'

if sys.argv[-1] != ASADMIN:
    script = os.path.abspath(sys.argv[0])
    params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
    shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
    sys.exit(0)
with open("somefilename.txt", "w") as out:
    print >> out, "i am root"

and then look in the file.

python tuple to dict

A slightly simpler method:

>>> t = ((1, 'a'),(2, 'b'))
>>> dict(map(reversed, t))
{'a': 1, 'b': 2}

Can a div have multiple classes (Twitter Bootstrap)

space is used to make multiple classes:

<div class="One Two Three">

</div>

Better way to represent array in java properties file

I can suggest using delimiters and using the

String.split(delimiter)

Example properties file:

MON=0800#Something#Something1, Something2

prop.load(new FileInputStream("\\\\Myseccretnetwork\\Project\\props.properties"));
String[]values = prop.get("MON").toString().split("#");

Hope that helps

Is this very likely to create a memory leak in Tomcat?

I added the following to @PreDestroy method in my CDI @ApplicationScoped bean, and when I shutdown TomEE 1.6.0 (tomcat7.0.39, as of today), it clears the thread locals.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pf;

import java.lang.ref.WeakReference;
import java.lang.reflect.Array;
import java.lang.reflect.Field;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Administrator
 * 
 * google-gson issue # 402: Memory Leak in web application; comment # 25
 * https://code.google.com/p/google-gson/issues/detail?id=402
 */
public class ThreadLocalImmolater {

    final Logger logger = LoggerFactory.getLogger(ThreadLocalImmolater.class);

    Boolean debug;

    public ThreadLocalImmolater() {
        debug = true;
    }

    public Integer immolate() {
        int count = 0;
        try {
            final Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
            threadLocalsField.setAccessible(true);
            final Field inheritableThreadLocalsField = Thread.class.getDeclaredField("inheritableThreadLocals");
            inheritableThreadLocalsField.setAccessible(true);
            for (final Thread thread : Thread.getAllStackTraces().keySet()) {
                    count += clear(threadLocalsField.get(thread));
                    count += clear(inheritableThreadLocalsField.get(thread));
            }
            logger.info("immolated " + count + " values in ThreadLocals");
        } catch (Exception e) {
            throw new Error("ThreadLocalImmolater.immolate()", e);
        }
        return count;
    }

    private int clear(final Object threadLocalMap) throws Exception {
        if (threadLocalMap == null)
                return 0;
        int count = 0;
        final Field tableField = threadLocalMap.getClass().getDeclaredField("table");
        tableField.setAccessible(true);
        final Object table = tableField.get(threadLocalMap);
        for (int i = 0, length = Array.getLength(table); i < length; ++i) {
            final Object entry = Array.get(table, i);
            if (entry != null) {
                final Object threadLocal = ((WeakReference)entry).get();
                if (threadLocal != null) {
                    log(i, threadLocal);
                    Array.set(table, i, null);
                    ++count;
                }
            }
        }
        return count;
    }

    private void log(int i, final Object threadLocal) {
        if (!debug) {
            return;
        }
        if (threadLocal.getClass() != null &&
            threadLocal.getClass().getEnclosingClass() != null &&
            threadLocal.getClass().getEnclosingClass().getName() != null) {

            logger.info("threadLocalMap(" + i + "): " +
                        threadLocal.getClass().getEnclosingClass().getName());
        }
        else if (threadLocal.getClass() != null &&
                 threadLocal.getClass().getName() != null) {
            logger.info("threadLocalMap(" + i + "): " + threadLocal.getClass().getName());
        }
        else {
            logger.info("threadLocalMap(" + i + "): cannot identify threadlocal class name");
        }
    }

}

Connecting to remote URL which requires authentication using Java

You can set the default authenticator for http requests like this:

Authenticator.setDefault (new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication ("username", "password".toCharArray());
    }
});

Also, if you require more flexibility, you can check out the Apache HttpClient, which will give you more authentication options (as well as session support, etc.)

How to Create an excel dropdown list that displays text with a numeric hidden value

There are two types of drop down lists available (I am not sure since which version).

ActiveX Drop Down
You can set the column widths, so your hidden column can be set to 0.

Form Drop Down
You could set the drop down range to a hidden sheet and reference the cell adjacent to the selected item. This would also work with the ActiveX type control.

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '...' is therefore not allowed access

Add this to you PHP file or main controller

header("Access-Control-Allow-Origin: http://localhost:9000");

In Angular, how to add Validator to FormControl after control is created?

In addition to Eduard Void answer here's the addValidators method:

declare module '@angular/forms' {
  interface FormControl {
    addValidators(validators: ValidatorFn[]): void;
  }
}

FormControl.prototype.addValidators = function(this: FormControl, validators: ValidatorFn[]) {
  if (!validators || !validators.length) {
    return;
  }

  this.clearValidators();
  this.setValidators( this.validator ? [ this.validator, ...validators ] : validators );
};

Using it you can set validators dynamically:

some_form_control.addValidators([ first_validator, second_validator ]);
some_form_control.addValidators([ third_validator ]);

how to generate web service out of wsdl

step-1

open -> Visual Studio 2017 Developer Command Prompt

step-2

WSDL.exe  /OUT:myFile.cs WSDLURL  /Language:CS /serverInterface
  • /serverInterface (this to create interface from wsdl file)
  • WSDL.exe (this use to create class from wsdl. this comes with .net
  • /OUT: (output file name)

step-2

create new "Web service Project"

step-3

add -> web service

step-4

copy all code from myFile.cs (generated above) except "using classes" eg:

 /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.6.1055.0")]
    [System.Web.Services.WebServiceBindingAttribute(Name="calculoterServiceSoap",Namespace="http://tempuri.org/")]

public interface ICalculoterServiceSoap {

    /// <remarks/>
    [System.Web.Services.WebMethodAttribute()]
    [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/addition", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
    string addition(int firtNo, int secNo);
}

step-4

past it into your webService.asmx.cs (inside of namespace) created above in step-2

step-5

inherit the interface class with your web service class eg:

public class WebService2 : ICalculoterServiceSoap

"CSV file does not exist" for a filename with embedded quotes

Had an issue with the path, it turns out that you need to specify the first '/' to get it to work! I am using VSCode/Python on macOS

Select dropdown with fixed width cutting off content in IE

A pure css solution : http://bavotasan.com/2011/style-select-box-using-only-css/

_x000D_
_x000D_
.styled-select select {_x000D_
   background: transparent;_x000D_
   width: 268px;_x000D_
   padding: 5px;_x000D_
   font-size: 16px;_x000D_
   line-height: 1;_x000D_
   border: 0;_x000D_
   border-radius: 0;_x000D_
   height: 34px;_x000D_
   -webkit-appearance: none;_x000D_
   }_x000D_
_x000D_
.styled-select {_x000D_
   width: 240px;_x000D_
   height: 34px;_x000D_
   overflow: hidden;_x000D_
   background: url(http://cdn.bavotasan.com/wp-content/uploads/2011/05/down_arrow_select.jpg) no-repeat right #ddd;_x000D_
   border: 1px solid #ccc;_x000D_
   }
_x000D_
<div class="styled-select">_x000D_
   <select>_x000D_
      <option>Here is the first option</option>_x000D_
      <option>The second option</option>_x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

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

You can do it with something like this, so if no arguments are specified it will continue anyway:

public static void main(String[] args) {
    try {
        String one = args[0];
        String two = args[1];
    }
    catch (ArrayIndexOutOfBoundsException e){
        System.out.println("ArrayIndexOutOfBoundsException caught");
    }
    finally {

    }
}

And then launch the application:

java -jar myapp.jar arg1 arg2

How does Content Security Policy (CSP) work?

Apache 2 mod_headers

You could also enable Apache 2 mod_headers. On Fedora it's already enabled by default. If you use Ubuntu/Debian, enable it like this:

# First enable headers module for Apache 2,
# and then restart the Apache2 service
a2enmod headers
apache2 -k graceful

On Ubuntu/Debian you can configure headers in the file /etc/apache2/conf-enabled/security.conf

#
# Setting this header will prevent MSIE from interpreting files as something
# else than declared by the content type in the HTTP headers.
# Requires mod_headers to be enabled.
#
#Header set X-Content-Type-Options: "nosniff"

#
# Setting this header will prevent other sites from embedding pages from this
# site as frames. This defends against clickjacking attacks.
# Requires mod_headers to be enabled.
#
Header always set X-Frame-Options: "sameorigin"
Header always set X-Content-Type-Options nosniff
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Permitted-Cross-Domain-Policies "master-only"
Header always set Cache-Control "no-cache, no-store, must-revalidate"
Header always set Pragma "no-cache"
Header always set Expires "-1"
Header always set Content-Security-Policy: "default-src 'none';"
Header always set Content-Security-Policy: "script-src 'self' www.google-analytics.com adserver.example.com www.example.com;"
Header always set Content-Security-Policy: "style-src 'self' www.example.com;"

Note: This is the bottom part of the file. Only the last three entries are CSP settings.

The first parameter is the directive, the second is the sources to be white-listed. I've added Google analytics and an adserver, which you might have. Furthermore, I found that if you have aliases, e.g, www.example.com and example.com configured in Apache 2 you should add them to the white-list as well.

Inline code is considered harmful, and you should avoid it. Copy all the JavaScript code and CSS to separate files and add them to the white-list.

While you're at it you could take a look at the other header settings and install mod_security

Further reading:

https://developers.google.com/web/fundamentals/security/csp/

https://www.w3.org/TR/CSP/

static files with express.js

res.sendFile & express.static both will work for this

var express = require('express');
var app = express();
var path = require('path');
var public = path.join(__dirname, 'public');

// viewed at http://localhost:8080
app.get('/', function(req, res) {
    res.sendFile(path.join(public, 'index.html'));
});

app.use('/', express.static(public));

app.listen(8080);

Where public is the folder in which the client side code is

As suggested by @ATOzTOA and clarified by @Vozzie, path.join takes the paths to join as arguments, the + passes a single argument to path.

How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

With Java 8 and later, use the java.time package.

ZonedDateTime.now().getYear();
ZonedDateTime.now().getMonthValue();
ZonedDateTime.now().getDayOfMonth();
ZonedDateTime.now().getHour();
ZonedDateTime.now().getMinute();
ZonedDateTime.now().getSecond();

ZonedDateTime.now() is a static method returning the current date-time from the system clock in the default time-zone. All the get methods return an int value.

using batch echo with special characters

Why not use single quote?

echo '<?xml version="1.0" encoding="utf-8" ?>'

output

<?xml version="1.0" encoding="utf-8" ?>

How to find index of all occurrences of element in array?

More simple way with es6 style.

const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []);


//Examples:
var cars = ["Nano", "Volvo", "BMW", "Nano", "VW", "Nano"];
indexOfAll(cars, "Nano"); //[0, 3, 5]
indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0,3]
indexOfAll([1, 2, 3], 4); // []

How to "git clone" including submodules?

Submodules parallel fetch aims at reducing the time required to fetch a repositories and all of its related submodules by enabling the fetching of multiple repositories at once. This can be accomplished by using the new --jobs option, e.g.:

git fetch --recurse-submodules --jobs=4

According to Git team, this can substantially speed up updating repositories that contain many submodules. When using --recurse-submodules without the new --jobs option, Git will fetch submodules one by one.

Source: http://www.infoq.com/news/2016/03/git28-released

How to implement LIMIT with SQL Server?

Starting SQL SERVER 2005, you can do this...

USE AdventureWorks;
GO
WITH OrderedOrders AS
(
    SELECT SalesOrderID, OrderDate,
    ROW_NUMBER() OVER (ORDER BY OrderDate) AS 'RowNumber'
    FROM Sales.SalesOrderHeader 
) 
SELECT * 
FROM OrderedOrders 
WHERE RowNumber BETWEEN 10 AND 20;

or something like this for 2000 and below versions...

SELECT TOP 10 * FROM (SELECT TOP 20 FROM Table ORDER BY Id) ORDER BY Id DESC

$location / switching between html5 and hashbang mode / link rewriting

This took me a while to figure out so this is how I got it working - Angular WebAPI ASP Routing without the # for SEO

  1. add to Index.html - base href="/">
  2. Add $locationProvider.html5Mode(true); to app.config

  3. I needed a certain controller (which was in the home controller) to be ignored for uploading images so I added that rule to RouteConfig

         routes.MapRoute(
            name: "Default2",
            url: "Home/{*.}",
            defaults: new { controller = "Home", action = "SaveImage" }
        );
    
  4. In Global.asax add the following - making sure to ignore api and image upload paths let them function as normal otherwise reroute everything else.

     private const string ROOT_DOCUMENT = "/Index.html";
    
    protected void Application_BeginRequest(Object sender, EventArgs e)
    {
        var path = Request.Url.AbsolutePath;
        var isApi = path.StartsWith("/api", StringComparison.InvariantCultureIgnoreCase);
        var isImageUpload = path.StartsWith("/home", StringComparison.InvariantCultureIgnoreCase);
    
        if (isApi || isImageUpload)
            return;
    
        string url = Request.Url.LocalPath;
        if (!System.IO.File.Exists(Context.Server.MapPath(url)))
            Context.RewritePath(ROOT_DOCUMENT);
    }
    
  5. Make sure to use $location.url('/XXX') and not window.location ... to redirect

  6. Reference the CSS files with absolute path

and not

<link href="app/content/bootstrapwc.css" rel="stylesheet" />

Final note - doing it this way gave me full control and I did not need to do anything to the web config.

Hope this helps as this took me a while to figure out.

How does C compute sin() and other math functions?

The actual implementation of library functions is up to the specific compiler and/or library provider. Whether it's done in hardware or software, whether it's a Taylor expansion or not, etc., will vary.

I realize that's absolutely no help.

How can I use Python to get the system hostname?

Both of these are pretty portable:

import platform
platform.node()

import socket
socket.gethostname()

Any solutions using the HOST or HOSTNAME environment variables are not portable. Even if it works on your system when you run it, it may not work when run in special environments such as cron.

How do I create a MessageBox in C#?

Also you can use a MessageBox with OKCancel options, but it requires many codes. The if block is for OK, the else block is for Cancel. Here is the code:

if (MessageBox.Show("Are you sure you want to do this?", "Question", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
    MessageBox.Show("You pressed OK!");
}
else
{
    MessageBox.Show("You pressed Cancel!");
}

You can also use a MessageBox with YesNo options:

if (MessageBox.Show("Are you sure want to doing this?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
    MessageBox.Show("You are pressed Yes!");
}
else
{
    MessageBox.Show("You are pressed No!");
}

File loading by getClass().getResource()

The best way to access files from resource folder inside a jar is it to use the InputStream via getResourceAsStream. If you still need a the resource as a file instance you can copy the resource as a stream into a temporary file (the temp file will be deleted when the JVM exits):

public static File getResourceAsFile(String resourcePath) {
    try {
        InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);
        if (in == null) {
            return null;
        }

        File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
        tempFile.deleteOnExit();

        try (FileOutputStream out = new FileOutputStream(tempFile)) {
            //copy stream
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
        return tempFile;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

How to check if a double is null?

Firstly, a Java double cannot be null, and cannot be compared with a Java null. (The double type is a primitive (non-reference) type and primitive types cannot be null.)

Next, if you call ResultSet.getDouble(...), that returns a double not a Double, the documented behaviour is that a NULL (from the database) will be returned as zero. (See javadoc linked above.) That is no help if zero is a legitimate value for that column.

So your options are:

The getObject method will deliver the value as a Double (assuming that the column type is double), and is documented to return null for a NULL. (For more information, this page documents the default mappings of SQL types to Java types, and therefore what actual type you should expect getObject to deliver.)

Make index.html default, but allow index.php to be visited if typed in

DirectoryIndex index.html index.htm default.htm index.php index.php3 index.phtml index.php5 index.shtml mwindex.phtml

it doesn't has any means? you may be just need to add like this!

<IfModule dir_module>
    DirectoryIndex index.php index.html index.htm
</IfModule>

enter image description here

Changing MongoDB data store directory

I found a special case that causes symlinks to appear to fail:

I did a standard enterprise install of mongodb but changed the /var/lib/mongodb to a symlink as I wanted to use an XFS filesystem for my database folder and a third filesystem for the log folder.

$sudo systemctl start mongod (fails with a message no permission to write to mongodb.log).. but it succceded if I started with the same configuration file:

.. as the owner of the external drives (ziggy) I was able to start $mongod --config /etc/mongodb.conf --fork

I eventually discovered that .. the symlinks pointed to a different filesystem and the mongodb (user) did not have permission to browse the folder that the symlink referred. Both the symlinks and the folders the symlinks referred had expansive rights to the mongod user so it made no sense?

/var/log/mongodb was changed (from the std ent install) to a symlink AND I had checked before:

$ ll /var/log/mongodb lrwxrwxrwx 1 mongodb mongodb 38 Oct 28 21:58 /var/log/mongodb -> /media/ziggy/XFS_DB/mongodb/log/

$ ll -d /media/ziggy/Ext4DataBase/mongodb/log drwxrwxrwx 2 mongodb mongodb 4096 Nov 1 12:05 /media/ashley/XFS_DB/mongodb/log/

.. But so it seemed to make no sense.. of course user mongodb had rwx access to the link, the folder and to the file mongodb.log .. but it couldnt find it via the symlink because the BASE folder of the media couldnt be searched by mongodb.

SO.. I EVENTUALLY DID THIS: $ ll /media/ziggy/ . . drwx------ 5 ziggy ziggy 4096 Oct 28 21:49 XFS_DB/

and found the offending missing x permissions..

$chmod a+x /media/ziggy/XFS_DB solved the problem

Seems stupid in hindsight but no searches turned up anything useful.

Bootstrap 3 select input form inline

Another different answer to an old question. However, I found a implementation made specifically for bootstrap which might prove useful here. Hope this helps anybody who is looking...

Bootstrap-select

Node JS Error: ENOENT

To expand a bit on why the error happened: A forward slash at the beginning of a path means "start from the root of the filesystem, and look for the given path". No forward slash means "start from the current working directory, and look for the given path".

The path

/tmp/test.jpg

thus translates to looking for the file test.jpg in the tmp folder at the root of the filesystem (e.g. c:\ on windows, / on *nix), instead of the webapp folder. Adding a period (.) in front of the path explicitly changes this to read "start from the current working directory", but is basically the same as leaving the forward slash out completely.

./tmp/test.jpg = tmp/test.jpg

Double.TryParse or Convert.ToDouble - which is faster and safer?

This is an interesting old question. I'm adding an answer because nobody noticed a couple of things with the original question.

Which is faster: Convert.ToDouble or Double.TryParse? Which is safer: Convert.ToDouble or Double.TryParse?

I'm going to answer both these questions (I'll update the answer later), in detail, but first:

For safety, the thing every programmer missed in this question is the line (emphasis mine):

It adds only data that are numbers with a few digits (1000 1000,2 1000,34 - comma is a delimiter in Russian standards).

Followed by this code example:

Convert.ToDouble(regionData, CultureInfo.CurrentCulture);

What's interesting here is that if the spreadsheets are in Russian number format but Excel has not correctly typed the cell fields, what is the correct interpretation of the values coming in from Excel?

Here is another interesting thing about the two examples, regarding speed:

catch (InvalidCastException)
{
    // is not a number
}

This is likely going to generate MSIL that looks like this:

catch [mscorlib]System.InvalidCastException 
{
  IL_0023:  stloc.0
  IL_0024:  nop
  IL_0025:  ldloc.0
  IL_0026:  nop
  IL_002b:  nop
  IL_002c:  nop
  IL_002d:  leave.s    IL_002f
}  // end handler
IL_002f: nop
IL_0030: return

In this sense, we can probably compare the total number of MSIL instructions carried out by each program - more on that later as I update this post.

I believe code should be Correct, Clear, and Fast... In that order!

What does "hard coded" mean?

"Hard Coding" means something that you want to embeded with your program or any project that can not be changed directly. For example if you are using a database server, then you must hardcode to connect your database with your project and that can not be changed by user. Because you have hard coded.

Do I cast the result of malloc?

For me, the take home and conclusion here is that casting malloc in C is totally NOT necessary but if you however cast, it wont affect malloc as malloc will still allocate to you your requested blessed memory space. Another take home is the reason or one of the reasons people do casting and this is to enable them compile same program either in C or C++.

There may be other reasons but other reasons, almost certainly, would land you in serious trouble sooner or later.

UIView frame, bounds and center

After reading the above answers, here adding my interpretations.

Suppose browsing online, web browser is your frame which decides where and how big to show webpage. Scroller of browser is your bounds.origin that decides which part of webpage will be shown. bounds.origin is hard to understand. The best way to learn is creating Single View Application, trying modify these parameters and see how subviews change.

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(100.0f, 200.0f, 200.0f, 400.0f)];
[view1 setBackgroundColor:[UIColor redColor]];

UIView *view2 = [[UIView alloc] initWithFrame:CGRectInset(view1.bounds, 20.0f, 20.0f)];
[view2 setBackgroundColor:[UIColor yellowColor]];
[view1 addSubview:view2];

[[self view] addSubview:view1];

NSLog(@"Old view1 frame %@, bounds %@, center %@", NSStringFromCGRect(view1.frame), NSStringFromCGRect(view1.bounds), NSStringFromCGPoint(view1.center));
NSLog(@"Old view2 frame %@, bounds %@, center %@", NSStringFromCGRect(view2.frame), NSStringFromCGRect(view2.bounds), NSStringFromCGPoint(view2.center));

// Modify this part.
CGRect bounds = view1.bounds;
bounds.origin.x += 10.0f;
bounds.origin.y += 10.0f;

// incase you need width, height
//bounds.size.height += 20.0f;
//bounds.size.width += 20.0f;

view1.bounds = bounds;

NSLog(@"New view1 frame %@, bounds %@, center %@", NSStringFromCGRect(view1.frame), NSStringFromCGRect(view1.bounds), NSStringFromCGPoint(view1.center));
NSLog(@"New view2 frame %@, bounds %@, center %@", NSStringFromCGRect(view2.frame), NSStringFromCGRect(view2.bounds), NSStringFromCGPoint(view2.center));

Aren't promises just callbacks?

Promises are not callbacks, both are programming idioms that facilitate async programming. Using an async/await-style of programming using coroutines or generators that return promises could be considered a 3rd such idiom. A comparison of these idioms across different programming languages (including Javascript) is here: https://github.com/KjellSchubert/promise-future-task

import .css file into .less file

since 1.5.0 u can use the 'inline' keyword.

Example: @import (inline) "not-less-compatible.css";

You will use this when a CSS file may not be Less compatible; this is because although Less supports most known standards CSS, it does not support comments in some places and does not support all known CSS hacks without modifying the CSS. So you can use this to include the file in the output so that all CSS will be in one file.

(source: http://lesscss.org/features/#import-directives-feature)

Arithmetic overflow error converting numeric to data type numeric

check your value which you want to store in integer column. I think this is greater then range of integer. if you want to store value greater then integer range. you should use bigint datatype

'Field required a bean of type that could not be found.' error spring restful API using mongodb

Add @Repository in you dao class

example:

@Repository
public class DaoClassName implements IIntefaceDao {
}

The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM'

THE ANSWER: The problem was all of the posts for such an issue were related to older kerberos and IIS issues where proxy credentials or AllowNTLM properties were helping. My case was different. What I have discovered after hours of picking worms from the ground was that somewhat IIS installation did not include Negotiate provider under IIS Windows authentication providers list. So I had to add it and move up. My WCF service started to authenticate as expected. Here is the screenshot how it should look if you are using Windows authentication with Anonymous auth OFF.

You need to right click on Windows authentication and choose providers menu item.

enter image description here

Hope this helps to save some time.

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

Thanks to all for sharing your answers and examples. The same standalone program worked for me by small changes and adding the lines of code below.

In this case, keystore file was given by webservice provider.

// Small changes during connection initiation.. 

// Please add this static block 

      static {

        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()

            {   @Override

        public boolean verify(String hostname, SSLSession arg1) {

        // TODO Auto-generated method stub

                if (hostname.equals("X.X.X.X")) {

                    System.out.println("Return TRUE"+hostname);

                    return true;

                }

                System.out.println("Return FALSE");

                return false;

              }
               });
         }


String xmlServerURL = "https://X.X.X.X:8080/services/EndpointPort";


URL urlXMLServer = new URL(null,xmlServerURL,new sun.net.www.protocol.https.Handler());


HttpsURLConnection httpsURLConnection = (HttpsURLConnection) urlXMLServer               .openConnection();

// Below extra lines are added to the same program

//Keystore file 

 System.setProperty("javax.net.ssl.keyStore", "Drive:/FullPath/keystorefile.store");

 System.setProperty("javax.net.ssl.keyStorePassword", "Password"); // Password given by vendor

//TrustStore file

System.setProperty("javax.net.ssl.trustStore"Drive:/FullPath/keystorefile.store");

System.setProperty("javax.net.ssl.trustStorePassword", "Password");

Find the number of downloads for a particular app in apple appstore

found a paper at: http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1924044 that suggests a formula to calculate the downloads:

d_iPad=13,516*rank^(-0.903)
d_iPhone=52,958*rank^(-0.944)

Ruby sleep or delay less than a second?

sleep(1.0/24.0)

As to your follow up question if that's the best way: No, you could get not-so-smooth framerates because the rendering of each frame might not take the same amount of time.

You could try one of these solutions:

  • Use a timer which fires 24 times a second with the drawing code.
  • Create as many frames as possible, create the motion based on the time passed, not per frame.

.htaccess file to allow access to images folder to view pictures?

Create a .htaccess file in the images folder and add this

<IfModule mod_rewrite.c>
RewriteEngine On
# directory browsing
Options All +Indexes
</IfModule>

you can put this Options All -Indexes in the project file .htaccess ,file to deny direct access to other folders.

This does what you want

How can I create a memory leak in Java?

From effective java book

  1. whenever a class manages its own memory, the programmer should be alert for memory leaks

.

public class Stack {
private Object[] elements;
private int size = 0;
private static final int DEFAULT_INITIAL_CAPACITY = 16;

public Stack() {
    elements = new Object[DEFAULT_INITIAL_CAPACITY];
}

public void push(Object e) {
    ensureCapacity();
    elements[size++] = e;
}

public Object pop() {
    if (size == 0)
        throw new EmptyStackException();
    return elements[--size];
}

/**
 * Ensure space for at least one more element, roughly doubling the capacity
 * each time the array needs to grow.
 */
private void ensureCapacity() {
    if (elements.length == size)
        elements = Arrays.copyOf(elements, 2 * size + 1);
}

}

Can you spot the memory leak? So where is the memory leak? If a stack grows and then shrinks, the objects that were popped off the stack will not be garbage collected, even if the program using the stack has no more references to them. This is because the stack maintains obsolete references to these objects. An obsolete reference is simply a reference that will never be dereferenced again. In this case, any references outside of the “active portion” of the element array are obsolete. The active portion consists of the elements whose index is less than size.

How to set up java logging using a properties file? (java.util.logging)

Okay, first intuition is here:

handlers = java.util.logging.FileHandler, java.util.logging.ConsoleHandler
.level = ALL

The Java prop file parser isn't all that smart, I'm not sure it'll handle this. But I'll go look at the docs again....

In the mean time, try:

handlers = java.util.logging.FileHandler
java.util.logging.ConsoleHandler.level = ALL

Update

No, duh, needed more coffee. Nevermind.

While I think more, note that you can use the methods in Properties to load and print a prop-file: it might be worth writing a minimal program to see what java thinks it reads in that file.


Another update

This line:

    FileInputStream configFile = new FileInputStream("/path/to/app.properties"));

has an extra end-paren. It won't compile. Make sure you're working with the class file you think you are.

Python: One Try Multiple Except

Yes, it is possible.

try:
   ...
except FirstException:
   handle_first_one()

except SecondException:
   handle_second_one()

except (ThirdException, FourthException, FifthException) as e:
   handle_either_of_3rd_4th_or_5th()

except Exception:
   handle_all_other_exceptions()

See: http://docs.python.org/tutorial/errors.html

The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)

how to add lines to existing file using python

Use 'a', 'a' means append. Anything written to a file opened with 'a' attribute is written at the end of the file.

with open('file.txt', 'a') as file:
    file.write('input')

WHERE statement after a UNION in SQL?

select column1..... from table1
where column1=''
union
select column1..... from table2
where column1= ''

Split string into array

ES6 is quite powerful in iterating through objects (strings, Array, Map, Set). Let's use a Spread Operator to solve this.

entry = prompt("Enter your name");
var count = [...entry];
console.log(count);

Efficient SQL test query or validation query that will work across all (or most) databases

select 1 would work in sql server, not sure about the others.

Use standard ansi sql to create a table and then query from that table.

How can I backup a Docker-container with its data-volumes?

If you just need a simple backup to an archive, you can try my little utility: https://github.com/loomchild/volume-backup

Example

Backup:

docker run -v some_volume:/volume -v /tmp:/backup --rm loomchild/volume-backup backup archive1

will archive volume named some_volume to /tmp/archive1.tar.bz2 archive file

Restore:

docker run -v some_volume:/volume -v /tmp:/backup --rm loomchild/volume-backup restore archive1

will wipe and restore volume named some_volume from /tmp/archive1.tar.bz2 archive file.

More info: https://medium.com/@loomchild/backup-restore-docker-named-volumes-350397b8e362

Module is not available, misspelled or forgot to load (but I didn't)

I have the same problem, but I resolved adding jquery.min.js before angular.min.js.

Unable to connect PostgreSQL to remote database using pgAdmin

Check your firewall. When you disable it, then you can connect. If you want/can't disable the firewall, add a rule for your remote connection.

How to get name of the computer in VBA?

A shell method to read the environmental variable for this courtesy of devhut

Debug.Print CreateObject("WScript.Shell").ExpandEnvironmentStrings("%COMPUTERNAME%")

Same source gives an API method:

Option Explicit

#If VBA7 And Win64 Then
    'x64 Declarations
    Declare PtrSafe Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#Else
    'x32 Declaration
    Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#End If

Public Sub test()

    Debug.Print ComputerName
    
End Sub

Public Function ComputerName() As String
    Dim sBuff                 As String * 255
    Dim lBuffLen              As Long
    Dim lResult               As Long
 
    lBuffLen = 255
    lResult = GetComputerName(sBuff, lBuffLen)
    If lBuffLen > 0 Then
        ComputerName = Left(sBuff, lBuffLen)
    End If
End Function

How to convert a Kotlin source file to a Java source file

As @Vadzim said, in IntelliJ or Android Studio, you just have to do the following to get java code from kotlin:

  1. Menu > Tools > Kotlin > Show Kotlin Bytecode
  2. Click on the Decompile button
  3. Copy the java code

Update:

With a recent version (1.2+) of the Kotlin plugin you also can directly do Menu > Tools > Kotlin -> Decompile Kotlin to Java.

Stored Procedure error ORA-06550

create or replace procedure point_triangle
AS
BEGIN
FOR thisteam in (select FIRSTNAME,LASTNAME,SUM(PTS)  from PLAYERREGULARSEASON  where TEAM    = 'IND' group by FIRSTNAME, LASTNAME order by SUM(PTS) DESC)

LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.PTS);
END LOOP;

END;
/

Working around MySQL error "Deadlock found when trying to get lock; try restarting transaction"

If you are using InnoDB or any row-level transactional RDBMS, then it is possible that any write transaction can cause a deadlock, even in perfectly normal situations. Larger tables, larger writes, and long transaction blocks will often increase the likelihood of deadlocks occurring. In your situation, it's probably a combination of these.

The only way to truly handle deadlocks is to write your code to expect them. This generally isn't very difficult if your database code is well written. Often you can just put a try/catch around the query execution logic and look for a deadlock when errors occur. If you catch one, the normal thing to do is just attempt to execute the failed query again.

I highly recommend you read this page in the MySQL manual. It has a list of things to do to help cope with deadlocks and reduce their frequency.

Append a Lists Contents to another List C#

With Linq

var newList = GlobalStrings.Append(localStrings)

Populating a dictionary using for loops (python)

dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
        dicts[i] = values[i]
print(dicts)

alternatively

In [7]: dict(list(enumerate(values)))
Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}

How to get the current time in milliseconds from C in Linux?

This can be achieved using the POSIX clock_gettime function.

In the current version of POSIX, gettimeofday is marked obsolete. This means it may be removed from a future version of the specification. Application writers are encouraged to use the clock_gettime function instead of gettimeofday.

Here is an example of how to use clock_gettime:

#define _POSIX_C_SOURCE 200809L

#include <inttypes.h>
#include <math.h>
#include <stdio.h>
#include <time.h>

void print_current_time_with_ms (void)
{
    long            ms; // Milliseconds
    time_t          s;  // Seconds
    struct timespec spec;

    clock_gettime(CLOCK_REALTIME, &spec);

    s  = spec.tv_sec;
    ms = round(spec.tv_nsec / 1.0e6); // Convert nanoseconds to milliseconds
    if (ms > 999) {
        s++;
        ms = 0;
    }

    printf("Current time: %"PRIdMAX".%03ld seconds since the Epoch\n",
           (intmax_t)s, ms);
}

If your goal is to measure elapsed time, and your system supports the "monotonic clock" option, then you should consider using CLOCK_MONOTONIC instead of CLOCK_REALTIME.

deleted object would be re-saved by cascade (remove deleted object from associations)

You need to remove association on the mapping object:

playList.getPlaylistadMaps().setPlayList(null);
session.delete(playList);

change directory in batch file using variable

The set statement doesn't treat spaces the way you expect; your variable is really named Pathname[space] and is equal to [space]C:\Program Files.

Remove the spaces from both sides of the = sign, and put the value in double quotes:

set Pathname="C:\Program Files"

Also, if your command prompt is not open to C:\, then using cd alone can't change drives.

Use

cd /d %Pathname%

or

pushd %Pathname%

instead.

Where are my postgres *.conf files?

nantha=# SHOW config_file;

config_file

/var/lib/postgresql/data/postgresql.conf (1 row)

nantha=# SHOW hba_file;

hba_file

/var/lib/postgresql/data/pg_hba.conf (1 row)

SQL Server 2005 Using DateAdd to add a day to a date

The following query i have used in sql-server 2008, it may be help you.

For add day  DATEADD(DAY,20,GETDATE())

*20 is the day quantity

Login to remote site with PHP cURL

This is how I solved this in ImpressPages:

//initial request with login data

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php');
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name');  //could be empty, but cause problems on some hosts
curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp');  //could be empty, but cause problems on some hosts
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

//another request preserving the session

curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile');
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

How do I get the name of the rows from the index of a data frame?

df.index

  • outputs the row names as pandas Index object.

list(df.index)

  • casts to a list.

df.index['Row 2':'Row 5']

  • supports label slicing similar to columns.

Problem in running .net framework 4.0 website on iis 7.0

In our case the solution to this problem did not involve the "ISAPI and CGI Restrictions" settings. The error started occuring after operations staff had upgraded the server to .NET 4.5 by accident, then downgraded to .NET 4.0 again. This caused some of the IIS websites to forget their respective correct application pools, and it caused some of the application pools to switch from .NET Framework 4.0 to 2.0. Changing these settings back fixed the problem.

Difference between HashMap and Map in Java..?

HashMap is an implementation of Map. Map is just an interface for any type of map.

Responsive image align center bootstrap 3

You can use property of d-block here or you can use a parent div with property 'text-center' in bootstrap or 'text-align: center' in css.

Image by default is displayed as inline-block, you need to display it as block in order to center it with .mx-auto. This can be done with built-in .d-block:

<div>
    <img class="mx-auto d-block" src="...">  
</div>

Or leave it as inline-block and wrapped it in a div with .text-center:

<div class="text-center">
    <img src="...">  
</div>

Print current call stack from a method in Python code

inspect.stack() returns the current stack rather than the exception traceback:

import inspect
print inspect.stack()

See https://gist.github.com/FredLoney/5454553 for a log_stack utility function.

How get value from URL

There are two ways to get variable from URL in PHP:

When your URL is: http://www.example.com/index.php?id=7 you can get this id via $_GET['id'] or $_REQUEST['id'] command and store in $id variable.

Lest's take a look:

// url is www.example.com?id=7

//get id from url via $_GET['id'] command:
$id = $_GET['id']

same will be:

//get id from url via $_REQUEST['id'] command:
$id = $_REQUEST['id']

the difference is that variables can be passed to file via URL or via POST method.

if variable is passed through url, then you can get it with $_GET['variable_name'] or $_REQUEST['variable_name'] but if variable is posted, then you need to you $_POST['variable_name'] or $_REQUEST['variable_name']

So as you see $_REQUEST['variable_name'] can be used in both ways.

P.S: Also remember - never do like this: $results = mysql_query("SELECT * FROM next WHERE id=$id"); it may cause MySQL Injection and your database can be hacked.

Try to use:

$results = mysql_query("SELECT * FROM next WHERE id='".mysql_real_escape_string($id)."'");

Include jQuery in the JavaScript Console

Turnkey solution :

Put your code in yourCode_here function. And prevent HTML without HEAD tag.

_x000D_
_x000D_
(function(head) {_x000D_
  var jq = document.createElement('script');_x000D_
  jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js";_x000D_
  ((head && head[0]) || document.firstChild).appendChild(jq);_x000D_
})(document.getElementsByTagName('head'));_x000D_
_x000D_
function jQueryReady() {_x000D_
  if (window.jQuery) {_x000D_
    jQuery.noConflict();_x000D_
    yourCode_here(jQuery);_x000D_
  } else {_x000D_
    setTimeout(jQueryReady, 100);_x000D_
  }_x000D_
}_x000D_
_x000D_
jQueryReady();_x000D_
_x000D_
function yourCode_here($) {_x000D_
  console.log("OK");_x000D_
  $("body").html("<h1>Hello world !</h1>");_x000D_
}
_x000D_
_x000D_
_x000D_

Reasons for a 409/Conflict HTTP error when uploading a file to sharepoint using a .NET WebRequest?

I encountered similar issue when uploading a file returned 409.

Besides issues mentioned above it can also happen due to file size restrictions for POST on the server side. For example, tomcat (java web server) have POST size limit of 2MB by default.

Compiler error: "class, interface, or enum expected"

class, interface, or enum expected

The above error is even possible when import statement is miss spelled. A proper statement is "import com.company.HelloWorld;"

If by mistake while code writing/editing it is miss written like "t com.company.HelloWorld;"

compiler will show "class, interface, or enum expected"

Angular2 RC6: '<component> is not a known element'

I received this error when I imported Module A into Module B, and then tried to use a component from Module A in Module B.

The solution is to declare that component in the exports array.

@NgModule({
  declarations: [
    MyComponent
  ],
  exports: [
    MyComponent
  ]
})
export class ModuleA {}
@NgModule({
  imports: [
    ModuleA
  ]
})
export class ModuleB {}

How do I detect the Python version at runtime?

To make the scripts compatible with Python2 and 3 i use :

from sys import version_info
if version_info[0] < 3:
    from __future__ import print_function

How to remove items from a list while iterating?

In some situations, where you're doing more than simply filtering a list one item at time, you want your iteration to change while iterating.

Here is an example where copying the list beforehand is incorrect, reverse iteration is impossible and a list comprehension is also not an option.

""" Sieve of Eratosthenes """

def generate_primes(n):
    """ Generates all primes less than n. """
    primes = list(range(2,n))
    idx = 0
    while idx < len(primes):
        p = primes[idx]
        for multiple in range(p+p, n, p):
            try:
                primes.remove(multiple)
            except ValueError:
                pass #EAFP
        idx += 1
        yield p

How to reload/refresh jQuery dataTable?

if using datatable v1.10.12 then simply calling .draw() method and passing your required draw types ie full-reset, page then you will re-draw your dt with new data

let dt = $("#my-datatable").datatable()

// do some action

dt.draw('full-reset')

for more check out datatable docs

how to realize countifs function (excel) in R

library(matrixStats)
> data <- rbind(c("M", "F", "M"), c("Student", "Analyst", "Analyst"))
> rowCounts(data, value = 'M') # output = 2 0
> rowCounts(data, value = 'F') # output = 1 0

Pip - Fatal error in launcher: Unable to create process using '"'

I met the the same error as you.that is because i had transplanted my python file from D disk to e disk. after that ,when I inputed python ,it worked. pip and other exe file which has the same path as pip ,it did not work. when "python -m pip install --upgrade pip" order was inputed,pip order worked,but other exe file which has the same path as pip did not work,so i think it is not the best way. at last I unistalled my python,and re-install it.everything is okay.maybe it is not the best way for all of you ,but it is for me.

How to select specified node within Xpath node sets by index with Selenium?

There is no i in XPath.

Either you use literal numbers: //img[@title='Modify'][1]

Or you build the expression string dynamically: '//img[@title='Modify']['+i+']' (but keep in mind that dynamic XPath expressions do not work from within XSLT).

Or does XPath support specified selection of nodes which are not under same parent node?

Yes: (//img[@title='Modify'])[13]


This //img[@title='Modify'][i] means "any <img> with a title of 'Modify' and a child element named <i>."

Eclipse copy/paste entire line keyboard shortcut

For mac, shift+alt+down_arrow works in netbeans' editor.

How should I tackle --secure-file-priv in MySQL?

I created a NodeJS import script if you are running nodeJS and you data is in the following form (double quote + comma and \n new line)

INSERT INTO <your_table> VALUEs( **CSV LINE **)

This one is configured to run on http://localhost:5000/import.

I goes line by line and creates query string

"city","city_ascii","lat","lng","country","iso2","iso3","id"
"Tokyo","Tokyo","35.6850","139.7514","Japan","JP","JPN","1392685764",
...

server.js

const express = require('express'),
   cors = require('cors'),
   bodyParser = require('body-parser'),
   cookieParser = require('cookie-parser'),
   session = require('express-session'),
   app = express(),
   port = process.env.PORT || 5000,
   pj = require('./config/config.json'),
   path = require('path');

app.use(bodyParser.json());
app.use(cookieParser());
app.use(cors());


app.use(
   bodyParser.urlencoded({
      extended: false,
   })
);

var Import = require('./routes/ImportRoutes.js');

app.use('/import', Import);
if (process.env.NODE_ENV === 'production') {
   // set static folder
   app.use(express.static('client/build'));

   app.get('*', (req, res) => {
      res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
   });
}

app.listen(port, function () {
   console.log('Server is running on port: ' + port);
});

ImportRoutes.js

const express = require('express'),
   cors = require('cors'),
   fs = require('fs-extra'),
   byline = require('byline'),
   db = require('../database/db'),
   importcsv = express.Router();

importcsv.use(cors());

importcsv.get('/csv', (req, res) => {

   function processFile() {
      return new Promise((resolve) => {
         let first = true;
         var sql, sqls;
         var stream = byline(
            fs.createReadStream('../PATH/TO/YOUR!!!csv', {
               encoding: 'utf8',
            })
         );

         stream
            .on('data', function (line, err) {
               if (line !== undefined) {
                  sql = 'INSERT INTO <your_table> VALUES (' + line.toString() + ');';
                  if (first) console.log(sql);
                  first = false;
                  db.sequelize.query(sql);
               }
            })
            .on('finish', () => {
               resolve(sqls);
            });
      });
   }

   async function startStream() {
      console.log('started stream');
      const sqls = await processFile();
      res.end();
      console.log('ALL DONE');
   }

   startStream();
});

module.exports = importcsv;

db.js is the config file

const Sequelize = require('sequelize');
const db = {};
const sequelize = new Sequelize(
   config.global.db,
   config.global.user,
   config.global.password,
   {
      host: config.global.host,
      dialect: 'mysql',
      logging: console.log,
      freezeTableName: true,

      pool: {
         max: 5,
         min: 0,
         acquire: 30000,
         idle: 10000,
      },
   }
);

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

Disclaimer: This is not a perfect solution - I am only posting it for devs who are under a timeline and have lots of data to import and are encountering this ridiculous issue. I lost a lot of time on this and I hope to spare another dev the same lost time.

JSON and XML comparison

Faster is not an attribute of JSON or XML or a result that a comparison between those would yield. If any, then it is an attribute of the parsers or the bandwidth with which you transmit the data.

Here is (the beginning of) a list of advantages and disadvantages of JSON and XML:


JSON

Pro:

  • Simple syntax, which results in less "markup" overhead compared to XML.
  • Easy to use with JavaScript as the markup is a subset of JS object literal notation and has the same basic data types as JavaScript.
  • JSON Schema for description and datatype and structure validation
  • JsonPath for extracting information in deeply nested structures

Con:

  • Simple syntax, only a handful of different data types are supported.

  • No support for comments.


XML

Pro:

  • Generalized markup; it is possible to create "dialects" for any kind of purpose
  • XML Schema for datatype, structure validation. Makes it also possible to create new datatypes
  • XSLT for transformation into different output formats
  • XPath/XQuery for extracting information in deeply nested structures
  • built in support for namespaces

Con:

  • Relatively wordy compared to JSON (results in more data for the same amount of information).

So in the end you have to decide what you need. Obviously both formats have their legitimate use cases. If you are mostly going to use JavaScript then you should go with JSON.

Please feel free to add pros and cons. I'm not an XML expert ;)

What is a "static" function in C?

A static function is one that can be called on the class itself, as opposed to an instance of the class.

For example a non-static would be:

Person* tom = new Person();
tom->setName("Tom");

This method works on an instance of the class, not the class itself. However you can have a static method that can work without having an instance. This is sometimes used in the Factory pattern:

Person* tom = Person::createNewPerson();

Apache: The requested URL / was not found on this server. Apache

In httpd.conf file you need to remove #

#LoadModule rewrite_module modules/mod_rewrite.so

after removing # line will look like this:

LoadModule rewrite_module modules/mod_rewrite.so

And Apache restart

How to trigger click event on href element

I do not have factual evidence to prove this but I already ran into this issue. It seems that triggering a click() event on an <a> tag doesn't seem to behave the same way you would expect with say, a input button.

The workaround I employed was to set the location.href property on the window which causes the browser to load the request resource like so:

$(document).ready(function()
{
      var href = $('.cssbuttongo').attr('href');
      window.location.href = href; //causes the browser to refresh and load the requested url
   });
});

Edit:

I would make a js fiddle but the nature of the question intermixed with how jsfiddle uses an iframe to render code makes that a no go.

@Nullable annotation usage

It makes it clear that the method accepts null values, and that if you override the method, you should also accept null values.

It also serves as a hint for code analyzers like FindBugs. For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning.

Regex for empty string or white space

If one only cares about whitespace at the beginning and end of the string (but not in the middle), then another option is to use String.trim():

"    your string contents  ".trim();

// => "your string contents"

How to install a .ipa file into my iPhone?

You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.

Checking if a list of objects contains a property with a specific value

Further to the other answers suggesting LINQ, another alternative in this case would be to use the FindAll instance method:

List<SampleClass> results = myList.FindAll(x => x.Name == nameToExtract);

A non well formed numeric value encountered

Because you are passing a string as the second argument to the date function, which should be an integer.

string date ( string $format [, int $timestamp = time() ] )

Try strtotime which will Parse about any English textual datetime description into a Unix timestamp (integer):

date("d", strtotime($_GET['start_date']));

Dismissing a Presented View Controller

Swift 3.0 //Dismiss View Controller in swift

self.navigationController?.popViewController(animated: true)
dismiss(animated: true, completion: nil)

How to get the device's IMEI/ESN programmatically in android?

You'll need the following permission in your AndroidManifest.xml:

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

To get IMEI (international mobile equipment identifier) and if It is above API level 26 then we get telephonyManager.getImei() as null so for that, we use ANDROID_ID as a Unique Identifier.

 public static String getIMEINumber(@NonNull final Context context)
            throws SecurityException, NullPointerException {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String imei;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            assert tm != null;
            imei = tm.getImei();
            //this change is for Android 10 as per security concern it will not provide the imei number.
            if (imei == null) {
                imei = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            }
        } else {
            assert tm != null;
            if (tm.getDeviceId() != null && !tm.getDeviceId().equals("000000000000000")) {
                imei = tm.getDeviceId();
            } else {
                imei = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            }
        }

        return imei;
    }

XPath to select element based on childs child value

Almost there. In your predicate, you want a relative path, so change

./book[/author/name = 'John'] 

to either

./book[author/name = 'John'] 

or

./book[./author/name = 'John'] 

and you will match your element. Your current predicate goes back to the root of the document to look for an author.

Removing the title text of an iOS UIBarButtonItem

Swift 3.1 You can do this by implementing the delegate method of UINavigationController. It'll hide the Title with back button only, we'll still get the back arrow image and default functionality.

func navigationController(_ navigationController: UINavigationController, 
  willShow viewController: UIViewController, animated: Bool) {
        let item = UIBarButtonItem(title: " ", style: .plain, target: nil, 
                    action: nil)
        viewController.navigationItem.backBarButtonItem = item
    }

How to get a variable value if variable name is stored as string?

For my fellow zsh users, the way to accomplish the same thing as the accepted answer is to use:

${(P)a}

It is appropriately called Parameter name replacement

This forces the value of the parameter name to be interpreted as a further parameter name, whose value will be used where appropriate. Note that flags set with one of the typeset family of commands (in particular case transformations) are not applied to the value of name used in this fashion.

If used with a nested parameter or command substitution, the result of that will be taken as a parameter name in the same way. For example, if you have ‘foo=bar’ and ‘bar=baz’, the strings ${(P)foo}, ${(P)${foo}}, and ${(P)$(echo bar)} will be expanded to ‘baz’.

Likewise, if the reference is itself nested, the expression with the flag is treated as if it were directly replaced by the parameter name. It is an error if this nested substitution produces an array with more than one word. For example, if ‘name=assoc’ where the parameter assoc is an associative array, then ‘${${(P)name}[elt]}’ refers to the element of the associative subscripted ‘elt’.

How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

Apparently, there was a /Users/myusername/local folder that contained a include with node and lib with node and node_modules. How and why this was created instead of in my /usr/local folder, I do not know.

Deleting these local references fixed the phantom v0.6.1-pre. If anyone has an explanation, I'll choose that as the correct answer.

EDIT:

You may need to do the additional instructions as well:

sudo rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/{npm*,node*,man1/node*}

which is the equivalent of (same as above)...

sudo rm -rf /usr/local/bin/npm /usr/local/share/man/man1/node* /usr/local/lib/dtrace/node.d ~/.npm ~/.node-gyp 

or (same as above) broken down...

To completely uninstall node + npm is to do the following:

  1. go to /usr/local/lib and delete any node and node_modules
  2. go to /usr/local/include and delete any node and node_modules directory
  3. if you installed with brew install node, then run brew uninstall node in your terminal
  4. check your Home directory for any local or lib or include folders, and delete any node or node_modules from there
  5. go to /usr/local/bin and delete any node executable

You may also need to do:

sudo rm -rf /opt/local/bin/node /opt/local/include/node /opt/local/lib/node_modules
sudo rm -rf /usr/local/bin/npm /usr/local/share/man/man1/node.1 /usr/local/lib/dtrace/node.d

Additionally, NVM modifies the PATH variable in $HOME/.bashrc, which must be reverted manually.

Then download nvm and follow the instructions to install node. The latest versions of node come with npm, I believe, but you can also reinstall that as well.

Handling warning for possible multiple enumeration of IEnumerable

If the aim is really to prevent multiple enumerations than the answer by Marc Gravell is the one to read, but maintaining the same semantics you could simple remove the redundant Any and First calls and go with:

public List<object> Foo(IEnumerable<object> objects)
{
    if (objects == null)
        throw new ArgumentNullException("objects");

    var first = objects.FirstOrDefault();

    if (first == null)
        throw new ArgumentException(
            "Empty enumerable not supported.", 
            "objects");

    var list = DoSomeThing(first);  

    var secondList = DoSomeThingElse(objects);

    list.AddRange(secondList);

    return list;
}

Note, that this assumes that you IEnumerable is not generic or at least is constrained to be a reference type.

How to get cumulative sum

Without using any type of JOIN cumulative salary for a person fetch by using follow query:

SELECT * , (
  SELECT SUM( salary ) 
  FROM  `abc` AS table1
  WHERE table1.ID <=  `abc`.ID
    AND table1.name =  `abc`.Name
) AS cum
FROM  `abc` 
ORDER BY Name

How to solve could not create the virtual machine error of Java Virtual Machine Launcher?

I was facing the same issue while i was using "jdk-10.0.1_windows-x64_bin" and eclipse-jee-oxygen-3a-win32-x86_64 on Windows 64 bit Operating System.

But Finally i resolved this issue by changing my jdk to "jdk-8u172-windows-x64", Now its working fine. @Thanks

How do I recognize "#VALUE!" in Excel spreadsheets?

in EXCEL 2013 i had to use IF function 2 times: 1st to identify error with ISERROR and 2nd to identify the specific type of error by ERROR.TYPE=3 in order to address this type of error. This way you can differentiate between error you want and other types.

What is the simplest way to convert array to vector?

You're asking the wrong question here - instead of forcing everything into a vector ask how you can convert test to work with iterators instead of a specific container. You can provide an overload too in order to retain compatibility (and handle other containers at the same time for free):

void test(const std::vector<int>& in) {
  // Iterate over vector and do whatever
}

becomes:

template <typename Iterator>
void test(Iterator begin, const Iterator end) {
    // Iterate over range and do whatever
}

template <typename Container>
void test(const Container& in) {
    test(std::begin(in), std::end(in));
}

Which lets you do:

int x[3]={1, 2, 3};
test(x); // Now correct

(Ideone demo)

How do I register a DLL file on Windows 7 64-bit?

On a x64 system, system32 is for 64 bit and syswow64 is for 32 bit (not the other way around as stated in another answer). WOW (Windows on Windows) is the 32 bit subsystem that runs under the 64 bit subsystem).

It's a mess in naming terms, and serves only to confuse, but that's the way it is.

Again ...

syswow64 is 32 bit, NOT 64 bit.

system32 is 64 bit, NOT 32 bit.

There is a regsrv32 in each of these directories. One is 64 bit, and the other is 32 bit. It is the same deal with odbcad32 and et al. (If you want to see 32-bit ODBC drivers which won't show up with the default odbcad32 in system32 which is 64-bit.)

Multiline editing in Visual Studio Code

(Windows 10 pro x64) Here have some ways!

  1. Alt + click

  2. Alt + Ctrl + up/down

  3. Keybindings: Ctrl + click (??? it doesn't work!)

Enter image description here

Docker-Compose can't connect to Docker Daemon

I found this and it seemed to fix my issue.

GitHub Fix Docker Daemon Crash

I changed the content of my docker-compose-deps.yml file as seen in the link. Then I ran docker-compose -f docker-compose-deps.yml up -d. Then I changed it back and it worked for some reason. I didn't have to continue the steps in the link I provided, but the first two steps fixed the issue for me.

Is there a command line utility for rendering GitHub flavored Markdown?

pandoc with browser works well for me.

Usage: cat README.md | pandoc -f markdown_github | browser

Installation (Assuming you are using Mac OSX):

  • $ brew install pandoc

  • $ brew install browser

Or on Debian/Ubuntu: apt-get install pandoc browser

Error creating bean with name 'entityManagerFactory

Adding dependencies didn't fix the issue at my end.

The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.

I removed the additional fields from the @Entity class and it worked.

Preloading images with JavaScript

I can confirm that the approach in the question is sufficient to trigger the images to be downloaded and cached (unless you have forbidden the browser from doing so via your response headers) in, at least:

  • Chrome 74
  • Safari 12
  • Firefox 66
  • Edge 17

To test this, I made a small webapp with several endpoints that each sleep for 10 seconds before serving a picture of a kitten. Then I added two webpages, one of which contained a <script> tag in which each of the kittens is preloaded using the preloadImage function from the question, and the other of which includes all the kittens on the page using <img> tags.

In all the browsers above, I found that if I visited the preloader page first, waited a while, and then went to the page with the <img> tags, my kittens rendered instantly. This demonstrates that the preloader successfully loaded the kittens into the cache in all browsers tested.

You can see or try out the application I used to test this at https://github.com/ExplodingCabbage/preloadImage-test.

Note in particular that this technique works in the browsers above even if the number of images being looped over exceeds the number of parallel requests that the browser is willing to make at a time, contrary to what Robin's answer suggests. The rate at which your images preload will of course be limited by how many parallel requests the browser is willing to send, but it will eventually request each image URL you call preloadImage() on.

check if a key exists in a bucket in s3 using boto3

FWIW, here are the very simple functions that I am using

import boto3

def get_resource(config: dict={}):
    """Loads the s3 resource.

    Expects AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY to be in the environment
    or in a config dictionary.
    Looks in the environment first."""

    s3 = boto3.resource('s3',
                        aws_access_key_id=os.environ.get(
                            "AWS_ACCESS_KEY_ID", config.get("AWS_ACCESS_KEY_ID")),
                        aws_secret_access_key=os.environ.get("AWS_SECRET_ACCESS_KEY", config.get("AWS_SECRET_ACCESS_KEY")))
    return s3


def get_bucket(s3, s3_uri: str):
    """Get the bucket from the resource.
    A thin wrapper, use with caution.

    Example usage:

    >> bucket = get_bucket(get_resource(), s3_uri_prod)"""
    return s3.Bucket(s3_uri)


def isfile_s3(bucket, key: str) -> bool:
    """Returns T/F whether the file exists."""
    objs = list(bucket.objects.filter(Prefix=key))
    return len(objs) == 1 and objs[0].key == key


def isdir_s3(bucket, key: str) -> bool:
    """Returns T/F whether the directory exists."""
    objs = list(bucket.objects.filter(Prefix=key))
    return len(objs) > 1

Fire event on enter key press for a textbox

<asp:Panel ID="Panel2" runat="server" DefaultButton="bttxt">
    <telerik:RadNumericTextBox ID="txt" runat="server">
    </telerik:RadNumericTextBox>
    <asp:LinkButton ID="bttxt" runat="server" Style="display: none;" OnClick="bttxt_Click" />
</asp:Panel>

 

protected void txt_TextChanged(object sender, EventArgs e)
{
    //enter code here
}

Can I force pip to reinstall the current version?

In the case you need to force the reinstallation of pip itself you can do:

python -m pip install --upgrade --force-reinstall pip

How do I check if a number is a palindrome?

Golang version:

package main

import "fmt"

func main() {
    n := 123454321
    r := reverse(n)
    fmt.Println(r == n)
}

func reverse(n int) int {
    r := 0
    for {
        if n > 0 {
            r = r*10 + n%10
            n = n / 10
        } else {
            break
        }
    }
    return r
}

Remove pandas rows with duplicate indices

If anyone like me likes chainable data manipulation using the pandas dot notation (like piping), then the following may be useful:

df3 = df3.query('~index.duplicated()')

This enables chaining statements like this:

df3.assign(C=2).query('~index.duplicated()').mean()

Find all files with name containing string

Use find:

find . -maxdepth 1 -name "*string*" -print

It will find all files in the current directory (delete maxdepth 1 if you want it recursive) containing "string" and will print it on the screen.

If you want to avoid file containing ':', you can type:

find . -maxdepth 1 -name "*string*" ! -name "*:*" -print

If you want to use grep (but I think it's not necessary as far as you don't want to check file content) you can use:

ls | grep touch

But, I repeat, find is a better and cleaner solution for your task.

Difference between using "chmod a+x" and "chmod 755"

Yes - different

chmod a+x will add the exec bits to the file but will not touch other bits. For example file might be still unreadable to others and group.

chmod 755 will always make the file with perms 755 no matter what initial permissions were.

This may or may not matter for your script.

Align div right in Bootstrap 3

Do you mean something like this:

HTML

<div class="row">
  <div class="container">

    <div class="col-md-4">
      left content
    </div>

    <div class="col-md-4 col-md-offset-4">

      <div class="yellow-background">
        text
        <div class="pull-right">right content</div>  
      </div>

    </div>
  </div>
</div>

CSS

.yellow-background {
  background: blue;
}

.pull-right {
  background: yellow;
}

A full example can be found on Codepen.

Java Currency Number format

you should do something like this:

public static void main(String[] args) {
    double d1 = 100d;
    double d2 = 100.1d;
    print(d1);
    print(d2);
}

private static void print(double d) {
    String s = null;
    if (Math.round(d) != d) {
        s = String.format("%.2f", d);
    } else {
        s = String.format("%.0f", d);
    }
    System.out.println(s);
}

which prints:

100

100,10

How do you search an amazon s3 bucket?

Not a technical answer, but I have built an application which allows for wildcard search: https://bucketsearch.net/

It will asynchronously index your bucket and then allow you to search the results.

It's free to use (donationware).

HTML list-style-type dash

HTML

<ul>
  <li>One</li>
  <li>Very</li>
  <li>Simple</li>
  <li>Approach!</li>
</ul>

CSS

ul {
  list-style-type: none;
}

ul li:before {
  content: '-';
  position: absolute;
  margin-left: -20px;
}`

How to pass json POST data to Web API method as an object?

Working with POST in webapi can be tricky! Would like to add to the already correct answer..

Will focus specifically on POST as dealing with GET is trivial. I don't think many would be searching around for resolving an issue with GET with webapis. Anyways..

If your question is - In MVC Web Api, how to- - Use custom action method names other than the generic HTTP verbs? - Perform multiple posts? - Post multiple simple types? - Post complex types via jQuery?

Then the following solutions may help:

First, to use Custom Action Methods in Web API, add a web api route as:

public static void Register(HttpConfiguration config)
{
    config.Routes.MapHttpRoute(
        name: "ActionApi",
        routeTemplate: "api/{controller}/{action}");
}

And then you may create action methods like:

[HttpPost]
public string TestMethod([FromBody]string value)
{
    return "Hello from http post web api controller: " + value;
}

Now, fire the following jQuery from your browser console

$.ajax({
    type: 'POST',
    url: 'http://localhost:33649/api/TestApi/TestMethod',
    data: {'':'hello'},
    contentType: 'application/x-www-form-urlencoded',
    dataType: 'json',
    success: function(data){ console.log(data) }
});

Second, to perform multiple posts, It is simple, create multiple action methods and decorate with the [HttpPost] attrib. Use the [ActionName("MyAction")] to assign custom names, etc. Will come to jQuery in the fourth point below

Third, First of all, posting multiple SIMPLE types in a single action is not possible. Moreover, there is a special format to post even a single simple type (apart from passing the parameter in the query string or REST style). This was the point that had me banging my head with Rest Clients (like Fiddler and Chrome's Advanced REST client extension) and hunting around the web for almost 5 hours when eventually, the following URL proved to be of help. Will quote the relevant content for the link might turn dead!

Content-Type: application/x-www-form-urlencoded
in the request header and add a = before the JSON statement:
={"Name":"Turbo Tina","Email":"[email protected]"}

PS: Noticed the peculiar syntax?

http://forums.asp.net/t/1883467.aspx?The+received+value+is+null+when+I+try+to+Post+to+my+Web+Api

Anyways, let us get over that story. Moving on:

Fourth, posting complex types via jQuery, ofcourse, $.ajax() is going to promptly come in the role:

Let us say the action method accepts a Person object which has an id and a name. So, from javascript:

var person = { PersonId:1, Name:"James" }
$.ajax({
    type: 'POST',
    url: 'http://mydomain/api/TestApi/TestMethod',
    data: JSON.stringify(person),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function(data){ console.log(data) }
});

And the action will look like:

[HttpPost]
public string TestMethod(Person person)
{
    return "Hello from http post web api controller: " + person.Name;
}

All of the above, worked for me!! Cheers!

How to detect when cancel is clicked on file input?

Combining Shiboe's and alx's solutions, i've got the most reliable code:

var selector = $('<input/>')
   .attr({ /* just for example, use your own attributes */
      "id": "FilesSelector",
      "name": "File",
      "type": "file",
      "contentEditable": "false" /* if you "click" on input via label, this prevents IE7-8 from just setting caret into file input's text filed*/
   })
   .on("click.filesSelector", function () {
      /* do some magic here, e.g. invoke callback for selection begin */
      var cancelled = false; /* need this because .one calls handler once for each event type */
      setTimeout(function () {
         $(document).one("mousemove.filesSelector focusin.filesSelector", function () {
            /* namespace is optional */
            if (selector.val().length === 0 && !cancelled) {
               cancelled = true; /* prevent double cancel */
               /* that's the point of cancel,   */
            }
         });                    
      }, 1); /* 1 is enough as we just need to delay until first available tick */
   })
   .on("change.filesSelector", function () {
      /* do some magic here, e.g. invoke callback for successful selection */
   })
   .appendTo(yourHolder).end(); /* just for example */

Generally, mousemove event does the trick, but in case user made a click and than:

  • cancelled file open dialog by escape key (without moving a mouse), made another accurate click to open file dialog again...
  • switched focus to any other application, than came back to browser's file open dialog and closed it, than opened again via enter or space key...

... we won't get mousemove event hence no cancel callback. Moreover, if user cancels second dialog and makes a mouse move, we'll get 2 cancel callbacks. Fortunately, special jQuery focusIn event bubbles up to the document in both cases, helping us to avoid such situations. The only limitation is if one blocks focusIn event either.

Writing a dictionary to a csv file with one line for every 'key: value'

outfile = open( 'dict.txt', 'w' )
for key, value in sorted( mydict.items() ):
    outfile.write( str(key) + '\t' + str(value) + '\n' )

How do I concatenate two text files in PowerShell?

Since most of the other replies often get the formatting wrong (due to the piping), the safest thing to do is as follows:

add-content $YourMasterFile -value (get-content $SomeAdditionalFile)

I know you wanted to avoid reading the content of $SomeAdditionalFile into a variable, but in order to save for example your newline formatting i do not think there is proper way to do it without.

A workaround would be to loop through your $SomeAdditionalFile line by line and piping that into your $YourMasterFile. However this is overly resource intensive.

Is it better to use std::memcpy() or std::copy() in terms to performance?

My rule is simple. If you are using C++ prefer C++ libraries and not C :)

Linq filter List<string> where it contains a string value from another List<string>

Try the following:

var filteredFileSet = fileList.Where(item => filterList.Contains(item));

When you iterate over filteredFileSet (See LINQ Execution) it will consist of a set of IEnumberable values. This is based on the Where Operator checking to ensure that items within the fileList data set are contained within the filterList set.

As fileList is an IEnumerable set of string values, you can pass the 'item' value directly into the Contains method.

The Completest Cocos2d-x Tutorial & Guide List

Good list. The Angry Ninjas Starter Kit will have a Cocos2d-X update soon.

How to get the last element of an array in Ruby?

Use -1 index (negative indices count backward from the end of the array):

a[-1] # => 5
b[-1] # => 6

or Array#last method:

a.last # => 5
b.last # => 6

HTML Mobile -forcing the soft keyboard to hide

Scott S's answer worked perfectly.

I was coding a web-based phone dialpad for mobile, and every time the user would press a number on the keypad (composed of td span elements in a table), the softkeyboard would pop up. I also wanted the user to not be able to tap into the input box of the number being dialed. This actually solved both problems in 1 shot. The following was used:

<input type="text" id="phone-number" onfocus="blur();" />

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

You can also use extremely small numbers for your radius'.

<corners 
  android:bottomRightRadius="0.1dp" android:bottomLeftRadius="2dp" 
 android:topLeftRadius="2dp" android:topRightRadius="0.1dp" />

What does getActivity() mean?

Two likely definitions:

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

I found this detailed post about how to open (attach) the MDF file in SQL Server Management Studio: http://learningsqlserver.wordpress.com/2011/02/13/how-can-i-open-mdf-and-ldf-files-in-sql-server-attach-tutorial-troublshooting/

I also have the issue of not being able to navigate to the file. The reason is most likely this:

The reason it won't "open" the folder is because the service account running the SQL Server Engine service does not have read permission on the folder in question. Assign the windows user group for that SQL Server instance the rights to read and list contents at the WINDOWS level. Then you should see the files that you want to attach inside of the folder.

(source: http://social.msdn.microsoft.com/Forums/sqlserver/en-US/c80d8e6a-4665-4be8-b9f5-37eaaa677226/cannot-navigate-to-some-folders-when-attempting-to-attach-mdf-files-to-database-in-management?forum=sqlkjmanageability)

One solution to this problem is described here: http://technet.microsoft.com/en-us/library/jj219062.aspx I haven't tried this myself yet. Once I do, I'll update the answer.

Hope this helps.

Display text from .txt file in batch file

Try this: use Find to iterate through all lines with "Current date/time", and write each line to the same file:

for /f "usebackq delims==" %i in (`find "Current date" log.txt`) do (echo %i > log-time.txt)
type log-time.txt

Set delims= to a character not relevant in the date/time lines. Use %%i in batch files.

Explanation (update):

Find extracts all lines from log.txt containing the search string.

For /f loops through each line the command inside (...) generates.

As echo > log-time.txt (single > !) overwrites log-time.txt every time it's executed, only the last matching line remains in log-time.txt

Can an Android Toast be longer than Toast.LENGTH_LONG?

This text will disappear in 5 seconds.

    final Toast toast = Toast.makeText(getApplicationContext(), "My Text", Toast.LENGTH_SHORT);
    toast.show();

    Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
           @Override
           public void run() {
               toast.cancel(); 
           }
    }, 5000); // Change to what you want

Edit: As Itai Spector in comment said it will be shown about 3.5 seconds, So use this code:

    int toastDuration = 5000; // in MilliSeconds
    Toast mToast = Toast.makeText(this, "My text", Toast.LENGTH_LONG);
    CountDownTimer countDownTimer;
    countDownTimer = new CountDownTimer(toastDuration, 1000) {
        public void onTick(long millisUntilFinished) {
            mToast.show();
        }

        public void onFinish() {
            mToast.cancel();
        }
    };

    mToast.show();
    countDownTimer.start();

How to index characters in a Golang string?

Interpreted string literals are character sequences between double quotes "" using the (possibly multi-byte) UTF-8 encoding of individual characters. In UTF-8, ASCII characters are single-byte corresponding to the first 128 Unicode characters. Strings behave like slices of bytes. A rune is an integer value identifying a Unicode code point. Therefore,

package main

import "fmt"

func main() {
    fmt.Println(string("Hello"[1]))              // ASCII only
    fmt.Println(string([]rune("Hello, ??")[1])) // UTF-8
    fmt.Println(string([]rune("Hello, ??")[8])) // UTF-8
}

Output:

e
e
?

Read:

Go Programming Language Specification section on Conversions.

The Go Blog: Strings, bytes, runes and characters in Go

What are database constraints?

constraints are conditions, that can validate specific condition. Constraints related with database are Domain integrity, Entity integrity, Referential Integrity, User Defined Integrity constraints etc.

Android - java.lang.SecurityException: Permission Denial: starting Intent

This is only for android studio

So I ran into this problem recently. The issue was in the build/run configuration. Apparently android studio had chosen an activity in my project as the launch activity thus disregarding my choice in the manifest file.

Click on the module name just to the left of the run button and click on "Edit configurations..." Now make sure "Launch default Activity" is selected.

The funny thing when I got this error was that I could still launch the app with from the device and it starts with the preferred Activity. But launching from the IDE seemed impossible.

Getting "cannot find Symbol" in Java project in Intellij

I know this thread is old but, another solution was to run

$ mvn clean install -Dmaven.test.skip=true

And on IntelliJ do CMD + Shift + A (mac os) -> type "Reimport all Maven projects".

If that doesn't work, try forcing maven dependencies to be re-downloaded

$ mvn clean -U install -Dmaven.test.skip=true

Find duplicates and delete all in notepad++

You could use

Click TextFX ? Click TextFX Tools ? Click Sort lines case insensitive (at column) Duplicates and blank lines have been removed and the data has been sorted alphabetically.

as indicated above. However, the way I did it because I need to replace the duplicates by blank lines and not just remove the lines, once sorted alphabetically:

REPLACE:
((^.*$)(\n))(?=\k<1>)

by

$3

This will convert:

Shorts
Shorts
Shorts
Shorts
Shorts
Shorts Two Pack
Shorts Two Pack
Signature Braces
Signature Braces
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers

to:

Shorts

Shorts Two Pack

Signature Braces










Signature Cotton Trousers

That's how I did it because I specifically needed those lines.

How to install easy_install in Python 2.7.1 on Windows 7

I recently used ez_setup.py as well and I did a tutorial on how to install it. The tutorial has snapshots and simple to follow. You can find it below:

Installing easy_install Using ez_setup.py

I hope you find this helpful.

Storing image in database directly or as base64 data?

I recommend looking at modern databases like NoSQL and also I agree with user1252434's post. For instance I am storing a few < 500kb PNGs as base64 on my Mongo db with binary set to true with no performance hit at all. Mongo can be used to store large files like 10MB videos and that can offer huge time saving advantages in metadata searches for those videos, see storing large objects and files in mongodb.

how to implement a pop up dialog box in iOS

For Swift 3 & Swift 4 :

Since UIAlertView is deprecated, there is the good way for display Alert on Swift 3

let alertController = UIAlertController(title: NSLocalizedString("No network connection",comment:""), message: NSLocalizedString("connected to the internet to use this app.",comment:""), preferredStyle: .alert)
let defaultAction = UIAlertAction(title:     NSLocalizedString("Ok", comment: ""), style: .default, handler: { (pAlert) in
                //Do whatever you want here
        })
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)

Deprecated :

This is the swift version inspired by the checked response :

Display AlertView :

   let alert = UIAlertView(title: "No network connection", 
                           message: "You must be connected to the internet to use this app.", delegate: nil, cancelButtonTitle: "Ok")
    alert.delegate = self
    alert.show()

Add the delegate to your view controller :

class AgendaViewController: UIViewController, UIAlertViewDelegate

When user click on button, this code will be executed :

func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {


}

How to convert nanoseconds to seconds using the TimeUnit enum?

Well, you could just divide by 1,000,000,000:

long elapsedTime = end - start;
double seconds = (double)elapsedTime / 1_000_000_000.0;

If you use TimeUnit to convert, you'll get your result as a long, so you'll lose decimal precision but maintain whole number precision.

How to receive POST data in django

You should have access to the POST dictionary on the request object.

At runtime, find all classes in a Java application that extend a base class

Java dynamically loads classes, so your universe of classes would be only those that have already been loaded (and not yet unloaded). Perhaps you can do something with a custom class loader that could check the supertypes of each loaded class. I don't think there's an API to query the set of loaded classes.

Read a Csv file with powershell and capture corresponding data

Old topic, but never clearly answered. I've been working on similar as well, and found the solution:

The pipe (|) in this code sample from Austin isn't the delimiter, but to pipe the ForEach-Object, so if you want to use it as delimiter, you need to do this:

Import-Csv H:\Programs\scripts\SomeText.csv -delimiter "|" |`
ForEach-Object {
    $Name += $_.Name
    $Phone += $_."Phone Number"
}

Spent a good 15 minutes on this myself before I understood what was going on. Hope the answer helps the next person reading this avoid the wasted minutes! (Sorry for expanding on your comment Austin)

How to create a backup of a single table in a postgres database?

I was trying to run pg_dump from within psql command prompt and I was not able to trace output file anywhere on my ubuntu 20.04 box. I tried finding by find / -name "myfilename.sql".

Instead When I tried pg_dump from /home/ubuntu, I found my output file in /home/ubuntu

wkhtmltopdf: cannot connect to X server

Problem is probably in old version of wkhtmltopdf - version 0.9 from distribution repository require running X server, but current version - 0.12.2.1 doesnt require it - can run headless.

Download package for your distribution from http://wkhtmltopdf.org/downloads.html and install it - for Ubuntu:

sudo apt-get install xfonts-75dpi
sudo dpkg -i wkhtmltox-0.12.2.1_linux-trusty-amd64.deb

Format certain floating dataframe columns into percentage in pandas

Often times we are interested in calculating the full significant digits, but for the visual aesthetics, we may want to see only few decimal point when we display the dataframe.

In jupyter-notebook, pandas can utilize the html formatting taking advantage of the method called style.

For the case of just seeing two significant digits of some columns, we can use this code snippet:

Given dataframe

import numpy as np
import pandas as pd

df = pd.DataFrame({'var1': [1.458315, 1.576704, 1.629253, 1.6693310000000001, 1.705139, 1.740447, 1.77598, 1.812037, 1.85313, 1.9439849999999999],
          'var2': [1.500092, 1.6084450000000001, 1.652577, 1.685456, 1.7120959999999998, 1.741961, 1.7708009999999998, 1.7993270000000001, 1.8229819999999999, 1.8684009999999998],
          'var3': [-0.0057090000000000005, -0.005122, -0.0047539999999999995, -0.003525, -0.003134, -0.0012230000000000001, -0.0017230000000000001, -0.002013, -0.001396, 0.005732]})

print(df)
       var1      var2      var3
0  1.458315  1.500092 -0.005709
1  1.576704  1.608445 -0.005122
2  1.629253  1.652577 -0.004754
3  1.669331  1.685456 -0.003525
4  1.705139  1.712096 -0.003134
5  1.740447  1.741961 -0.001223
6  1.775980  1.770801 -0.001723
7  1.812037  1.799327 -0.002013
8  1.853130  1.822982 -0.001396
9  1.943985  1.868401  0.005732

Style to get required format

    df.style.format({'var1': "{:.2f}",'var2': "{:.2f}",'var3': "{:.2%}"})

Gives:

var1    var2    var3
id          
0   1.46    1.50    -0.57%
1   1.58    1.61    -0.51%
2   1.63    1.65    -0.48%
3   1.67    1.69    -0.35%
4   1.71    1.71    -0.31%
5   1.74    1.74    -0.12%
6   1.78    1.77    -0.17%
7   1.81    1.80    -0.20%
8   1.85    1.82    -0.14%
9   1.94    1.87    0.57%

Update

If display command is not found try following:

from IPython.display import display

df_style = df.style.format({'var1': "{:.2f}",'var2': "{:.2f}",'var3': "{:.2%}"})

display(df_style)

Requirements

  • To use display command, you need to have installed Ipython in your machine.
  • The display command does not work in online python interpreter which do not have IPyton installed such as https://repl.it/languages/python3
  • The display command works in jupyter-notebook, jupyter-lab, Google-colab, kaggle-kernels, IBM-watson,Mode-Analytics and many other platforms out of the box, you do not even have to import display from IPython.display

JavaScript equivalent of PHP’s die

use firebug and the glorious...

debugger;

and never let the debugger make any step forward. Cleaner than throwing a proper Error, innit?

How to write trycatch in R

Here goes a straightforward example:

# Do something, or tell me why it failed
my_update_function <- function(x){
    tryCatch(
        # This is what I want to do...
        {
        y = x * 2
        return(y)
        },
        # ... but if an error occurs, tell me what happened: 
        error=function(error_message) {
            message("This is my custom message.")
            message("And below is the error message from R:")
            message(error_message)
            return(NA)
        }
    )
}

If you also want to capture a "warning", just add warning= similar to the error= part.

Deserialize JSON into C# dynamic object?

Deserializing in JSON.NET can be dynamic using the JObject class, which is included in that library. My JSON string represents these classes:

public class Foo {
   public int Age {get;set;}
   public Bar Bar {get;set;}
}

public class Bar {
   public DateTime BDay {get;set;}
}

Now we deserialize the string WITHOUT referencing the above classes:

var dyn = JsonConvert.DeserializeObject<JObject>(jsonAsFooString);

JProperty propAge = dyn.Properties().FirstOrDefault(i=>i.Name == "Age");
if(propAge != null) {
    int age = int.Parse(propAge.Value.ToString());
    Console.WriteLine("age=" + age);
}

//or as a one-liner:
int myage = int.Parse(dyn.Properties().First(i=>i.Name == "Age").Value.ToString());

Or if you want to go deeper:

var propBar = dyn.Properties().FirstOrDefault(i=>i.Name == "Bar");
if(propBar != null) {
    JObject o = (JObject)propBar.First();
    var propBDay = o.Properties().FirstOrDefault (i => i.Name=="BDay");
    if(propBDay != null) {
        DateTime bday = DateTime.Parse(propBDay.Value.ToString());
        Console.WriteLine("birthday=" + bday.ToString("MM/dd/yyyy"));
    }
}

//or as a one-liner:
DateTime mybday = DateTime.Parse(((JObject)dyn.Properties().First(i=>i.Name == "Bar").First()).Properties().First(i=>i.Name == "BDay").Value.ToString());

See post for a complete example.

About catching ANY exception

You can but you probably shouldn't:

try:
    do_something()
except:
    print "Caught it!"

However, this will also catch exceptions like KeyboardInterrupt and you usually don't want that, do you? Unless you re-raise the exception right away - see the following example from the docs:

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

Docker is installed but Docker Compose is not ? why?

just use brew:

brew install docker-compose

Return a `struct` from a function in C

There is no issue in passing back a struct. It will be passed by value

But, what if the struct contains any member which has a address of a local variable

struct emp {
    int id;
    char *name;
};

struct emp get() {
    char *name = "John";

    struct emp e1 = {100, name};

    return (e1);
}

int main() {

    struct emp e2 = get();

    printf("%s\n", e2.name);
}

Now, here e1.name contains a memory address local to the function get(). Once get() returns, the local address for name would have been freed up. SO, in the caller if we try to access that address, it may cause segmentation fault, as we are trying a freed address. That is bad..

Where as the e1.id will be perfectly valid as its value will be copied to e2.id

So, we should always try to avoid returning local memory addresses of a function.

Anything malloced can be returned as and when wanted

Should CSS always preceed Javascript?

Updated 2017-12-16

I was not sure about the tests in OP. I decided to experiment a little and ended up busting some of the myths.

Synchronous <script src...> will block downloading of the resources below it until it is downloaded and executed

This is no longer true. Have a look at the waterfall generated by Chrome 63:

<head>
<script src="//alias-0.redacted.com/payload.php?type=js&amp;delay=333&amp;rand=1"></script>
<script src="//alias-1.redacted.com/payload.php?type=js&amp;delay=333&amp;rand=2"></script>
<script src="//alias-2.redacted.com/payload.php?type=js&amp;delay=333&amp;rand=3"></script>
</head>

Chrome net inspector -> waterfall

<link rel=stylesheet> will not block download and execution of scripts below it

This is incorrect. The stylesheet will not block download but it will block execution of the script (little explanation here). Have a look at performance chart generated by Chrome 63:

<link href="//alias-0.redacted.com/payload.php?type=css&amp;delay=666" rel="stylesheet">
<script src="//alias-1.redacted.com/payload.php?type=js&amp;delay=333&amp;block=1000"></script>

Chrome dev tools -> performance


Keeping the above in mind, the results in OP can be explained as follows:

CSS First:

CSS Download  500ms:<------------------------------------------------>
JS Download   400ms:<-------------------------------------->
JS Execution 1000ms:                                                  <-------------------------------------------------------------------------------------------------->
DOM Ready   @1500ms:                                                                                                                                                      ?

JS First:

JS Download   400ms:<-------------------------------------->
CSS Download  500ms:<------------------------------------------------>
JS Execution 1000ms:                                        <-------------------------------------------------------------------------------------------------->
DOM Ready   @1400ms:                                                                                                                                            ?

How do I see which checkbox is checked?

If you don't know which checkboxes your page has (ex: if you are creating them dynamically) you can simply put a hidden field with the same name and 0 value right above the checkbox.

<input type="hidden" name="foo" value="0" />
<input type="checkbox" name="foo" value="1">

This way you will get 1 or 0 based on whether the checkbox is selected or not.

How to reset the state of a Redux store?

In addition to Dan Abramov's answer, shouldn't we explicitly set action as action = {type: '@@INIT'} alongside state = undefined. With above action type, every reducer returns the initial state.

highlight the navigation menu for the current page

You can set the id of the body of the page to some value that represents the current page. Then for each element in the menu you set a class specific to that menu item. And within your CSS you can set up a rule that will highlight the menu item specifically...

That probably didn't make much sense, so here's an example:

<body id="index">
<div id="menu">
 <ul>
  <li class="index"     ><a href="index.html">Index page</a></li>
  <li class="page1"     ><a href="page1.html">Page 1</a></li>
 </ul>
</div> <!-- menu -->
</body>

In the page1.html, you would set the id of the body to: id="page1".

Finally in your CSS you have something like the following:

#index #menu .index, #page1 #menu .page1 {
  font-weight: bold;
}

You would need to alter the ID for each page, but the CSS remains the same, which is important as the CSS is often cached and can require a forced refresh to update.

It's not dynamic, but it's one method that's simple to do, and you can just include the menu html from a template file using PHP or similar.

How to check if a DateTime field is not null or empty?

DateTime is not standard nullable type. If you want assign null to DateTime type of variable, you have to use DateTime? type which supports null value.

If you only want test your variable to be set (e.g. variable holds other than default value), you can use keyword "default" like in following code:

if (dateTimeVariable == default(DateTime))
{
    //do work for dateTimeVariable == null situation
}

Cannot push to Git repository on Bitbucket

Writing this for those just getting started with Git and BitBucket on Windows & who are not as familiar with Bash (since this is both a common issue and a high ranking Google result when searching for the error message within the question).

For those who don't mind HTTPS and who are looking for a quick fix, scroll to the bottom of this answer for instructions under FOR THE LAZY

For those looking to solve the actual problem, follow the instructions below:

Fixing the SSH issue as fast as possible

This is a set of instructions derived from the URL linked to by VonC. It was modified to be as resilient and succinct as possible.

  • Don't type the $ or any lines that do not begin with $ (the $ means this is something you type into GitBash).

  • Open GitBash

Set your global info if you haven't already:

$ git config --global user.name "Your Name"
$ git config --global user.email "[email protected]"

Check for OpenSSH:

$ ssh -v localhost
OpenSSH_4.6p1, OpenSSL...

See something like that?

  • Yes: Continue.
  • No: Skip to the FOR THE LAZY section or follow the linked article from VonC.

See if you have generated the keys already:

$ ls -a ~/.ssh/id_*

If there are two files, you can skip the next step.

$ ssh-keygen

Leave everything as the defaults, enter a passphrase. You should now see results with this command:

$ ls -a ~/.ssh/id_*

Check for an existing config file:

$ ls -a ~/.ssh/config

If you get a result, check this file for erroneous information. If no file exists, do the following:

$ echo "Host bitbucket.org" >> ~/.ssh/config
$ echo " IdentityFile ~/.ssh/id_rsa" >> ~/.ssh/config

Confirm the contents:

$ cat ~/.ssh/config

Host bitbucket.org
 IdentityFile ~/.ssh/id_rsa
  • The single space before "IdentityFile" is required.

Check you are starting the SSH agent every time you run GitBash:

$ cat ~/.bashrc
  • If you see a function called start_agent, this step has already been completed.
  • If no file, continue.
  • If there is a file that does not contain this function, you're in a sticky situation. It's probably safe to append to it (using the instructions below) but it may not be! If unsure, make a backup of your .bashrc before following the instructions below or skip ahead to FOR THE LAZY section.

Enter the following into GitBash to create your .bashrc file:

$ echo "SSH_ENV=$HOME/.ssh/environment" >> ~/.bashrc
$ echo "" >> ~/.bashrc
$ echo "# start the ssh-agent" >> ~/.bashrc
$ echo "function start_agent {" >> ~/.bashrc
$ echo "    echo \"Initializing new SSH agent...\"" >> ~/.bashrc
$ echo "    # spawn ssh-agent" >> ~/.bashrc
$ echo "    /usr/bin/ssh-agent | sed 's/^echo/#echo/' > \"\${SSH_ENV}\"" >> ~/.bashrc
$ echo "    echo succeeded" >> ~/.bashrc
$ echo "    chmod 600 \"\${SSH_ENV}\"" >> ~/.bashrc
$ echo "    . \"\${SSH_ENV}\" > /dev/null" >> ~/.bashrc
$ echo "    /usr/bin/ssh-add" >> ~/.bashrc
$ echo "}" >> ~/.bashrc
$ echo "" >> ~/.bashrc
$ echo "if [ -f \"\${SSH_ENV}\" ]; then" >> ~/.bashrc
$ echo "     . \"\${SSH_ENV}\" > /dev/null" >> ~/.bashrc
$ echo "     ps -ef | grep \${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {" >> ~/.bashrc
$ echo "        start_agent;" >> ~/.bashrc
$ echo "    }" >> ~/.bashrc
$ echo "else" >> ~/.bashrc
$ echo "    start_agent;" >> ~/.bashrc
$ echo "fi" >> ~/.bashrc

Verify the file was created successfully (yours should only differ where "yourusername" appears):

$ cat ~/.bashrc
SSH_ENV=/c/Users/yourusername/.ssh/environment

# start the ssh-agent
function start_agent {
    echo "Initializing new SSH agent..."
    # spawn ssh-agent
    /usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
    echo succeeded
    chmod 600 "${SSH_ENV}"
    . "${SSH_ENV}" > /dev/null
    /usr/bin/ssh-add
}

if [ -f "${SSH_ENV}" ]; then
     . "${SSH_ENV}" > /dev/null
     ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
        start_agent;
    }
else
    start_agent;
fi
  • Close GitBash and re-open it.
  • You should be asked for your passphrase (for the SSH file you generated earlier).
  • If no prompt, you either did not set a passphrase or GitBash isn't running the .bashrc script (which would be odd so consider reviewing the contents of it!). If you are running this on a Mac(OS X), .bashrc isn't executed by default - .bash_profile is. To fix this, put this snippet in your .bash_profile: [[ -s ~/.bashrc ]] && source ~/.bashrc

If you didn't enter a passphrase, you would have seen something like this when starting GitBash:

Initializing new SSH agent...
succeeded
Identity added: /c/Users/yourusername/.ssh/id_rsa (/c/Users/yourusername/.ssh/id_rsa)

And the following should return results:

$ ssh-add -l

However, if you get the following from ssh-add -l:

Could not open a connection to your authentication agent.

It didn't spawn the SSH agent and your .bashrc is likely the cause.

If, when starting GitBash, you see this:

Initializing new SSH agent...
sh.exe": : No such file or directory

That means you forgot to escape the $ with a \ when echoing to the file (ie. the variables were expanded). Re-create your .bashrc to resolve this.

Verify the agent is running and your keys have been added:

$ ssh-add -l

Should return something similar to this:

2048 0f:37:21:af:1b:31:d5:cd:65:58:b2:68:4a:ba:a2:46 /Users/yourusername/.ssh/id_rsa (RSA)

Run the following command to get your public key:

$ cat ~/.ssh/id_rsa.pub

(it should return something starting with "ssh-rsa ......"

  • Click the GitBash window icon
  • Click Edit
  • Click Mark
  • Highlight the public key using your mouse (including the leading ssh-rsa bit and the trailing == [email protected] bit)
  • Right-click the window (performs a copy)
  • Paste your public key into Notepad.
  • Delete all the newlines such that it is only a single line.
  • Press CTRL+A then CTRL+C to copy the public key again to your clipboard.

Configure your private key with BitBucket by performing the following steps:

  • Open your browser and navigate to the BitBucket.org site
  • Login to BitBucket.org
  • Click your avatar (top-right)
  • Click Manage Account
  • Click SSH Keys (under Security on the left-hand menu)
  • Click Add Key
  • Enter Global Public Key for the Label
  • Paste the public key you copied from Notepad

A Global Public Key entry should now be visible in your list of keys.

  • Return to GitBash
  • cd into the directory containing your project
  • Change your origin to the SSH variation (it will not be if you ran the FOR THE LAZY steps)

Check your remotes:

$ git remote -v

Switch to the SSH url:

$ git remote set-url origin [email protected]:youraccount/yourproject.git

Check things are in working order:

$ git remote show origin

You should see something like this:

Warning: Permanently added the RSA host key for IP address '...' to the list of known hosts.
* remote origin
  Fetch URL: [email protected]:youruser/yourproject.git
  Push  URL: [email protected]:youruser/yourproject.git
  HEAD branch: master
  Remote branch:
    master tracked
  Local ref configured for 'git push':
    master pushes to master (fast-forwardable)

DONE!

You can opt to use HTTPS instead of SSH. It will require you to type your password during remote operations (it's cached temporarily after you type it once). Here is how you can configure HTTPS:

FOR THE LAZY

You should fix the SSH issue as described by VonC; however, if you're in a rush to commit and don't have the tools/time/knowledge to generate a new public key right now, set your origin to the HTTPS alternative:

> https://[email protected]/accountname/reponame.git

Using a GUI tool such as TortoiseGit or command line tools.

Here is the documentation of this alternative origin URL.

Command line to add an origin if one does not exist:

git remote add origin https://[email protected]/accountname/reponame.git

Command line to change an existing origin:

git remote set-url origin https://[email protected]/accountname/reponame.git

NOTE: your account name is not your email.

You may also want to set your global info:

git config --global user.name "Your Name"
git config --global user.email "[email protected]"

Then try your push again (no need to commit again)

git push origin master

Can I use multiple "with"?

Try:

With DependencedIncidents AS
(
    SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
    (
        SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A 
        CROSS JOIN [Incident] AS X
            WHERE
                patindex('%' + A.[Col] + '%', X.[SQL]) > 0
    ) AS INC
),
lalala AS
(
    SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
    (
        SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A 
        CROSS JOIN [Incident] AS X
            WHERE
                patindex('%' + A.[Col] + '%', X.[SQL]) > 0
    ) AS INC
)

And yes, you can reference common table expression inside common table expression definition. Even recursively. Which leads to some very neat tricks.

How to provide user name and password when connecting to a network share

You can either change the thread identity, or P/Invoke WNetAddConnection2. I prefer the latter, as I sometimes need to maintain multiple credentials for different locations. I wrap it into an IDisposable and call WNetCancelConnection2 to remove the creds afterwards (avoiding the multiple usernames error):

using (new NetworkConnection(@"\\server\read", readCredentials))
using (new NetworkConnection(@"\\server2\write", writeCredentials)) {
   File.Copy(@"\\server\read\file", @"\\server2\write\file");
}

How to set the env variable for PHP?

For windows: Go to your "system properties" please.then follow as bellow.

Advanced system settings(from left sidebar)->Environment variables(very last option)->path(from lower box/system variables called as I know)->edit

then concatenate the "php" location you have in your pc (usually it is where your xampp is installed say c:/xampp/php)

N.B : Please never forget to set semicolon (;) between your recent concatenated path and the existed path in your "Path"

Something like C:\Program Files\Git\usr\bin;C:\xampp\php

Hope this will help.Happy coding. :) :)

How to force deletion of a python object?

  1. Add an exit handler that closes all the bars.
  2. __del__() gets called when the number of references to an object hits 0 while the VM is still running. This may be caused by the GC.
  3. If __init__() raises an exception then the object is assumed to be incomplete and __del__() won't be invoked.

How to rename JSON key

If you want to rename all occurrences of some key you can use a regex with the g option. For example:

var json = [{"_id":"1","email":"[email protected]","image":"some_image_url","name":"Name 1"},{"_id":"2","email":"[email protected]","image":"some_image_url","name":"Name 2"}];

str = JSON.stringify(json);

now we have the json in string format in str.

Replace all occurrences of "_id" to "id" using regex with the g option:

str = str.replace(/\"_id\":/g, "\"id\":");

and return to json format:

json = JSON.parse(str);

now we have our json with the wanted key name.

What's onCreate(Bundle savedInstanceState)

onCreate(Bundle savedInstanceState) you will get the Bundle null when activity get starts first time and it will get in use when activity orientation get changed .......

http://www.gitshah.com/2011/03/how-to-handle-screen-orientation_28.html

Android provides another elegant way of achieving this. To achieve this, we have to override a method called onSaveInstanceState(). Android platform allows the users to save any instance state. Instance state can be saved in the Bundle. Bundle is passed as argument to the onSaveInstanceState method.

we can load the saved instance state from the Bundle passed as argument to the onCreate method. We can also load the saved instance state in onRestoreInstanceState method. But I will leave that for the readers to figure out.

MVC - Set selected value of SelectList

Why are you trying to set the value after you create the list? My guess is you are creating the list in your model instead of in your view. I recommend creating the underlying enumerable in your model and then using this to build the actual SelectList:

<%= Html.DropDownListFor(m => m.SomeValue, new SelectList(Model.ListOfValues, "Value", "Text", Model.SomeValue)) %>

That way your selected value is always set just as the view is rendered and not before. Also, you don't have to put any unnecessary UI classes (i.e. SelectList) in your model and it can remain unaware of the UI.

How to match "any character" in regular expression?

[^] should match any character, including newline. [^CHARS] matches all characters except for those in CHARS. If CHARS is empty, it matches all characters.

JavaScript example:

/a[^]*Z/.test("abcxyz \0\r\n\t012789ABCXYZ") // Returns ‘true’.

HTML5 video - show/hide controls programmatically

<video id="myvideo">
  <source src="path/to/movie.mp4" />
</video>

<p onclick="toggleControls();">Toggle</p>

<script>
var video = document.getElementById("myvideo");

function toggleControls() {
  if (video.hasAttribute("controls")) {
     video.removeAttribute("controls")   
  } else {
     video.setAttribute("controls","controls")   
  }
}
</script>

See it working on jsFiddle: http://jsfiddle.net/dgLds/

How is an HTTP POST request made in node.js?

There are dozens of open-source libraries available that you can use to making an HTTP POST request in Node.

1. Axios (Recommended)

const axios = require('axios');

const data = {
    name: 'John Doe',
    job: 'Content Writer'
};

axios.post('https://reqres.in/api/users', data)
    .then((res) => {
        console.log(`Status: ${res.status}`);
        console.log('Body: ', res.data);
    }).catch((err) => {
        console.error(err);
    });

2. Needle

const needle = require('needle');

const data = {
    name: 'John Doe',
    job: 'Content Writer'
};

needle('post', 'https://reqres.in/api/users', data, {json: true})
    .then((res) => {
        console.log(`Status: ${res.statusCode}`);
        console.log('Body: ', res.body);
    }).catch((err) => {
        console.error(err);
    });

3. Request

const request = require('request');

const options = {
    url: 'https://reqres.in/api/users',
    json: true,
    body: {
        name: 'John Doe',
        job: 'Content Writer'
    }
};

request.post(options, (err, res, body) => {
    if (err) {
        return console.log(err);
    }
    console.log(`Status: ${res.statusCode}`);
    console.log(body);
});

4. Native HTTPS Module

const https = require('https');

const data = JSON.stringify({
    name: 'John Doe',
    job: 'Content Writer'
});

const options = {
    hostname: 'reqres.in',
    path: '/api/users',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': data.length
    }
};


const req = https.request(options, (res) => {
    let data = '';

    console.log('Status Code:', res.statusCode);

    res.on('data', (chunk) => {
        data += chunk;
    });

    res.on('end', () => {
        console.log('Body: ', JSON.parse(data));
    });

}).on("error", (err) => {
    console.log("Error: ", err.message);
});

req.write(data);
req.end();

For details, check out this article.

Static image src in Vue.js template

declare new variable that the value contain the path of image

const imgLink = require('../../assets/your-image.png')

then call the variable

export default {
    name: 'onepage',
    data(){
        return{
            img: imgLink,
        }
    }
}

bind that on html, this the example:

<a href="#"><img v-bind:src="img" alt="" class="logo"></a>

hope it will help

Creating a segue programmatically

well , you can create and also can subclass the UIStoryBoardSegue . subclassing is mostly used for giving custom transition animation.

you can see video of wwdc 2011 introducing StoryBoard. its available in youtube also.

http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIStoryboardSegue_Class/Reference/Reference.html#//apple_ref/occ/cl/UIStoryboardSegue

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

CORS: credentials mode is 'include'

If it helps, I was using centrifuge with my reactjs app, and, after checking some comments below, I looked at the centrifuge.js library file, which in my version, had the following code snippet:

if ('withCredentials' in xhr) {
 xhr.withCredentials = true;
}

After I removed these three lines, the app worked fine, as expected.

Hope it helps!

Can we define min-margin and max-margin, max-padding and min-padding in css?

Comming late to the party, as said above there unfortunately is no such thing as max-margin. A sollution that helped me is to place a div above the item you want to have the max-margin applied to.

<body style="width:90vw; height:90vh;">
    <div name="parrentdiv/body" style="width:300px; height:100%; background-color: blue">
        <div name="margin top" style="width:300px; height:50%; min-height:200px; background-color: red"></div>
        <div name="item" style="width:300px; height:180px; background-color: lightgrey">Hello World!</div>
    </div>
</body>

Run above coded snippet in full page and resize the window to see this working. The lightgreypart will have the margin-top of 50% and a 'min-margin-top' of 200px. This margin is the red div (wich you can hide with display: none; if you want to). The blue part is what's left of the body.

I hope this will help people with the same problem in the future.

CMake output/build directory

There's little need to set all the variables you're setting. CMake sets them to reasonable defaults. You should definitely not modify CMAKE_BINARY_DIR or CMAKE_CACHEFILE_DIR. Treat these as read-only.

First remove the existing problematic cache file from the src directory:

cd src
rm CMakeCache.txt
cd ..

Then remove all the set() commands and do:

cd Compile && rm -rf *
cmake ../src

As long as you're outside of the source directory when running CMake, it will not modify the source directory unless your CMakeList explicitly tells it to do so.

Once you have this working, you can look at where CMake puts things by default, and only if you're not satisfied with the default locations (such as the default value of EXECUTABLE_OUTPUT_PATH), modify only those you need. And try to express them relative to CMAKE_BINARY_DIR, CMAKE_CURRENT_BINARY_DIR, PROJECT_BINARY_DIR etc.

If you look at CMake documentation, you'll see variables partitioned into semantic sections. Except for very special circumstances, you should treat all those listed under "Variables that Provide Information" as read-only inside CMakeLists.

How do I view Android application specific cache?

Cached files are indeed stored in /data/data/my_app_package/cache

Make sure to store the files using the following method:

String cacheDir = context.getCacheDir();
File imageFile = new File(cacheDir, "image1.jpg");
FileOutputStream out = new FileOutputStream(imageFile);
out.write(imagebuffer, 0, imagebufferlength);

where imagebuffer[] contains image data in byte format and imagebufferlength is the length of the content to be written to the FileOutputStream.

Now, you may look at DDMS File Explorer or do an "adb shell" and cd to /data/data/my_app_package/cache and do an "ls". You will find the image files you have stored through code in this directory.

Moreover, from Android documentation:

If you'd like to cache some data, rather than store it persistently, you should use getCacheDir() to open a File that represents the internal directory where your application should save temporary cache files.

When the device is low on internal storage space, Android may delete these cache files to recover space. However, you should not rely on the system to clean up these files for you. You should always maintain the cache files yourself and stay within a reasonable limit of space consumed, such as 1MB. When the user uninstalls your application, these files are removed.

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

Well, I'm late.


In your image, the paper is white, while the background is colored. So, it's better to detect the paper is Saturation(???) channel in HSV color space. Take refer to wiki HSL_and_HSV first. Then I'll copy most idea from my answer in this Detect Colored Segment in an image.


Main steps:

  1. Read into BGR
  2. Convert the image from bgr to hsv space
  3. Threshold the S channel
  4. Then find the max external contour(or do Canny, or HoughLines as you like, I choose findContours), approx to get the corners.

This is my result:

enter image description here


The Python code(Python 3.5 + OpenCV 3.3):

#!/usr/bin/python3
# 2017.12.20 10:47:28 CST
# 2017.12.20 11:29:30 CST

import cv2
import numpy as np

##(1) read into  bgr-space
img = cv2.imread("test2.jpg")

##(2) convert to hsv-space, then split the channels
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h,s,v = cv2.split(hsv)

##(3) threshold the S channel using adaptive method(`THRESH_OTSU`) or fixed thresh
th, threshed = cv2.threshold(s, 50, 255, cv2.THRESH_BINARY_INV)

##(4) find all the external contours on the threshed S
#_, cnts, _ = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]

canvas  = img.copy()
#cv2.drawContours(canvas, cnts, -1, (0,255,0), 1)

## sort and choose the largest contour
cnts = sorted(cnts, key = cv2.contourArea)
cnt = cnts[-1]

## approx the contour, so the get the corner points
arclen = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.02* arclen, True)
cv2.drawContours(canvas, [cnt], -1, (255,0,0), 1, cv2.LINE_AA)
cv2.drawContours(canvas, [approx], -1, (0, 0, 255), 1, cv2.LINE_AA)

## Ok, you can see the result as tag(6)
cv2.imwrite("detected.png", canvas)

Related answers:

  1. How to detect colored patches in an image using OpenCV?
  2. Edge detection on colored background using OpenCV
  3. OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection
  4. How to use `cv2.findContours` in different OpenCV versions?

Algorithm to calculate the number of divisors of a given number

Here is a function that I wrote. it's worst time complexity is O(sqrt(n)),best time on the other hand is O(log(n)). It gives you all the prime divisors along with the number of its occurence.

public static List<Integer> divisors(n) {   
    ArrayList<Integer> aList = new ArrayList();
    int top_count = (int) Math.round(Math.sqrt(n));
    int new_n = n;

    for (int i = 2; i <= top_count; i++) {
        if (new_n == (new_n / i) * i) {
            aList.add(i);
            new_n = new_n / i;
            top_count = (int) Math.round(Math.sqrt(new_n));
            i = 1;
        }
    }
    aList.add(new_n);
    return aList;
}

destination path already exists and is not an empty directory

An engineered way to solve this if you already have files you need to push to Github/Server:

  1. In Github/Server where your repo will live:

    • Create empty Git Repo (Save <YourPathAndRepoName>)
    • $git init --bare
  2. Local Computer (Just put in any folder):

    • $touch .gitignore
    • (Add files you want to ignore in text editor to .gitignore)
    • $git clone <YourPathAndRepoName>

    • (This will create an empty folder with your Repo Name from Github/Server)

    • (Legitimately copy and paste all your files from wherever and paste them into this empty Repo)

    • $git add . && git commit -m "First Commit"

    • $git push origin master

How to get access to job parameters from ItemReader, in Spring Batch?

Did you declare the jobparameters as map properly as bean?

Or did you perhaps accidently instantiate a JobParameters object, which has no getter for the filename?

For more on expression language you can find information in Spring documentation here.

Restart pods when configmap updates in Kubernetes?

The best way I've found to do it is run Reloader

It allows you to define configmaps or secrets to watch, when they get updated, a rolling update of your deployment is performed. Here's an example:

You have a deployment foo and a ConfigMap called foo-configmap. You want to roll the pods of the deployment every time the configmap is changed. You need to run Reloader with:

kubectl apply -f https://raw.githubusercontent.com/stakater/Reloader/master/deployments/kubernetes/reloader.yaml

Then specify this annotation in your deployment:

kind: Deployment
metadata:
  annotations:
    configmap.reloader.stakater.com/reload: "foo-configmap"
  name: foo
...

Best approach to converting Boolean object to string in java

I don't think there would be any significant performance difference between them, but I would prefer the 1st way.

If you have a Boolean reference, Boolean.toString(boolean) will throw NullPointerException if your reference is null. As the reference is unboxed to boolean before being passed to the method.

While, String.valueOf() method as the source code shows, does the explicit null check:

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

Just test this code:

Boolean b = null;

System.out.println(String.valueOf(b));    // Prints null
System.out.println(Boolean.toString(b));  // Throws NPE

For primitive boolean, there is no difference.

Check if null Boolean is true results in exception

Or with the power of Java 8 Optional, you also can do such trick:

Optional.ofNullable(boolValue).orElse(false)

:)

How to convert Nonetype to int or string?

int(value or 0)

This will use 0 in the case when you provide any value that Python considers False, such as None, 0, [], "", etc. Since 0 is False, you should only use 0 as the alternative value (otherwise you will find your 0s turning into that value).

int(0 if value is None else value)

This replaces only None with 0. Since we are testing for None specifically, you can use some other value as the replacement.

On Duplicate Key Update same as insert

There is a MySQL specific extension to SQL that may be what you want - REPLACE INTO

However it does not work quite the same as 'ON DUPLICATE UPDATE'

  1. It deletes the old row that clashes with the new row and then inserts the new row. So long as you don't have a primary key on the table that would be fine, but if you do, then if any other table references that primary key

  2. You can't reference the values in the old rows so you can't do an equivalent of

    INSERT INTO mytable (id, a, b, c) values ( 1, 2, 3, 4) 
    ON DUPLICATE KEY UPDATE
    id=1, a=2, b=3, c=c + 1;
    

I'd like to use the work around to get the ID to!

That should work — last_insert_id() should have the correct value so long as your primary key is auto-incrementing.

However as I said, if you actually use that primary key in other tables, REPLACE INTO probably won't be acceptable to you, as it deletes the old row that clashed via the unique key.

Someone else suggested before you can reduce some typing by doing:

INSERT INTO `tableName` (`a`,`b`,`c`) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE `a`=VALUES(`a`), `b`=VALUES(`b`), `c`=VALUES(`c`);

How to set the text/value/content of an `Entry` widget using a button in tkinter

You can choose between the following two methods to set the text of an Entry widget. For the examples, assume imported library import tkinter as tk and root window root = tk.Tk().


  • Method A: Use delete and insert

    Widget Entry provides methods delete and insert which can be used to set its text to a new value. First, you'll have to remove any former, old text from Entry with delete which needs the positions where to start and end the deletion. Since we want to remove the full old text, we start at 0 and end at wherever the end currently is. We can access that value via END. Afterwards the Entry is empty and we can insert new_text at position 0.

    entry = tk.Entry(root)
    new_text = "Example text"
    entry.delete(0, tk.END)
    entry.insert(0, new_text)
    

  • Method B: Use StringVar

    You have to create a new StringVar object called entry_text in the example. Also, your Entry widget has to be created with keyword argument textvariable. Afterwards, every time you change entry_text with set, the text will automatically show up in the Entry widget.

    entry_text = tk.StringVar()
    entry = tk.Entry(root, textvariable=entry_text)
    new_text = "Example text"
    entry_text.set(new_text)
    

  • Complete working example which contains both methods to set the text via Button:

    This window

    screenshot

    is generated by the following complete working example:

    import tkinter as tk
    
    def button_1_click():
        # define new text (you can modify this to your needs!)
        new_text = "Button 1 clicked!"
        # delete content from position 0 to end
        entry.delete(0, tk.END)
        # insert new_text at position 0
        entry.insert(0, new_text)
    
    def button_2_click():
        # define new text (you can modify this to your needs!)
        new_text = "Button 2 clicked!"
        # set connected text variable to new_text
        entry_text.set(new_text)
    
    root = tk.Tk()
    
    entry_text = tk.StringVar()
    entry = tk.Entry(root, textvariable=entry_text)
    
    button_1 = tk.Button(root, text="Button 1", command=button_1_click)
    button_2 = tk.Button(root, text="Button 2", command=button_2_click)
    
    entry.pack(side=tk.TOP)
    button_1.pack(side=tk.LEFT)
    button_2.pack(side=tk.LEFT)
    
    root.mainloop()
    

Remove folder and its contents from git/GitHub's history

I removed the bin and obj folders from old C# projects using git on windows. Be careful with

git filter-branch --tree-filter "rm -rf bin" --prune-empty HEAD

It destroys the integrity of the git installation by deleting the usr/bin folder in the git install folder.

How to create timer in angular2

You can simply use setInterval utility and use arrow function as callback so that this will point to the component instance.

For ex:

this.interval = setInterval( () => { 
    // call your functions like 
    this.getList();
    this.updateInfo();
});

Inside your ngOnDestroy lifecycle hook, clear the interval.

ngOnDestroy(){
    clearInterval(this.interval);
}

How to send a pdf file directly to the printer using JavaScript?

This is actually a lot easier using a dataURI, because you can just call print on the returned window object.

// file is a File object, this will also take a blob
const dataUrl = window.URL.createObjectURL(file);

// Open the window
const pdfWindow = window.open(dataUrl);

// Call print on it
pdfWindow.print();

This opens the pdf in a new tab and then pops the print dialog up.

How do I autoindent in Netbeans?

To format all the code in NetBeans, press Alt + Shift + F. If you want to indent lines, select the lines and press Alt + Shift + right arrow key, and to unindent, press Alt + Shift + left arrow key.

How to access array elements in a Django template?

You can access sequence elements with arr.0 arr.1 and so on. See The Django template system chapter of the django book for more information.

phpMyAdmin allow remote users

Replace the contents of the first <directory> tag.

Remove:

<Directory /usr/share/phpMyAdmin/>
 <IfModule mod_authz_core.c>
  # Apache 2.4
  <RequireAny>
    Require ip 127.0.0.1
    Require ip ::1
  </RequireAny>
 </IfModule>
 <IfModule !mod_authz_core.c>
  # Apache 2.2
  Order Deny,Allow
  Deny from All
  Allow from 127.0.0.1
  Allow from ::1
 </IfModule>
</Directory>

And place this instead:

<Directory /usr/share/phpMyAdmin/>
 Order allow,deny
 Allow from all
</Directory>

Don't forget to restart Apache afterwards.

How do I log errors and warnings into a file?

See

  • error_log — Send an error message somewhere

Example

error_log("You messed up!", 3, "/var/tmp/my-errors.log");

You can customize error handling with your own error handlers to call this function for you whenever an error or warning or whatever you need to log occurs. For additional information, please refer to the Chapter Error Handling in the PHP Manual

Serializing a list to JSON

There are two common ways of doing that with built-in JSON serializers:

  1. JavaScriptSerializer

    var serializer = new JavaScriptSerializer();
    return serializer.Serialize(TheList);
    
  2. DataContractJsonSerializer

    var serializer = new DataContractJsonSerializer(TheList.GetType());
    using (var stream = new MemoryStream())
    {
        serializer.WriteObject(stream, TheList);
        using (var sr = new StreamReader(stream))
        {
            return sr.ReadToEnd();
        }
    }
    

    Note, that this option requires definition of a data contract for your class:

    [DataContract]
    public class MyObjectInJson
    {
       [DataMember]
       public long ObjectID {get;set;}
       [DataMember]
       public string ObjectInJson {get;set;}
    }