Programs & Examples On #User32

user32.dll implements the Windows USER component that creates and manipulates the standard elements of the Windows user interface, such as the desktop, windows, and menus.

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

The FailedPreconditionError arises because the program is attempting to read a variable (named "Variable_1") before it has been initialized. In TensorFlow, all variables must be explicitly initialized, by running their "initializer" operations. For convenience, you can run all of the variable initializers in the current session by executing the following statement before your training loop:

tf.initialize_all_variables().run()

Note that this answer assumes that, as in the question, you are using tf.InteractiveSession, which allows you to run operations without specifying a session. For non-interactive uses, it is more common to use tf.Session, and initialize as follows:

init_op = tf.initialize_all_variables()

sess = tf.Session()
sess.run(init_op)

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

When I had this problem, I had literally just forgot to fill in a parameter value in the XAML of the code.

For some reason though, the exception would send me to the CS of the WPF program rather than the XAML. No idea why.

How to refresh or show immediately in datagridview after inserting?

In the form designer add a new timer using the toolbox. In properties set "Enabled" equal to "True".

enter image description here

The set the DataGridView to equal your new data in the timer

enter image description here

How to use [DllImport("")] in C#?

You can't declare an extern local method inside of a method, or any other method with an attribute. Move your DLL import into the class:

using System.Runtime.InteropServices;


public class WindowHandling
{
    [DllImport("User32.dll")]
    public static extern int SetForegroundWindow(IntPtr point);

    public void ActivateTargetApplication(string processName, List<string> barcodesList)
    {
        Process p = Process.Start("notepad++.exe");
        p.WaitForInputIdle();
        IntPtr h = p.MainWindowHandle;
        SetForegroundWindow(h);
        SendKeys.SendWait("k");
        IntPtr processFoundWindow = p.MainWindowHandle;
    }
}

Windows 7, 64 bit, DLL problems

This contribution does not really answer the initial question, but taking into account the hit-rate of this thread I assume that there are quite a few people dealing with the problem that API-MS-WIN-CORE- libraries cannot be found.

I was able to solve a problem where my application refused to start with the error message that API-MS-WIN-CORE-WINRT-STRING-L1-1-0.DLL is not found by simply updating Visual Studio.

I don't think that my build environment (Windows 7 Pro SP1, Visual Studio Ultimate 2012) was messed up completely, it worked fine for most of my projects. But under some very specific circumstances I got the error message (see below).

After updating Visual Studio 11 from the initial CD-Version (I forgot to look up the version number) to version 11.0.61030.00 Update 4 also the broken project was running again.

Error message at application startup

Error Message : Cannot find or open the PDB file

I'm also a newbie to CUDA/Visual studio and encountered the same problem with a couple of the samples. If you run DEBUG-> Start Debugging, then repeatedly step over (F10) you'll see the output window appear and get populated. Normal execution returns nomal completion status 0x0 (as you observed) and the output window is closed.

C# using Sendkey function to send a key to another application

If notepad is already started, you should write:

// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);

//...

Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
    IntPtr h = p.MainWindowHandle;
    SetForegroundWindow(h);
    SendKeys.SendWait("k");
}

GetProcessesByName returns an array of processes, so you should get the first one (or find the one you want).

If you want to start notepad and send the key, you should write:

Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");

The only situation in which the code may not work is when notepad is started as Administrator and your application is not.

Cannot find or open the PDB file in Visual Studio C++ 2010

If you have more as one Project in your Project Map use THE SAME hard coded PathFile PDB Name in all your Sub-Projects:

Use e.g.

D:\Visual Studio Projects\my_app\MyFile.pdb

Dont use e.g.

$(IntDir)\MyFile.pdb

in all the Sub-Projects !!!

= Compiler Param /Fd

PHP Curl And Cookies

Solutions which are described above, even with unique CookieFile names, can cause a lot of problems on scale.

We had to serve a lot of authentications with this solution and our server went down because of high file read write actions.

The solution for this was to use Apache Reverse Proxy and omit CURL requests at all.

Details how to use Proxy on Apache can be found here: https://httpd.apache.org/docs/2.4/howto/reverse_proxy.html

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

Try change _DEBUG to NDEBUG macro definition in C++ project properties (for Release configuration) Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions

Send Message in C#

You don't need to send messages.

Add an event to the one form and an event handler to the other. Then you can use a third project which references the other two to attach the event handler to the event. The two DLLs don't need to reference each other for this to work.

What does "#pragma comment" mean?

Pragma directives specify operating system or machine specific (x86 or x64 etc) compiler options. There are several options available. Details can be found in https://msdn.microsoft.com/en-us/library/d9x1s805.aspx

#pragma comment( comment-type [,"commentstring"] ) has this format.

Refer https://msdn.microsoft.com/en-us/library/7f0aews7.aspx for details about different comment-type.

#pragma comment(lib, "kernel32") #pragma comment(lib, "user32")

The above lines of code includes the library names (or path) that need to be searched by the linker. These details are included as part of the library-search record in the object file.

So, in this case kernel.lib and user32.lib are searched by the linker and included in the final executable.

How to use <DllImport> in VB.NET?

Imports System.Runtime.InteropServices

makefiles - compile all c files at once

SRCS=$(wildcard *.c)

OBJS=$(SRCS:.c=.o)

all: $(OBJS)

Url decode UTF-8 in Python

You can achieve an expected result with requests library as well:

import requests

url = "http://www.mywebsite.org/Data%20Set.zip"

print(f"Before: {url}")
print(f"After:  {requests.utils.unquote(url)}")

Output:

$ python3 test_url_unquote.py

Before: http://www.mywebsite.org/Data%20Set.zip
After:  http://www.mywebsite.org/Data Set.zip

Might be handy if you are already using requests, without using another library for this job.

YouTube iframe API: how do I control an iframe player that's already in the HTML?

My own version of Kim T's code above which combines with some jQuery and allows for targeting of specific iframes.

$(function() {
    callPlayer($('#iframe')[0], 'unMute');
});

function callPlayer(iframe, func, args) {
    if ( iframe.src.indexOf('youtube.com/embed') !== -1) {
        iframe.contentWindow.postMessage( JSON.stringify({
            'event': 'command',
            'func': func,
            'args': args || []
        } ), '*');
    }
}

How to add local .jar file dependency to build.gradle file?

You can add jar doing:

For gradle just put following code in build.gradle:

dependencies {
...
compile fileTree(dir: 'lib', includes: ['suitetalk-*0.jar'])
...
}

and for maven just follow steps:

For Intellij: File->project structure->modules->dependency tab-> click on + sign-> jar and dependency->select jars you want to import-> ok-> apply(if visible)->ok

Remember that if you got any java.lang.NoClassDefFoundError: Could not initialize class exception at runtime this means that dependencies in jar not installed for that you have to add all dependecies in parent project.

error LNK2001: unresolved external symbol (C++)

Sounds like you are using Microsoft Visual C++. If that is the case, then the most possibility is that you don't compile your two.cpp with one.cpp (one.cpp is the implementation for one.h).

If you are from command line (cmd.exe), then try this first: cl -o two.exe one.cpp two.cpp

If you are from IDE, right click on the project name from Solution Explore. Then choose Add, Existing Item.... Add one.cpp into your project.

Deciding between HttpClient and WebClient

Perhaps you could think about the problem in a different way. WebClient and HttpClient are essentially different implementations of the same thing. What I recommend is implementing the Dependency Injection pattern with an IoC Container throughout your application. You should construct a client interface with a higher level of abstraction than the low level HTTP transfer. You can write concrete classes that use both WebClient and HttpClient, and then use the IoC container to inject the implementation via config.

What this would allow you to do would be to switch between HttpClient and WebClient easily so that you are able to objectively test in the production environment.

So questions like:

Will HttpClient be a better design choice if we upgrade to .Net 4.5?

Can actually be objectively answered by switching between the two client implementations using the IoC container. Here is an example interface that you might depend on that doesn't include any details about HttpClient or WebClient.

/// <summary>
/// Dependency Injection abstraction for rest clients. 
/// </summary>
public interface IClient
{
    /// <summary>
    /// Adapter for serialization/deserialization of http body data
    /// </summary>
    ISerializationAdapter SerializationAdapter { get; }

    /// <summary>
    /// Sends a strongly typed request to the server and waits for a strongly typed response
    /// </summary>
    /// <typeparam name="TResponseBody">The expected type of the response body</typeparam>
    /// <typeparam name="TRequestBody">The type of the request body if specified</typeparam>
    /// <param name="request">The request that will be translated to a http request</param>
    /// <returns></returns>
    Task<Response<TResponseBody>> SendAsync<TResponseBody, TRequestBody>(Request<TRequestBody> request);

    /// <summary>
    /// Default headers to be sent with http requests
    /// </summary>
    IHeadersCollection DefaultRequestHeaders { get; }

    /// <summary>
    /// Default timeout for http requests
    /// </summary>
    TimeSpan Timeout { get; set; }

    /// <summary>
    /// Base Uri for the client. Any resources specified on requests will be relative to this.
    /// </summary>
    Uri BaseUri { get; set; }

    /// <summary>
    /// Name of the client
    /// </summary>
    string Name { get; }
}

public class Request<TRequestBody>
{
    #region Public Properties
    public IHeadersCollection Headers { get; }
    public Uri Resource { get; set; }
    public HttpRequestMethod HttpRequestMethod { get; set; }
    public TRequestBody Body { get; set; }
    public CancellationToken CancellationToken { get; set; }
    public string CustomHttpRequestMethod { get; set; }
    #endregion

    public Request(Uri resource,
        TRequestBody body,
        IHeadersCollection headers,
        HttpRequestMethod httpRequestMethod,
        IClient client,
        CancellationToken cancellationToken)
    {
        Body = body;
        Headers = headers;
        Resource = resource;
        HttpRequestMethod = httpRequestMethod;
        CancellationToken = cancellationToken;

        if (Headers == null) Headers = new RequestHeadersCollection();

        var defaultRequestHeaders = client?.DefaultRequestHeaders;
        if (defaultRequestHeaders == null) return;

        foreach (var kvp in defaultRequestHeaders)
        {
            Headers.Add(kvp);
        }
    }
}

public abstract class Response<TResponseBody> : Response
{
    #region Public Properties
    public virtual TResponseBody Body { get; }

    #endregion

    #region Constructors
    /// <summary>
    /// Only used for mocking or other inheritance
    /// </summary>
    protected Response() : base()
    {
    }

    protected Response(
    IHeadersCollection headersCollection,
    int statusCode,
    HttpRequestMethod httpRequestMethod,
    byte[] responseData,
    TResponseBody body,
    Uri requestUri
    ) : base(
        headersCollection,
        statusCode,
        httpRequestMethod,
        responseData,
        requestUri)
    {
        Body = body;
    }

    public static implicit operator TResponseBody(Response<TResponseBody> readResult)
    {
        return readResult.Body;
    }
    #endregion
}

public abstract class Response
{
    #region Fields
    private readonly byte[] _responseData;
    #endregion

    #region Public Properties
    public virtual int StatusCode { get; }
    public virtual IHeadersCollection Headers { get; }
    public virtual HttpRequestMethod HttpRequestMethod { get; }
    public abstract bool IsSuccess { get; }
    public virtual Uri RequestUri { get; }
    #endregion

    #region Constructor
    /// <summary>
    /// Only used for mocking or other inheritance
    /// </summary>
    protected Response()
    {
    }

    protected Response
    (
    IHeadersCollection headersCollection,
    int statusCode,
    HttpRequestMethod httpRequestMethod,
    byte[] responseData,
    Uri requestUri
    )
    {
        StatusCode = statusCode;
        Headers = headersCollection;
        HttpRequestMethod = httpRequestMethod;
        RequestUri = requestUri;
        _responseData = responseData;
    }
    #endregion

    #region Public Methods
    public virtual byte[] GetResponseData()
    {
        return _responseData;
    }
    #endregion
}

Full code

HttpClient Implementation

You can use Task.Run to make WebClient run asynchronously in its implementation.

Dependency Injection, when done well helps alleviate the problem of having to make low level decisions upfront. Ultimately, the only way to know the true answer is try both in a live environment and see which one works the best. It's quite possible that WebClient may work better for some customers, and HttpClient may work better for others. This is why abstraction is important. It means that code can quickly be swapped in, or changed with configuration without changing the fundamental design of the app.

BTW: there are numerous other reasons that you should use an abstraction instead of directly calling one of these low-level APIs. One huge one being unit-testability.

Copy file remotely with PowerShell

None of the above answers worked for me. I kept getting this error:

Copy-Item : Access is denied
+ CategoryInfo          : PermissionDenied: (\\192.168.1.100\Shared\test.txt:String) [Copy-Item], UnauthorizedAccessException>   
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.CopyItemCommand

So this did it for me:

netsh advfirewall firewall set rule group="File and Printer Sharing" new enable=yes

Then from my host my machine in the Run box I just did this:

\\{IP address of nanoserver}\C$

Xcode warning: "Multiple build commands for output file"

This happens if you have 2 files with the same name in the project. Even though files are in groups in XCode when the project is compiled all of the files end up in the same directory. In other words if you have /group1/image.jpg and /group2/image.jpg the compiled project will only have one of the two image.jpg files.

Vertically center text in a 100% height div?

This answer is no longer the best answer ... see the flexbox answer below instead!


To get it perfectly centered (as mentioned in david's answer) you need to add a negative top margin. If you know (or force) there to only be a single line of text, you can use:

margin-top: -0.5em;

for example:

http://jsfiddle.net/45MHk/623/

//CSS:
html, body, div {
    height: 100%;
}

#parent
{
    position:relative;
    border: 1px solid black;
}

#child
{
    position: absolute;
    top: 50%;
    /* adjust top up half the height of a single line */
    margin-top: -0.5em;
    /* force content to always be a single line */
    overflow: hidden;
    white-space: nowrap;
    width: 100%;
    text-overflow: ellipsis;
}

//HTML:
<div id="parent">
    <div id="child">Text that is suppose to be centered</div>
</div>?

The originally accepted answer will not vertically center on the middle of the text (it centers based on the top of the text). So, if you parent is not very tall, it will not look centered at all, for example:

http://jsfiddle.net/45MHk/

//CSS:
#parent
{
    position:relative;
    height: 3em;
    border: 1px solid black;
}

#child
{
    position: absolute;
    top: 50%;
}? 

//HTML:
<div id="parent">
    <div id="child">Text that is suppose to be centered</div>
</div>?

How to get relative path of a file in visual studio?

When it is the case that you want to use any kind of external file, there is certainly a way to put them in a folder within your project, but not as valid as getting them from resources. In a regular Visual Studio project, you should have a Resources.resx file under the Properties section, if not, you can easily add your own Resource.resx file. And add any kind of file in it, you can reach the walkthrough for adding resource files to your project here.

After having resource files in your project, calling them is easy as this:

var myIcon = Resources.MyIconFile;

Of course you should add the using Properties statement like this:

using <namespace>.Properties;

Editing legend (text) labels in ggplot

The legend titles can be labeled by specific aesthetic.

This can be achieved using the guides() or labs() functions from ggplot2 (more here and here). It allows you to add guide/legend properties using the aesthetic mapping.

Here's an example using the mtcars data set and labs():

ggplot(mtcars, aes(x=mpg, y=disp, size=hp, col=as.factor(cyl), shape=as.factor(gear))) +
  geom_point() +
  labs(x="miles per gallon", y="displacement", size="horsepower", 
       col="# of cylinders", shape="# of gears")

enter image description here

Answering the OP's question using guides():

# transforming the data from wide to long
require(reshape2)
dfm <- melt(df, id="TY")

# creating a scatterplot
ggplot(data = dfm, aes(x=TY, y=value, color=variable)) + 
  geom_point(size=5) +
  labs(title="Temperatures\n", x="TY [°C]", y="Txxx") +
  scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
  theme_bw() +
  guides(color=guide_legend("my title"))  # add guide properties by aesthetic

enter image description here

How can I use a C++ library from node.js?

You can use a node.js extension to provide bindings for your C++ code. Here is one tutorial that covers that:

http://syskall.com/how-to-write-your-own-native-nodejs-extension

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

I also met the error message in raspberry pi 3, but my solution is reload kernel of camera after search on google, hope it can help you.

sudo modprobe bcm2835-v4l2

BTW, for this error please check your camera and file path is workable or not

How can you tell if a value is not numeric in Oracle?

From Oracle DB 12c Release 2 you could use VALIDATE_CONVERSION function:

VALIDATE_CONVERSION determines whether expr can be converted to the specified data type. If expr can be successfully converted, then this function returns 1; otherwise, this function returns 0. If expr evaluates to null, then this function returns 1. If an error occurs while evaluating expr, then this function returns the error.

 IF (VALIDATE_CONVERSION(value AS NUMBER) = 1) THEN
     ...
 END IF;

db<>fiddle demo

Error Dropping Database (Can't rmdir '.test\', errno: 17)

I had the same issue (mysql 5.6 on mac) with 'can't rmdir..'-errors when dropping databases. Leaving an empty database directory not possible to get rid of. Thanks @Framework and @Beel for the solutions.

I first deleted the db directory from the Terminal in (/Applications/XAMPP/xamppfiles/var/mysql).

For further db drops, I also deleted the empty test file. In my case the file was called NOTEMPTY but still containing 0:

sudo ls -al test
total 0
drwxrwx---   3 _mysql  _mysql  102 Mar 26 16:50 .
drwxrwxr-x  18 _mysql  _mysql  612 Apr  7 13:34 ..
-rw-rw----   1 _mysql  _mysql    0 Jun 26  2013 NOTEMPTY

Chmod first and then

sudo rm -rf test/NOTEMPTY

No problems dropping databases after that

How can I open the interactive matplotlib window in IPython notebook?

Starting with matplotlib 1.4.0 there is now an an interactive backend for use in the notebook

%matplotlib notebook

There are a few version of IPython which do not have that alias registered, the fall back is:

%matplotlib nbagg

If that does not work update you IPython.

To play with this, goto tmpnb.org

and paste

%matplotlib notebook

import pandas as pd
import numpy as np
import matplotlib

from matplotlib import pyplot as plt
import seaborn as sns

ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()

df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index,
                  columns=['A', 'B', 'C', 'D'])
df = df.cumsum()
df.plot(); plt.legend(loc='best')    

into a code cell (or just modify the existing python demo notebook)

An App ID with Identifier '' is not available. Please enter a different string

This is for those who bump into the odd case I did, you CANNOT use the keyword test in the bundle id.

We were needing to test sharing data through the app group feature and the companion app wasn't developed yet so we simply changed the bundle identifier to test.APP_NAME instead of company.APP_NAME. We set up everything in iTunes Connect and nothing worked right. We then swapped the name to beta.APP_NAME and Xcode was able to manage the app id correctly again.

Normally to fix this issue, verify your provisioning profiles and App Id's have the correct settings, and if your still having trouble to to Xcode -> Preferences -> Accounts -> View Details -> Download All and you should be good.

Hope that helps.

Get protocol + host name from URL

You should be able to do it with urlparse (docs: python2, python3):

from urllib.parse import urlparse
# from urlparse import urlparse  # Python 2
parsed_uri = urlparse('http://stackoverflow.com/questions/1234567/blah-blah-blah-blah' )
result = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
print(result)

# gives
'http://stackoverflow.com/'

Checking for an empty field with MySQL

Yes, what you are doing is correct. You are checking to make sure the email field is not an empty string. NULL means the data is missing. An empty string "" is a blank string with the length of 0.

You can add the null check also

AND (email != "" OR email IS NOT NULL)

Is it possible to pull just one file in Git?

Yes, here is the process:

# Navigate to a directory and initiate a local repository
git init        

# Add remote repository to be tracked for changes:   
git remote add origin https://github.com/username/repository_name.git

# Track all changes made on above remote repository
# This will show files on remote repository not available on local repository
git fetch

# Add file present in staging area for checkout
git check origin/master -m /path/to/file
# NOTE: /path/to/file is a relative path from repository_name
git add /path/to/file

# Verify track of file(s) being committed to local repository
git status

# Commit to local repository
git commit -m "commit message"

# You may perform a final check of the staging area again with git status

How to call a function within class?

Since these are member functions, call it as a member function on the instance, self.

def isNear(self, p):
    self.distToPoint(p)
    ...

Selecting multiple columns with linq query and lambda expression

        Object AccountObject = _dbContext.Accounts
                                   .Join(_dbContext.Users, acc => acc.AccountId, usr => usr.AccountId, (acc, usr) => new { acc, usr })
                                   .Where(x => x.usr.EmailAddress == key1)
                                   .Where(x => x.usr.Hash == key2)
                                   .Select(x => new { AccountId = x.acc.AccountId, Name = x.acc.Name })
                                   .SingleOrDefault();

How to set button click effect in Android?

This can be achieved by creating a drawable xml file containing a list of states for the button. So for example if you create a new xml file called "button.xml" with the following code:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/YOURIMAGE" />
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/gradient" />
    <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/gradient" />
    <item android:drawable="@drawable/YOURIMAGE" />
</selector>

To keep the background image with a darkened appearance on press, create a second xml file and call it gradient.xml with the following code:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <bitmap android:src="@drawable/YOURIMAGE"/>
    </item>
    <item>
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <gradient android:angle="90" android:startColor="#880f0f10" android:centerColor="#880d0d0f" android:endColor="#885d5d5e"/>
        </shape>
    </item>
</layer-list>

In the xml of your button set the background to be the button xml e.g.

android:background="@drawable/button"

Hope this helps!

Edit: Changed the above code to show an image (YOURIMAGE) in the button as opposed to a block colour.

no sqljdbc_auth in java.library.path

Here are the steps if you want to do this from Eclipse :

1) Create a folder 'sqlauth' in your C: drive, and copy the dll file sqljdbc_auth.dll to the folder

1) Go to Run> Run Configurations

2) Choose the 'Arguments' tab for your class

3) Add the below code in VM arguments:

-Djava.library.path="C:\\sqlauth"

4) Hit 'Apply' and click 'Run'

Feel free to try other methods .

Sending HTML email using Python

You might try using my mailer module.

from mailer import Mailer
from mailer import Message

message = Message(From="[email protected]",
                  To="[email protected]")
message.Subject = "An HTML Email"
message.Html = """<p>Hi!<br>
   How are you?<br>
   Here is the <a href="http://www.python.org">link</a> you wanted.</p>"""

sender = Mailer('smtp.example.com')
sender.send(message)

Getting a list of all subdirectories in the current directory

This below class would be able to get list of files, folder and all sub folder inside a given directory

import os
import json

class GetDirectoryList():
    def __init__(self, path):
        self.main_path = path
        self.absolute_path = []
        self.relative_path = []


    def get_files_and_folders(self, resp, path):
        all = os.listdir(path)
        resp["files"] = []
        for file_folder in all:
            if file_folder != "." and file_folder != "..":
                if os.path.isdir(path + "/" + file_folder):
                    resp[file_folder] = {}
                    self.get_files_and_folders(resp=resp[file_folder], path= path + "/" + file_folder)
                else:
                    resp["files"].append(file_folder)
                    self.absolute_path.append(path.replace(self.main_path + "/", "") + "/" + file_folder)
                    self.relative_path.append(path + "/" + file_folder)
        return resp, self.relative_path, self.absolute_path

    @property
    def get_all_files_folder(self):
        self.resp = {self.main_path: {}}
        all = self.get_files_and_folders(self.resp[self.main_path], self.main_path)
        return all

if __name__ == '__main__':
    mylib = GetDirectoryList(path="sample_folder")
    file_list = mylib.get_all_files_folder
    print (json.dumps(file_list))

Whereas Sample Directory looks like

sample_folder/
    lib_a/
        lib_c/
            lib_e/
                __init__.py
                a.txt
            __init__.py
            b.txt
            c.txt
        lib_d/
            __init__.py
        __init__.py
        d.txt
    lib_b/
        __init__.py
        e.txt
    __init__.py

Result Obtained

[
  {
    "files": [
      "__init__.py"
    ],
    "lib_b": {
      "files": [
        "__init__.py",
        "e.txt"
      ]
    },
    "lib_a": {
      "files": [
        "__init__.py",
        "d.txt"
      ],
      "lib_c": {
        "files": [
          "__init__.py",
          "c.txt",
          "b.txt"
        ],
        "lib_e": {
          "files": [
            "__init__.py",
            "a.txt"
          ]
        }
      },
      "lib_d": {
        "files": [
          "__init__.py"
        ]
      }
    }
  },
  [
    "sample_folder/lib_b/__init__.py",
    "sample_folder/lib_b/e.txt",
    "sample_folder/__init__.py",
    "sample_folder/lib_a/lib_c/lib_e/__init__.py",
    "sample_folder/lib_a/lib_c/lib_e/a.txt",
    "sample_folder/lib_a/lib_c/__init__.py",
    "sample_folder/lib_a/lib_c/c.txt",
    "sample_folder/lib_a/lib_c/b.txt",
    "sample_folder/lib_a/lib_d/__init__.py",
    "sample_folder/lib_a/__init__.py",
    "sample_folder/lib_a/d.txt"
  ],
  [
    "lib_b/__init__.py",
    "lib_b/e.txt",
    "sample_folder/__init__.py",
    "lib_a/lib_c/lib_e/__init__.py",
    "lib_a/lib_c/lib_e/a.txt",
    "lib_a/lib_c/__init__.py",
    "lib_a/lib_c/c.txt",
    "lib_a/lib_c/b.txt",
    "lib_a/lib_d/__init__.py",
    "lib_a/__init__.py",
    "lib_a/d.txt"
  ]
]

IOException: Too many open files

This problem comes when you are writing data in many files simultaneously and your Operating System has a fixed limit of Open files. In Linux, you can increase the limit of open files.

https://www.tecmint.com/increase-set-open-file-limits-in-linux/

How do I change the number of open files limit in Linux?

IndexError: index 1 is out of bounds for axis 0 with size 1/ForwardEuler

The problem is with your line

x=np.array ([x0*n])

Here you define x as a single-item array of -200.0. You could do this:

x=np.array ([x0,]*n)

or this:

x=np.zeros((n,)) + x0

Note: your imports are quite confused. You import numpy modules three times in the header, and then later import pylab (that already contains all numpy modules). If you want to go easy, with one single

from pylab import *

line in the top you could use all the modules you need.

Find a line in a file and remove it

package com.ncs.cache;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;

public class FileUtil {

    public void removeLineFromFile(String file, String lineToRemove) {

        try {

            File inFile = new File(file);

            if (!inFile.isFile()) {
                System.out.println("Parameter is not an existing file");
                return;
            }

            // Construct the new file that will later be renamed to the original
            // filename.
            File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

            BufferedReader br = new BufferedReader(new FileReader(file));
            PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

            String line = null;

            // Read from the original file and write to the new
            // unless content matches data to be removed.
            while ((line = br.readLine()) != null) {

                if (!line.trim().equals(lineToRemove)) {

                    pw.println(line);
                    pw.flush();
                }
            }
            pw.close();
            br.close();

            // Delete the original file
            if (!inFile.delete()) {
                System.out.println("Could not delete file");
                return;
            }

            // Rename the new file to the filename the original file had.
            if (!tempFile.renameTo(inFile))
                System.out.println("Could not rename file");

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        FileUtil util = new FileUtil();
        util.removeLineFromFile("test.txt", "bbbbb");
    }
}

src : http://www.javadb.com/remove-a-line-from-a-text-file/

How to deal with SQL column names that look like SQL keywords?

While you are doing it - alias it as something else (or better yet, use a view or an SP and deprecate the old direct access method).

SELECT [from] AS TransferFrom -- Or something else more suitable
FROM TableName

The Completest Cocos2d-x Tutorial & Guide List

Here you got complementaries discussions about the topic, it can be interesting.

discussion1

discussion2

How do I loop through a list by twos?

nums = range(10)
for i in range(0, len(nums)-1, 2):
    print nums[i]

Kinda dirty but it works.

Convert date formats in bash

It's enough to do:

data=`date`
datatime=`date -d "${data}" '+%Y%m%d'`
echo $datatime
20190206

If you want to add also the time you can use in that way

data=`date`
datatime=`date -d "${data}" '+%Y%m%d %T'`

echo $data
Wed Feb 6 03:57:15 EST 2019

echo $datatime
20190206 03:57:15

TortoiseSVN icons overlay not showing after updating to Windows 10

For anyone using Windows 10, there's a request in Feedback Hub to get Microsoft to fix this issue. If you'd like to add a +1 to have it fixed, here's a link: https://aka.ms/Cryalp.

The link only works on Windows 10 as it needs to open Feedback Hub to get to the suggestion. The link was generated using the "Share" feature in Feedback Hub and aka.ms is an internal link shortening service used by Microsoft.

How to add a footer in ListView?

Answers here are a bit outdated. Though the code remains the same there are some changes in the behavior.

public class MyListActivity extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        TextView footerView = (TextView) ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_view, null, false);
        getListView().addFooterView(footerView);
        setListAdapter(new ArrayAdapter<String>(this, getResources().getStringArray(R.array.news)));
    }
}

Info about addFooterView() method

Add a fixed view to appear at the bottom of the list. If addFooterView() is called more than once, the views will appear in the order they were added. Views added using this call can take focus if they want.

Most of the answers above stress very important point -

addFooterView() must be called before calling setAdapter().This is so ListView can wrap the supplied cursor with one that will also account for header and footer views.

From Kitkat this has changed.

Note: When first introduced, this method could only be called before setting the adapter with setAdapter(ListAdapter). Starting with KITKAT, this method may be called at any time. If the ListView's adapter does not extend HeaderViewListAdapter, it will be wrapped with a supporting instance of WrapperListAdapter.

Documentation

How to center text vertically with a large font-awesome icon?

Simply define vertical-align property for the icon element:

div .icon {
   vertical-align: middle;
}

How to close a thread from within?

A little late, but I use a _is_running variable to tell the thread when I want to close. It's easy to use, just implement a stop() inside your thread class.

def stop(self):
  self._is_running = False

And in run() just loop on while(self._is_running)

Difference between two dates in years, months, days in JavaScript

If you are using date-fns and if you dont want to install the Moment.js or the moment-precise-range-plugin. You can use the following date-fns function to get the same result as moment-precise-range-plugin

intervalToDuration({
  start: new Date(),
  end: new Date("24 Jun 2020")
})

This will give output in a JSON object like below

{
  "years": 0,
  "months": 0,
  "days": 0,
  "hours": 19,
  "minutes": 35,
  "seconds": 24
}

Live Example https://stackblitz.com/edit/react-wvxvql

Link to Documentation https://date-fns.org/v2.14.0/docs/intervalToDuration

What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

These are use in ruby on rails :-

<% %> :-

The <% %> tags are used to execute Ruby code that does not return anything, such as conditions, loops or blocks. Eg :-

<h1>Names of all the people</h1>
<% @people.each do |person| %>
  Name: <%= person.name %><br>
<% end %>

<%= %> :-

use to display the content .

Name: <%= person.name %><br>

<% -%>:-

Rails extends ERB, so that you can suppress the newline simply by adding a trailing hyphen to tags in Rails templates

<%# %>:-

comment out the code

<%# WRONG %>
Hi, Mr. <% puts "Frodo" %>

Adding n hours to a date in Java?

You can use the LocalDateTime class from Java 8. For eg :

long n = 4;
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime.plusHours(n));

How to really read text file from classpath in Java

My answer is not exactly what is asked in the question. Rather I am giving a solution exactly how easily we can read a file into out java application from our project class path.

For example suppose a config file name example.xml is located in a path like below:-

com.myproject.config.dev

and our java executable class file is in the below path:-

com.myproject.server.main

now just check in both the above path which is the nearest common directory/folder from where you can access both dev and main directory/folder (com.myproject.server.main - where our application’s java executable class is existed) – We can see that it is myproject folder/directory which is the nearest common directory/folder from where we can access our example.xml file. Therefore from a java executable class resides in folder/directory main we have to go back two steps like ../../ to access myproject. Now following this, see how we can read the file:-

package com.myproject.server.main;

class Example {

  File xmlFile;

  public Example(){
       String filePath = this.getClass().getResource("../../config/dev/example.xml").getPath();
       this.xmlFile = new File(filePath);
    }

  public File getXMLFile() {
      return this.xmlFile;
  }
   public static void main(String args[]){
      Example ex = new Example();
      File xmlFile = ex.getXMLFile();
   }
}

log4j:WARN No appenders could be found for logger in web.xml

OK, I see a lot of answer and some very correct. However, none fixed my problem. The problem in my case was the UNIX filesystem permissions had the log4j.properties file I was editing on the server as owned by root. and readable by only root. However, the web application I was deploying was to tomcat couldn't read the file as tomcat runs as user tomcat on Linux systems by default. Hope this helps. so the solution was typing 'chown tomcat:tomcat log4j.properties' in the directory where the log4j.properties file resides.

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JDBC_DBO]]

Even I had same problem

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/]

I have added respective dependency at very begenining it had worked for me.

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
</dependency>

How to make Bootstrap carousel slider use mobile left/right swipe

Same functionality I prefer than using much heavy jQuery mobile is Carousel Swipe. I suggest directly jump in to source code on github, and copy file carousel-swipe.js in to your project directory.

Use swiper events as bellow:

$('#carousel-example-generic').carousel({
      interval: false 
  });

Display a table/list data dynamically in MVC3/Razor from a JsonResult?

The normal way of doing it is:

  • You get the users from the database in controller.
  • You send a collection of users to the View
  • In the view to loop the list of users building the list.

You don't need a JsonResult or jQuery for this.

Can I safely delete contents of Xcode Derived data folder?

I would say it's safe--I often delete the contents of the folder for many kind of iOS projects, this way. And, I haven't had any issues with builds or submitting to the App Store. The procedure deletes derived data and cleans a project's cached assets, for both Xcode 5 and 6.

Sometimes, simply calling rm -rf on the Derived Data directory leaves a lingering file or two, but my script loops until all files are deleted.

What is the "double tilde" (~~) operator in JavaScript?

~(5.5)   // => -6
~(-6)    // => 5
~~5.5    // => 5  (same as Math.floor(5.5))
~~(-5.5) // => -5 (NOT the same as Math.floor(-5.5), which would give -6 )

For more info, see:

How to connect to local instance of SQL Server 2008 Express

I know this question is old, but in case it helps anyone make sure the SQL Server Browser is running in the Services MSC. I installed SQL Server Express 2008 R2 and the SQL Server Browser Service was set to Disabled.

  1. Start->Run->Services.msc
  2. Find "SQL Server Browser"->Right Click->Properties
  3. Set Startup Type to Automatic->Click Apply
  4. Retry your connection.

How is returning the output of a function different from printing it?

def add(x, y):
    return x+y

That way it can then become a variable.

sum = add(3, 5)

print(sum)

But if the 'add' function print the output 'sum' would then be None as action would have already taken place after it being assigned.

Filtering a list of strings based on contents

This simple filtering can be achieved in many ways with Python. The best approach is to use "list comprehensions" as follows:

>>> lst = ['a', 'ab', 'abc', 'bac']
>>> [k for k in lst if 'ab' in k]
['ab', 'abc']

Another way is to use the filter function. In Python 2:

>>> filter(lambda k: 'ab' in k, lst)
['ab', 'abc']

In Python 3, it returns an iterator instead of a list, but you can cast it:

>>> list(filter(lambda k: 'ab' in k, lst))
['ab', 'abc']

Though it's better practice to use a comprehension.

Shortcut to Apply a Formula to an Entire Column in Excel

Try double-clicking on the bottom right hand corner of the cell (ie on the box that you would otherwise drag).

Setting button text via javascript

The value of a button element isn't the displayed text, contrary to what happens to input elements of type button.

You can do this :

 b.appendChild(document.createTextNode('test value'));

Demonstration

How do I get indices of N maximum values in a NumPy array?

Newer NumPy versions (1.8 and up) have a function called argpartition for this. To get the indices of the four largest elements, do

>>> a = np.array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0])
>>> a
array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0])
>>> ind = np.argpartition(a, -4)[-4:]
>>> ind
array([1, 5, 8, 0])
>>> a[ind]
array([4, 9, 6, 9])

Unlike argsort, this function runs in linear time in the worst case, but the returned indices are not sorted, as can be seen from the result of evaluating a[ind]. If you need that too, sort them afterwards:

>>> ind[np.argsort(a[ind])]
array([1, 8, 5, 0])

To get the top-k elements in sorted order in this way takes O(n + k log k) time.

Creating Unicode character from its number

The other answers here either only support unicode up to U+FFFF (the answers dealing with just one instance of char) or don't tell how to get to the actual symbol (the answers stopping at Character.toChars() or using incorrect method after that), so adding my answer here, too.

To support supplementary code points also, this is what needs to be done:

// this character:
// http://www.isthisthingon.org/unicode/index.php?page=1F&subpage=4&glyph=1F495
// using code points here, not U+n notation
// for equivalence with U+n, below would be 0xnnnn
int codePoint = 128149;
// converting to char[] pair
char[] charPair = Character.toChars(codePoint);
// and to String, containing the character we want
String symbol = new String(charPair);

// we now have str with the desired character as the first item
// confirm that we indeed have character with code point 128149
System.out.println("First code point: " + symbol.codePointAt(0));

I also did a quick test as to which conversion methods work and which don't

int codePoint = 128149;
char[] charPair = Character.toChars(codePoint);

System.out.println(new String(charPair, 0, 2).codePointAt(0)); // 128149, worked
System.out.println(charPair.toString().codePointAt(0));        // 91, didn't work
System.out.println(new String(charPair).codePointAt(0));       // 128149, worked
System.out.println(String.valueOf(codePoint).codePointAt(0));  // 49, didn't work
System.out.println(new String(new int[] {codePoint}, 0, 1).codePointAt(0));
                                                               // 128149, worked

What parameters should I use in a Google Maps URL to go to a lat-lon?

In May 2017 Google announced the Google Maps URLs API that allows to construct universal cross-platform links. Now you can open Google maps on web, Android or iOS using the same URL string in form:

https://www.google.com/maps/search/?api=1&parameters

There are several modes that you can use: search, directions, show map and show street view.

So you can use something like

https://www.google.com/maps/search/?api=1&query=58.698017,-152.522067

to open map and place marker on some lat and lng.

For further details please refer to:

https://developers.google.com/maps/documentation/urls/guide

How to specify the private SSH-key to use when executing shell command on Git?

You could use GIT_SSH environment variable. But you will need to wrap ssh and options into a shell script.

See git manual: man git in your command shell.

Laravel stylesheets and javascript don't load for non-base routes

in Laravel 5,
there are 2 ways to load a js file in your view
first is using html helper, second is using asset helpers.
to use html helper you have to first install this package via commandline:

composer require illuminate/html

then you need to reqister it, so go to config/app.php, and add this line to the providers array

'Illuminate\Html\HtmlServiceProvider'

then you have to define aliases for your html package so go to aliases array in config/app.php and add this

'Html'     => 'Illuminate\Html\HtmlFacade'

now your html helper is installed so in your blade view files you can write this:

{!! Html::script('js/test.js') !!}

this will look for your test.js file in your project_root/public/js/test.js.
//////////////////////////////////////////////////////////////
to use asset helpers instead of html helper, you have to write sth like this in your view files:

<script src="{{ URL::asset('test.js') }}"></script>

this will look for test.js file in project_root/resources/assets/test.js

Git undo local branch delete

This worked for me:

git fsck --full --no-reflogs --unreachable --lost-found
git show d6e883ff45be514397dcb641c5a914f40b938c86
git branch helpme 15e521b0f716269718bb4e4edc81442a6c11c139

How to move a git repository into another directory and make that directory a git repository?

I am no expert, but I copy the .git folder to a new folder, then invoke: git reset --hard

Access the css ":after" selector with jQuery

You can't manipulate :after, because it's not technically part of the DOM and therefore is inaccessible by any JavaScript. But you can add a new class with a new :after specified.

CSS:

.pageMenu .active.changed:after { 
/* this selector is more specific, so it takes precedence over the other :after */
    border-top-width: 22px;
    border-left-width: 22px;
    border-right-width: 22px;
}

JS:

$('.pageMenu .active').toggleClass('changed');

UPDATE: while it's impossible to directly modify the :after content, there are ways to read and/or override it using JavaScript. See "Manipulating CSS pseudo-elements using jQuery (e.g. :before and :after)" for a comprehensive list of techniques.

How to multiply all integers inside list

Another functional approach which is maybe a little easier to look at than an anonymous function if you go that route is using functools.partial to utilize the two-parameter operator.mul with a fixed multiple

>>> from functools import partial
>>> from operator import mul
>>> double = partial(mul, 2)
>>> list(map(double, [1, 2, 3]))
[2, 4, 6]

How do I query for all dates greater than a certain date in SQL Server?

To sum it all up, the correct answer is :

select * from db where Date >= '20100401'  (Format of date yyyymmdd)

This will avoid any problem with other language systems and will use the index.

Static variables in C++

Excuse me when I answer your questions out-of-order, it makes it easier to understand this way.

When static variable is declared in a header file is its scope limited to .h file or across all units.

There is no such thing as a "header file scope". The header file gets included into source files. The translation unit is the source file including the text from the header files. Whatever you write in a header file gets copied into each including source file.

As such, a static variable declared in a header file is like a static variable in each individual source file.

Since declaring a variable static this way means internal linkage, every translation unit #includeing your header file gets its own, individual variable (which is not visible outside your translation unit). This is usually not what you want.

I would like to know what is the difference between static variables in a header file vs declared in a class.

In a class declaration, static means that all instances of the class share this member variable; i.e., you might have hundreds of objects of this type, but whenever one of these objects refers to the static (or "class") variable, it's the same value for all objects. You could think of it as a "class global".

Also generally static variable is initialized in .cpp file when declared in a class right ?

Yes, one (and only one) translation unit must initialize the class variable.

So that does mean static variable scope is limited to 2 compilation units ?

As I said:

  • A header is not a compilation unit,
  • static means completely different things depending on context.

Global static limits scope to the translation unit. Class static means global to all instances.

I hope this helps.

PS: Check the last paragraph of Chubsdad's answer, about how you shouldn't use static in C++ for indicating internal linkage, but anonymous namespaces. (Because he's right. ;-) )

length and length() in Java

In Java, an Array stores its length separately from the structure that actually holds the data. When you create an Array, you specify its length, and that becomes a defining attribute of the Array. No matter what you do to an Array of length N (change values, null things out, etc.), it will always be an Array of length N.

A String's length is incidental; it is not an attribute of the String, but a byproduct. Though Java Strings are in fact immutable, if it were possible to change their contents, you could change their length. Knocking off the last character (if it were possible) would lower the length.

I understand this is a fine distinction, and I may get voted down for it, but it's true. If I make an Array of length 4, that length of four is a defining characteristic of the Array, and is true regardless of what is held within. If I make a String that contains "dogs", that String is length 4 because it happens to contain four characters.

I see this as justification for doing one with an attribute and the other with a method. In truth, it may just be an unintentional inconsistency, but it's always made sense to me, and this is always how I've thought about it.

How do I Geocode 20 addresses without receiving an OVER_QUERY_LIMIT response?

EDIT:

Forgot to say that this solution is in pure js, the only thing you need is a browser that supports promises https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Promise


For those who still needs to accomplish such, I've written my own solution that combines promises with timeouts.

Code:

/*
    class: Geolocalizer
        - Handles location triangulation and calculations.
        -- Returns various prototypes to fetch position from strings or coords or dragons or whatever.
*/

var Geolocalizer = function () {
    this.queue          = [];     // queue handler..
    this.resolved       = [];
    this.geolocalizer = new google.maps.Geocoder();  
};

Geolocalizer.prototype = {
    /*
        @fn: Localize
        @scope: resolve single or multiple queued requests.
        @params: <array> needles
        @returns: <deferred> object
    */
    Localize: function ( needles ) {
        var that = this;
        // Enqueue the needles.
        for ( var i = 0; i < needles.length; i++ ) {
            this.queue.push(needles[i]);
        }
        // return a promise and resolve it after every element have been fetched (either with success or failure), then reset the queue.
        return new Promise (
            function (resolve, reject) {
                that.resolveQueueElements().then(function(resolved){
                  resolve(resolved);
                  that.queue    = [];
                  that.resolved = [];
                });
            }
        );
    },

    /*
        @fn: resolveQueueElements
        @scope: resolve queue elements.
        @returns: <deferred> object (promise)
    */

    resolveQueueElements: function (callback) {
        var that = this;
        return new Promise(
            function(resolve, reject) {
                // Loop the queue and resolve each element.
                // Prevent QUERY_LIMIT by delaying actions by one second.
                (function loopWithDelay(such, queue, i){
                    console.log("Attempting the resolution of " +queue[i-1]);
                    setTimeout(function(){
                        such.find(queue[i-1], function(res){
                           such.resolved.push(res); 
                        });
                        if (--i) {
                            loopWithDelay(such,queue,i);
                        }
                    }, 1000);
                })(that, that.queue, that.queue.length);

                // Check every second if the queue has been cleared.
                var it = setInterval(function(){
                    if (that.queue.length == that.resolved.length) {
                        resolve(that.resolved);
                        clearInterval(it);
                    }
                }, 1000);
            }
        );
    },

    /*
        @fn: find
        @scope: resolve an address from string
        @params: <string> s, <fn> Callback
    */
    find: function (s, callback) {
        this.geolocalizer.geocode({
            "address": s
        }, function(res, status){
           if (status == google.maps.GeocoderStatus.OK) {
               var r = {
                   originalString:  s,
                   lat: res[0].geometry.location.lat(),
                   lng: res[0].geometry.location.lng()
               };
               callback(r);
           }
            else {
                callback(undefined);
                console.log(status);
                console.log("could not locate " + s);
            }
        });
    }
};

Please note that it's just a part of a bigger library I wrote to handle google maps stuff, hence comments may be confusing.

Usage is quite simple, the approach, however, is slightly different: instead of looping and resolving one address at a time, you will need to pass an array of addresses to the class and it will handle the search by itself, returning a promise which, when resolved, returns an array containing all the resolved (and unresolved) address.

Example:

var myAmazingGeo = new Geolocalizer();
var locations = ["Italy","California","Dragons are thugs...","China","Georgia"];
myAmazingGeo.Localize(locations).then(function(res){ 
   console.log(res); 
});

Console output:

Attempting the resolution of Georgia
Attempting the resolution of China
Attempting the resolution of Dragons are thugs...
Attempting the resolution of California
ZERO_RESULTS
could not locate Dragons are thugs...
Attempting the resolution of Italy

Object returned:

enter image description here

The whole magic happens here:

(function loopWithDelay(such, queue, i){
                    console.log("Attempting the resolution of " +queue[i-1]);
                    setTimeout(function(){
                        such.find(queue[i-1], function(res){
                           such.resolved.push(res); 
                        });
                        if (--i) {
                            loopWithDelay(such,queue,i);
                    }
                }, 750);
            })(that, that.queue, that.queue.length);

Basically, it loops every item with a delay of 750 milliseconds between each of them, hence every 750 milliseconds an address is controlled.

I've made some further testings and I've found out that even at 700 milliseconds I was sometimes getting the QUERY_LIMIT error, while with 750 I haven't had any issue at all.

In any case, feel free to edit the 750 above if you feel you are safe by handling a lower delay.

Hope this helps someone in the near future ;)

Given a class, see if instance has method (Ruby)

You can use method_defined? as follows:

String.method_defined? :upcase # => true

Much easier, portable and efficient than the instance_methods.include? everyone else seems to be suggesting.

Keep in mind that you won't know if a class responds dynamically to some calls with method_missing, for example by redefining respond_to?, or since Ruby 1.9.2 by defining respond_to_missing?.

Expected block end YAML error

I would like to make this answer for meaningful, so the same kind of erroneous user can enjoy without feel any hassle.

Actually, i was getting the same error but for the different reason, in my case I didn't used any kind of quoted, still getting the same error like expected <block end>, but found BlockMappingStart.

I have solved it by fixing, the Alignment issue inside the same .yml file.

If we don't manage the proper 'tab-space(Keyboard key)' for maintaining successor or ancestor then we have to phase such kind of things.

Now i am doing well.

Multipart File Upload Using Spring Rest Template + Spring Web MVC

The Multipart File Upload worked after following code modification to Upload using RestTemplate

LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new ClassPathResource(file));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);

HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new    HttpEntity<LinkedMultiValueMap<String, Object>>(
                    map, headers);
ResponseEntity<String> result = template.get().exchange(
                    contextPath.get() + path, HttpMethod.POST, requestEntity,
                    String.class);

And adding MultipartFilter to web.xml

    <filter>
        <filter-name>multipartFilter</filter-name>
        <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>multipartFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Avoid trailing zeroes in printf()

Here is my first try at an answer:

void
xprintfloat(char *format, float f)
{
  char s[50];
  char *p;

  sprintf(s, format, f);
  for(p=s; *p; ++p)
    if('.' == *p) {
      while(*++p);
      while('0'==*--p) *p = '\0';
    }
  printf("%s", s);
}

Known bugs: Possible buffer overflow depending on format. If "." is present for other reason than %f wrong result might happen.

SQL update query using joins

You can update with MERGE Command with much more control over MATCHED and NOT MATCHED:(I slightly changed the source code to demonstrate my point)

USE tempdb;
GO
IF(OBJECT_ID('target') > 0)DROP TABLE dbo.target
IF(OBJECT_ID('source') > 0)DROP TABLE dbo.source
CREATE TABLE dbo.Target
    (
      EmployeeID INT ,
      EmployeeName VARCHAR(100) ,
      CONSTRAINT Target_PK PRIMARY KEY ( EmployeeID )
    );
CREATE TABLE dbo.Source
    (
      EmployeeID INT ,
      EmployeeName VARCHAR(100) ,
      CONSTRAINT Source_PK PRIMARY KEY ( EmployeeID )
    );
GO
INSERT  dbo.Target
        ( EmployeeID, EmployeeName )
VALUES  ( 100, 'Mary' );
INSERT  dbo.Target
        ( EmployeeID, EmployeeName )
VALUES  ( 101, 'Sara' );
INSERT  dbo.Target
        ( EmployeeID, EmployeeName )
VALUES  ( 102, 'Stefano' );

GO
INSERT  dbo.Source
        ( EmployeeID, EmployeeName )
VALUES  ( 100, 'Bob' );
INSERT  dbo.Source
        ( EmployeeID, EmployeeName )
VALUES  ( 104, 'Steve' );
GO

SELECT * FROM dbo.Source
SELECT * FROM dbo.Target

MERGE Target AS T
USING Source AS S
ON ( T.EmployeeID = S.EmployeeID )
WHEN MATCHED THEN
    UPDATE SET T.EmployeeName = S.EmployeeName + '[Updated]';
GO 
SELECT '-------After Merge----------'
SELECT * FROM dbo.Source
SELECT * FROM dbo.Target

Remove CSS from a Div using JQuery

jQuery.fn.extend
({
    removeCss: function(cssName) {
        return this.each(function() {
            var curDom = $(this);
            jQuery.grep(cssName.split(","),
                    function(cssToBeRemoved) {
                        curDom.css(cssToBeRemoved, '');
                    });
            return curDom;
        });
    }
});

/*example code: I prefer JQuery extend so I can use it anywhere I want to use.

$('#searchJqueryObject').removeCss('background-color');
$('#searchJqueryObject').removeCss('background-color,height,width'); //supports comma separated css names.

*/

OR

//this parse style & remove style & rebuild style. I like the first one.. but anyway exploring..
jQuery.fn.extend
({
    removeCSS: function(cssName) {
        return this.each(function() {

            return $(this).attr('style',

            jQuery.grep($(this).attr('style').split(";"),
                    function(curCssName) {
                        if (curCssName.toUpperCase().indexOf(cssName.toUpperCase() + ':') <= 0)
                            return curCssName;
                    }).join(";"));
        });
    }
});

Display open transactions in MySQL

How can I display these open transactions and commit or cancel them?

There is no open transaction, MySQL will rollback the transaction upon disconnect.
You cannot commit the transaction (IFAIK).

You display threads using

SHOW FULL PROCESSLIST  

See: http://dev.mysql.com/doc/refman/5.1/en/thread-information.html

It will not help you, because you cannot commit a transaction from a broken connection.

What happens when a connection breaks
From the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/mysql-tips.html

4.5.1.6.3. Disabling mysql Auto-Reconnect

If the mysql client loses its connection to the server while sending a statement, it immediately and automatically tries to reconnect once to the server and send the statement again. However, even if mysql succeeds in reconnecting, your first connection has ended and all your previous session objects and settings are lost: temporary tables, the autocommit mode, and user-defined and session variables. Also, any current transaction rolls back.

This behavior may be dangerous for you, as in the following example where the server was shut down and restarted between the first and second statements without you knowing it:

Also see: http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html

How to diagnose and fix this
To check for auto-reconnection:

If an automatic reconnection does occur (for example, as a result of calling mysql_ping()), there is no explicit indication of it. To check for reconnection, call mysql_thread_id() to get the original connection identifier before calling mysql_ping(), then call mysql_thread_id() again to see whether the identifier has changed.

Make sure you keep your last query (transaction) in the client so that you can resubmit it if need be.
And disable auto-reconnect mode, because that is dangerous, implement your own reconnect instead, so that you know when a drop occurs and you can resubmit that query.

How to construct a set out of list items in python?

One general way to construct set in iterative way like this:

aset = {e for e in alist}

Set a cookie to never expire

All cookies expire as per the cookie specification, so this is not a PHP limitation.

Use a far future date. For example, set a cookie that expires in ten years:

setcookie(
  "CookieName",
  "CookieValue",
  time() + (10 * 365 * 24 * 60 * 60)
);

Note that if you set a date past 2038 in 32-bit PHP, the number will wrap around and you'll get a cookie that expires instantly.

Git clone particular version of remote repository

The source tree you are requiring is still available within the git repository, however, you will need the SHA1 of the commit that you are interested in. I would assume that you can get the SHA1 from the current clone you have?

If you can get that SHA1, the you can create a branch / reset there to have the identical repository.

Commands as per Rui's answer

Publish to IIS, setting Environment Variable

Update web.config with an <environmentVariables> section under <aspNetCore>

<configuration>
  <system.webServer>
    <aspNetCore .....>
      <environmentVariables>
        <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
      </environmentVariables>
    </aspNetCore>
  </system.webServer>
</configuration>

Or to avoid losing this setting when overwriting web.config, make similar changes to applicationHost.config specifying the site location as @NickAb suggests.

<location path="staging.site.com">
    <system.webServer>
        <aspNetCore>
            <environmentVariables>
                <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" />
            </environmentVariables>
        </aspNetCore>
    </system.webServer>
</location>
<location path="production.site.com">
    <system.webServer>
        <aspNetCore>
            <environmentVariables>
                <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Production" />
            </environmentVariables>
        </aspNetCore>
    </system.webServer>
</location>

Adding a Time to a DateTime in C#

You can use the DateTime.Add() method to add the time to the date.

DateTime date = DateTime.Now;
TimeSpan time = new TimeSpan(36, 0, 0, 0);
DateTime combined = date.Add(time);
Console.WriteLine("{0:dddd}", combined);

You can also create your timespan by parsing a String, if that is what you need to do.

Alternatively, you could look at using other controls. You didn't mention if you are using winforms, wpf or asp.net, but there are various date and time picker controls that support selection of both date and time.

Rails DateTime.now without Time

If you want today's date without the time, just use Date.today

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

Beginning with MySQL 8.0.19 you can use an alias for that row (see reference).

INSERT INTO beautiful (name, age)
    VALUES
    ('Helen', 24),
    ('Katrina', 21),
    ('Samia', 22),
    ('Hui Ling', 25),
    ('Yumie', 29)
    AS new
ON DUPLICATE KEY UPDATE
    age = new.age
    ...

For earlier versions use the keyword VALUES (see reference, deprecated with MySQL 8.0.20).

INSERT INTO beautiful (name, age)
    VALUES
    ('Helen', 24),
    ('Katrina', 21),
    ('Samia', 22),
    ('Hui Ling', 25),
    ('Yumie', 29)
ON DUPLICATE KEY UPDATE
    age = VALUES(age),
     ...

Using the rJava package on Win7 64 bit with R

Sorry for necro. I have too run into the same issue and found out that rJava expects JAVA_HOME to point to JRE. If you have JDK installed, most probably your JAVA_HOME points to JDK. My quick solution:

Sys.setenv(JAVA_HOME=paste(Sys.getenv("JAVA_HOME"), "jre", sep="\\"))

How to make the corners of a button round?

If you want change corner radius as well as want a ripple effect in button when pressed use this:-

  1. Put button_background.xml in drawable
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="#F7941D">

    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="#F7941D" />
            <corners android:radius="10dp" />
        </shape>
    </item>

    <item android:id="@android:id/background">
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
            <corners android:radius="10dp" />
        </shape>
    </item>

</ripple>
  1. Apply this background to your button
<Button
    android:background="@drawable/button_background"
    android:id="@+id/myBtn"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="My Button" />

Invalid Host Header when ngrok tries to connect to React dev server

Option 1

If you do not need to use Authentication you can add configs to ngrok commands

ngrok http 9000 --host-header=rewrite

or

ngrok http 9000 --host-header="localhost:9000"

But in this case Authentication will not work on your website because ngrok rewriting headers and session is not valid for your ngrok domain

Option 2

If you are using webpack you can add the following configuration

devServer: {
    disableHostCheck: true
}

In that case Authentication header will be valid for your ngrok domain

How to use Comparator in Java to sort

public static Comparator<JobSet> JobEndTimeComparator = new Comparator<JobSet>() {
            public int compare(JobSet j1, JobSet j2) {
                int cost1 = j1.cost;
                int cost2 = j2.cost;
                return cost1-cost2;
            }
        };

Using XAMPP, how do I swap out PHP 5.3 for PHP 5.2?

I couldn't get this working. Started with PHP 5.3, then tried to switch to PHP 5.28 from xampp-win32-1.7.0.zip. Couldn't get it to work. Then, I got smart and figured out i was working with XAMPP and you can install it wherever you want, so I did a fresh install from scratch with xampp-win32-1.7.0.zip. The whole point of working with XAMPP is so you don't have to fuss with the sysadmin stuff. Using it in that context got me up and running in no time.

How to load Spring Application Context

Add this at the start of main

ApplicationContext context = new ClassPathXmlApplicationContext("path/to/applicationContext.xml");

JobLauncher launcher=(JobLauncher)context.getBean("launcher");
Job job=(Job)context.getBean("job");

//Get as many beans you want
//Now do the thing you were doing inside test method
StopWatch sw = new StopWatch();
sw.start();
launcher.run(job, jobParameters);
sw.stop();
//initialize the log same way inside main
logger.info(">>> TIME ELAPSED:" + sw.prettyPrint());

Recursive sub folder search and return files in a list python

If you don't mind installing an additional light library, you can do this:

pip install plazy

Usage:

import plazy

txt_filter = lambda x : True if x.endswith('.txt') else False
files = plazy.list_files(root='data', filter_func=txt_filter, is_include_root=True)

The result should look something like this:

['data/a.txt', 'data/b.txt', 'data/sub_dir/c.txt']

It works on both Python 2.7 and Python 3.

Github: https://github.com/kyzas/plazy#list-files

Disclaimer: I'm an author of plazy.

What does ${} (dollar sign and curly braces) mean in a string in Javascript?

As mentioned in a comment above, you can have expressions within the template strings/literals. Example:

_x000D_
_x000D_
const one = 1;_x000D_
const two = 2;_x000D_
const result = `One add two is ${one + two}`;_x000D_
console.log(result); // output: One add two is 3
_x000D_
_x000D_
_x000D_

How to connect mySQL database using C++

Finally I could successfully compile a program with C++ connector in Ubuntu 12.04 I have installed the connector using this command

'apt-get install libmysqlcppconn-dev'

Initially I faced the same problem with "undefined reference to `get_driver_instance' " to solve this I declare my driver instance variable of MySQL_Driver type. For ready reference this type is defined in mysql_driver.h file. Here is the code snippet I used in my program.

sql::mysql::MySQL_Driver *driver;
try {     
    driver = sql::mysql::get_driver_instance();
}

and I compiled the program with -l mysqlcppconn linker option

and don't forget to include this header

#include "mysql_driver.h" 

How to do a for loop in windows command line?

The commandline interpreter does indeed have a FOR construct that you can use from the command prompt or from within a batch file.

For your purpose, you probably want something like:

FOR %i IN (*.ext) DO my-function %i

Which will result in the name of each file with extension *.ext in the current directory being passed to my-function (which could, for example, be another .bat file).

The (*.ext) part is the "filespec", and is pretty flexible with how you specify sets of files. For example, you could do:

FOR %i IN (C:\Some\Other\Dir\*.ext) DO my-function %i

To perform an operation in a different directory.

There are scores of options for the filespec and FOR in general. See

HELP FOR

from the command prompt for more information.

How to explain callbacks in plain english? How are they different from calling one function from another function?

In non-programmer terms, a callback is a fill-in-the-blank in a program.

A common item on many paper forms is "Person to call in case of emergency". There is a blank line there. You write in someone's name and phone number. If an emergency occurs, then that person gets called.

  • Everyone gets the same blank form, but
  • Everyone can write a different emergency contact number.

This is key. You do not change the form (the code, usually someone else's). However you can fill in missing pieces of information (your number).

Example 1:

Callbacks are used as customized methods, possibly for adding to/changing a program's behavior. For example, take some C code that performs a function, but does not know how to print output. All it can do is make a string. When it tries to figure out what to do with the string, it sees a blank line. But, the programmer gave you the blank to write your callback in!

In this example, you do not use a pencil to fill in a blank on a sheet of paper, you use the function set_print_callback(the_callback).

  • The blank variable in the module/code is the blank line,
  • set_print_callback is the pencil,
  • and the_callback is your information you are filling in.

You've now filled in this blank line in the program. Whenever it needs to print output, it will look at that blank line, and follow the instructions there (i.e. call the function you put there.) Practically, this allows the possibility of printing to screen, to a log file, to a printer, over a network connection, or any combination thereof. You have filled in the blank with what you want to do.

Example 2:

When you get told you need to call an emergency number, you go and read what is written on the paper form, and then call the number you read. If that line is blank nothing will be done.

Gui programming works much the same way. When a button is clicked, the program needs to figure out what to do next. It goes and looks for the callback. This callback happens to be in a blank labeled "Here's what you do when Button1 is clicked"

Most IDEs will automatically fill in the blank for you (write the basic method) when you ask it to (e.g. button1_clicked). However that blank can have any method you darn well please. You could call the method run_computations or butter_the_biscuits as long as you put that callback's name in the proper blank. You could put "555-555-1212" in the emergency number blank. It doesn't make much sense, but it's permissible.


Final note: That blank line that you're filling in with the callback? It can be erased and re-written at will. (whether you should or not is another question, but that is a part of their power)

How to sum up an array of integers in C#

In one of my apps I used :

public class ClassBlock
{
    public int[] p;
    public int Sum
    {
        get { int s = 0;  Array.ForEach(p, delegate (int i) { s += i; }); return s; }
    }
}

unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

Try this. For python 2.7.12 we need to define constructor or need to add self to each methods followed by defining an instance of an class called object.

import cv2

class calculator:

#   def __init__(self):

def multiply(self, a, b):
    x= a*b
    print(x)

def subtract(self, a,b):
    x = a-b
    print(x)

def add(self, a,b):
    x = a+b
    print(x)

def div(self, a,b):
    x = a/b
    print(x)

 calc = calculator()
 calc.multiply(2,3)
 calc.add(2,3)
 calc.div(10,5)
 calc.subtract(2,3)

How to split csv whose columns may contain ,

You could split on all commas that do have an even number of quotes following them.

You would also like to view at the specf for CSV format about handling comma's.

Useful Link : C# Regex Split - commas outside quotes

Delete statement in SQL is very slow

In my case the database statistics had become corrupt. The statement

delete from tablename where col1 = 'v1' 

was taking 30 seconds even though there were no matching records but

delete from tablename where col1 = 'rubbish'

ran instantly

running

update statistics tablename

fixed the issue

Use the auto keyword in C++ STL

The auto keyword gets the type from the expression on the right of =. Therefore it will work with any type, the only requirement is to initialize the auto variable when declaring it so that the compiler can deduce the type.

Examples:

auto a = 0.0f;  // a is float
auto b = std::vector<int>();  // b is std::vector<int>()

MyType foo()  { return MyType(); }

auto c = foo();  // c is MyType

What is Python used for?

Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.

  1. Python is dynamically typed: it means that you don't declare a type (e.g. 'integer') for a variable name, and then assign something of that type (and only that type). Instead, you have variable names, and you bind them to entities whose type stays with the entity itself. a = 5 makes the variable name a to refer to the integer 5. Later, a = "hello" makes the variable name a to refer to a string containing "hello". Static typed languages would have you declare int a and then a = 5, but assigning a = "hello" would have been a compile time error. On one hand, this makes everything more unpredictable (you don't know what a refers to). On the other hand, it makes very easy to achieve some results a static typed languages makes very difficult.
  2. Python is strongly typed. It means that if a = "5" (the string whose value is '5') will remain a string, and never coerced to a number if the context requires so. Every type conversion in python must be done explicitly. This is different from, for example, Perl or Javascript, where you have weak typing, and can write things like "hello" + 5 to get "hello5".
  3. Python is object oriented, with class-based inheritance. Everything is an object (including classes, functions, modules, etc), in the sense that they can be passed around as arguments, have methods and attributes, and so on.
  4. Python is multipurpose: it is not specialised to a specific target of users (like R for statistics, or PHP for web programming). It is extended through modules and libraries, that hook very easily into the C programming language.
  5. Python enforces correct indentation of the code by making the indentation part of the syntax. There are no control braces in Python. Blocks of code are identified by the level of indentation. Although a big turn off for many programmers not used to this, it is precious as it gives a very uniform style and results in code that is visually pleasant to read.
  6. The code is compiled into byte code and then executed in a virtual machine. This means that precompiled code is portable between platforms.

Python can be used for any programming task, from GUI programming to web programming with everything else in between. It's quite efficient, as much of its activity is done at the C level. Python is just a layer on top of C. There are libraries for everything you can think of: game programming and openGL, GUI interfaces, web frameworks, semantic web, scientific computing...

Get child Node of another Node, given node name

//xn=list of parent nodes......                
foreach (XmlNode xn in xnList)
{                                           
    foreach (XmlNode child in xn.ChildNodes) 
    {
        if (child.Name.Equals("name")) 
        {
            name = child.InnerText; 
        }
        if (child.Name.Equals("age"))
        {
            age = child.InnerText; 
        }
    }
}

How to launch PowerShell (not a script) from the command line

If you go to C:\Windows\system32\Windowspowershell\v1.0 (and C:\Windows\syswow64\Windowspowershell\v1.0 on x64 machines) in Windows Explorer and double-click powershell.exe you will see that it opens PowerShell with a black background. The PowerShell console shows up as blue when opened from the start menu because the console properties for shortcuts to powershell.exe can be set independently from the default properties.

To set the default options, font, colors and layout, open a PowerShell console, type Alt-Space, and select the Defaults menu option.

Running start powershell from cmd.exe should start a new console with your default settings.

Does Python have a ternary conditional operator?

You might often find

cond and on_true or on_false

but this lead to problem when on_true == 0

>>> x = 0
>>> print x == 0 and 0 or 1 
1
>>> x = 1
>>> print x == 0 and 0 or 1 
1

where you would expect for a normal ternary operator this result

>>> x = 0
>>> print 0 if x == 0 else 1 
0
>>> x = 1
>>> print 0 if x == 0 else 1 
1

Pass variables between two PHP pages without using a form or the URL of page

<?php
session_start();

$message1 = "A message";
$message2 = "Another message";

$_SESSION['firstMessage'] = $message1;
$_SESSION['secondMessage'] = $message2; 
?>

Stores the sessions on page 1 then on page 2 do

<?php
session_start();

echo $_SESSION['firstMessage'];
echo $_SESSION['secondMessage'];
?>

How to get URL parameters with Javascript?

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

So you can use:

myvar = getURLParameter('myvar');

How to change menu item text dynamically in Android

For people that need the title set statically. This can be done in the AndroidManifest.xml

<activity
    android:name=".ActivityName"
    android:label="Title Text" >
</activity>

Options Menu Title Text

Which version of C# am I using

In order to see the installed compiler version of VC#:

Open Visual Studio command prompt and just type csc then press Enter.

You will see something like following:

Microsoft (R) Visual C# Compiler version 4.0.30319.34209

for Microsoft (R) .NET Framework 4.5

Copyright (C) Microsoft Corporation. All rights reserved.

P.S.: "CSC" stand for "C Sharp Compiler". Actually using this command you run csc.exe which is an executable file which is located in "c:\Windows\Microsoft.NET\Framework\vX.X.XXX". For more information about CSC visit http://www.file.net/process/csc.exe.html

What file uses .md extension and how should I edit them?

Extension '.md' refers to Markdown files.

If you don't want to install an app to read them in that format, you can simply use TextEdit or Xcode itself to open it on Mac.

On any other OS, you should be able to open it using any text editor, though as expected, you will not see it in Markdown format.

Make Bootstrap's Carousel both center AND responsive?

This work for me very simple just add attribute align="center". Tested on Bootstrap 4.

<!-- The slideshow -->
            <div class="carousel-inner" align="center">             
                <div class="carousel-item active">
                    <img src="image1.jpg" alt="no image" height="550">
                </div>
                <div class="carousel-item">
                    <img src="image2.jpg" alt="no image" height="550">
                </div>                
                <div class="carousel-item">
                    <img src="image3.png" alt="no image" height="550">
                </div>
             </div>

How to present a modal atop the current view in Swift

You can try this code for Swift

 let popup : PopupVC = self.storyboard?.instantiateViewControllerWithIdentifier("PopupVC") as! PopupVC
 let navigationController = UINavigationController(rootViewController: popup)
 navigationController.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext
 self.presentViewController(navigationController, animated: true, completion: nil)

For swift 4 latest syntax using extension

extension UIViewController {
    func presentOnRoot(`with` viewController : UIViewController){
        let navigationController = UINavigationController(rootViewController: viewController)
        navigationController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
        self.present(navigationController, animated: false, completion: nil)
    }
}

How to use

let popup : PopupVC = self.storyboard?.instantiateViewControllerWithIdentifier("PopupVC") as! PopupVC
self.presentOnRoot(with: popup)

Replacing a fragment with another fragment inside activity group

hope you are doing well.when I started work with Android Fragments then I was also having the same problem then I read about 1- How to switch fragment with other. 2- How to add fragment if Fragment container does not have any fragment.

then after some R&D, I created a function which helps me in many Projects till now and I am still using this simple function.

public void switchFragment(BaseFragment baseFragment) {
    try {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
        if (getSupportFragmentManager().findFragmentById(R.id.home_frame) == null) {
            ft.add(R.id.home_frame, baseFragment);
        } else {
            ft.replace(R.id.home_frame, baseFragment);
        }
        ft.addToBackStack(null);
        ft.commit();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

enjoy your code time :)

Check if value exists in column in VBA

Try adding WorksheetFunction:

If Not IsError(Application.WorksheetFunction.Match(ValueToSearchFor, RangeToSearchIn, 0)) Then
' String is in range

.htaccess or .htpasswd equivalent on IIS?

I've never used it but Trilead, a free ISAPI filter which enables .htaccess based control, looks like what you want.

Counting in a FOR loop using Windows Batch script

It's not working because the entire for loop (from the for to the final closing parenthesis, including the commands between those) is being evaluated when it's encountered, before it begins executing.

In other words, %count% is replaced with its value 1 before running the loop.

What you need is something like:

setlocal enableextensions enabledelayedexpansion
set /a count = 1
for /f "tokens=*" %%a in (config.properties) do (
  set /a count += 1
  echo !count!
)
endlocal

Delayed expansion using ! instead of % will give you the expected behaviour. See also here.


Also keep in mind that setlocal/endlocal actually limit scope of things changed inside so that they don't leak out. If you want to use count after the endlocal, you have to use a "trick" made possible by the very problem you're having:

endlocal && set count=%count%

Let's say count has become 7 within the inner scope. Because the entire command is interpreted before execution, it effectively becomes:

endlocal && set count=7

Then, when it's executed, the inner scope is closed off, returning count to it's original value. But, since the setting of count to seven happens in the outer scope, it's effectively leaking the information you need.

You can string together multiple sub-commands to leak as much information as you need:

endlocal && set count=%count% && set something_else=%something_else%

Jquery button click() function is not working

You need to use a delegated event handler, as the #add elements dynamically appended won't have the click event bound to them. Try this:

$("#buildyourform").on('click', "#add", function() {
    // your code...
});

Also, you can make your HTML strings easier to read by mixing line quotes:

var fieldWrapper = $('<div class="fieldwrapper" name="field' + intId + '" id="field' + intId + '"/>');

Or even supplying the attributes as an object:

var fieldWrapper = $('<div></div>', { 
    'class': 'fieldwrapper',
    'name': 'field' + intId,
    'id': 'field' + intId
});

Loading a properties file from Java package

When loading the Properties from a Class in the package com.al.common.email.templates you can use

Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("foo.properties");
prop.load(in);
in.close();

(Add all the necessary exception handling).

If your class is not in that package, you need to aquire the InputStream slightly differently:

InputStream in = 
 getClass().getResourceAsStream("/com/al/common/email/templates/foo.properties");

Relative paths (those without a leading '/') in getResource()/getResourceAsStream() mean that the resource will be searched relative to the directory which represents the package the class is in.

Using java.lang.String.class.getResource("foo.txt") would search for the (inexistent) file /java/lang/String/foo.txt on the classpath.

Using an absolute path (one that starts with '/') means that the current package is ignored.

Rails - How to use a Helper Inside a Controller

In Rails 5 use the helpers.helper_function in your controller.

Example:

def update
  # ...
  redirect_to root_url, notice: "Updated #{helpers.pluralize(count, 'record')}"
end

Source: From a comment by @Markus on a different answer. I felt his answer deserved it's own answer since it's the cleanest and easier solution.

Reference: https://github.com/rails/rails/pull/24866

make: *** No rule to make target `all'. Stop

Your makefile should ideally be named makefile, not make. Note that you can call your makefile anything you like, but as you found, you then need the -f option with make to specify the name of the makefile. Using the default name of makefile just makes life easier.

Check existence of directory and create if doesn't exist

One-liner:

if (!dir.exists(output_dir)) {dir.create(output_dir)}

Example:

dateDIR <- as.character(Sys.Date())
outputDIR <- file.path(outD, dateDIR)
if (!dir.exists(outputDIR)) {dir.create(outputDIR)}

Convert a negative number to a positive one in JavaScript

I know another way to do it. This technique works negative to positive & Vice Versa

var x = -24;
var result = x * -1;

Vice Versa:

var x = 58;
var result = x * -1;

LIVE CODE:

_x000D_
_x000D_
// NEGATIVE TO POSITIVE: ******************************************_x000D_
var x = -24;_x000D_
var result = x * -1;_x000D_
console.log(result);_x000D_
_x000D_
// VICE VERSA: ****************************************************_x000D_
var x = 58;_x000D_
var result = x * -1;_x000D_
console.log(result);_x000D_
_x000D_
// FLOATING POINTS: ***********************************************_x000D_
var x = 42.8;_x000D_
var result = x * -1;_x000D_
console.log(result);_x000D_
_x000D_
// FLOATING POINTS VICE VERSA: ************************************_x000D_
var x = -76.8;_x000D_
var result = x * -1;_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

Find the IP address of the client in an SSH session

Assuming he opens an interactive session (that is, allocates a pseudo terminal) and you have access to stdin, you can call an ioctl on that device to get the device number (/dev/pts/4711) and try to find that one in /var/run/utmp (where there will also be the username and the IP address the connection originated from).

SQL Left Join first match only

Add an identity column (PeopleID) and then use a correlated subquery to return the first value for each value.

SELECT *
FROM People p
WHERE PeopleID = (
    SELECT MIN(PeopleID) 
    FROM People 
    WHERE IDNo = p.IDNo
)

UDP vs TCP, how much faster is it?

In some applications TCP is faster (better throughput) than UDP.

This is the case when doing lots of small writes relative to the MTU size. For example, I read an experiment in which a stream of 300 byte packets was being sent over Ethernet (1500 byte MTU) and TCP was 50% faster than UDP.

The reason is because TCP will try and buffer the data and fill a full network segment thus making more efficient use of the available bandwidth.

UDP on the other hand puts the packet on the wire immediately thus congesting the network with lots of small packets.

You probably shouldn't use UDP unless you have a very specific reason for doing so. Especially since you can give TCP the same sort of latency as UDP by disabling the Nagle algorithm (for example if you're transmitting real-time sensor data and you're not worried about congesting the network with lot's of small packets).

How can I get the iOS 7 default blue color programmatically?

From iOS 7 there is an API and you can get (and set) the tint color with:

self.view.tintColor

Or if you need the CGColor:

self.view.tintColor.CGColor

How can I disable the Maven Javadoc plugin from the command line?

You can use the maven.javadoc.skip property to skip execution of the plugin, going by the Mojo's javadoc. You can specify the value as a Maven property:

<properties>
    <maven.javadoc.skip>true</maven.javadoc.skip>
</properties>

or as a command-line argument: -Dmaven.javadoc.skip=true, to skip generation of the Javadocs.

Best C# API to create PDF

My work uses Winnovative's PDF generator (We've used it mainly to convert HTML to PDF, but you can generate it other ways as well)

How to get the current date without the time?

You can use DateTime.Now.ToShortDateString() like so:

var test = $"<b>Date of this report:</b> {DateTime.Now.ToShortDateString()}";

Setting the MySQL root user password on OS X

Try the command FLUSH PRIVILEGES when you log into the MySQL terminal. If that doesn't work, try the following set of commands while in the MySQL terminal

$ mysql -u root
mysql> USE mysql;
mysql> UPDATE user SET password=PASSWORD("NEWPASSWORD") WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> quit

Change out NEWPASSWORD with whatever password you want. Should be all set!

Update: As of MySQL 5.7, the password field has been renamed authentication_string. When changing the password, use the following query to change the password. All other commands remain the same:

mysql> UPDATE user SET authentication_string=PASSWORD("NEWPASSWORD") WHERE User='root';

Update: On 8.0.15 (maybe already before that version) the PASSWORD() function does not work, as mentioned in the comments below. You have to use:

UPDATE mysql.user SET authentication_string='password' WHERE User='root';

Running Python from Atom

Yes, you can do it by:

-- Install Atom

-- Install Python on your system. Atom requires the latest version of Python (currently 3.8.5). Note that Anaconda sometimes may not have this version, and depending on how you installed it, it may not have been added to the PATH. Install Python via https://www.python.org/ and make sure to check the option of "Add to PATH"

-- Install "scripts" on Atom via "Install packages"

-- Install any other autocomplete package like Kite on Atom if you want that feature.

-- Run it

I tried the normal way (I had Python installed via Anaconda) but Atom did not detect it & gave me an error when I tried to run Python. This is the way around it.

How to include layout inside layout?

Learn More Using this link https://developer.android.com/training/improving-layouts/reusing-layouts.html

    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".Game_logic">
    
          
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
    
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dp"
                    android:id="@+id/text1"
                    android:textStyle="bold"
                    tools:text="Player " />
    
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:layout_marginLeft="20dp"
    
                    android:id="@+id/text2"
                    tools:text="Player 2" />
          
            
          
        </LinearLayout>
    </androidx.constraintlayout.widget.ConstraintLayout>

Blockquote

  • Above layout you can used in other activity using

     <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
                      xmlns:app="http://schemas.android.com/apk/res-auto"
                      xmlns:tools="http://schemas.android.com/tools"
                      android:layout_width="match_parent"
                      android:layout_height="match_parent"
                      tools:context=".SinglePlayer">   
    
              <include layout="@layout/activity_game_logic"/> 
          </androidx.constraintlayout.widget.ConstraintLayout>
    

Scala: what is the best way to append an element to an Array?

You can use :+ to append element to array and +: to prepend it:

0 +: array :+ 4

should produce:

res3: Array[Int] = Array(0, 1, 2, 3, 4)

It's the same as with any other implementation of Seq.

ConnectionTimeout versus SocketTimeout

A connection timeout is the maximum amount of time that the program is willing to wait to setup a connection to another process. You aren't getting or posting any application data at this point, just establishing the connection, itself.

A socket timeout is the timeout when waiting for individual packets. It's a common misconception that a socket timeout is the timeout to receive the full response. So if you have a socket timeout of 1 second, and a response comprised of 3 IP packets, where each response packet takes 0.9 seconds to arrive, for a total response time of 2.7 seconds, then there will be no timeout.

Operation must use an updatable query. (Error 3073) Microsoft Access

Since Jet 4, all queries that have a join to a SQL statement that summarizes data will be non-updatable. You aren't using a JOIN, but the WHERE clause is exactly equivalent to a join, and thus, the Jet query optimizer treats it the same way it treats a join.

I'm afraid you're out of luck without a temp table, though maybe somebody with greater Jet SQL knowledge than I can come up with a workaround.

BTW, it might have been updatable in Jet 3.5 (Access 97), as a whole lot of queries were updatable then that became non-updatable when upgraded to Jet 4.

--

How to check for an empty object in an AngularJS view

I have met a similar problem when checking emptiness in a component. In this case, the controller must define a method that actually performs the test and the view uses it:

function FormNumericFieldController(/*$scope, $element, $attrs*/ ) {
    var ctrl = this;

    ctrl.isEmptyObject = function(object) {
        return angular.equals(object, {});
    }
}

<!-- any validation error will trigger an error highlight -->
<span ng-class="{'has-error': !$ctrl.isEmptyObject($ctrl.formFieldErrorRef) }">
    <!-- validated control here -->
</span>

How to get a URL parameter in Express?

You can do something like req.param('tagId')

C++ string to double conversion

#include <iostream>
#include <string>
using namespace std;

int main()
{
    cout << stod("  99.999  ") << endl;
}

Output: 99.999 (which is double, whitespace was automatically stripped)

Since C++11 converting string to floating-point values (like double) is available with functions:
stof - convert str to a float
stod - convert str to a double
stold - convert str to a long double

As conversion of string to int was also mentioned in the question, there are the following functions in C++11:
stoi - convert str to an int
stol - convert str to a long
stoul - convert str to an unsigned long
stoll - convert str to a long long
stoull - convert str to an unsigned long long

SQL Server 2008: How to query all databases sizes?

IF OBJECT_ID('tempdb.dbo.#space') IS NOT NULL
    DROP TABLE #space

CREATE TABLE #space (
      database_id INT PRIMARY KEY
    , data_used_size DECIMAL(18,2)
    , log_used_size DECIMAL(18,2)
)

DECLARE @SQL NVARCHAR(MAX)

SELECT @SQL = STUFF((
    SELECT '
    USE [' + d.name + ']
    INSERT INTO #space (database_id, data_used_size, log_used_size)
    SELECT
          DB_ID()
        , SUM(CASE WHEN [type] = 0 THEN space_used END)
        , SUM(CASE WHEN [type] = 1 THEN space_used END)
    FROM (
        SELECT s.[type], space_used = SUM(FILEPROPERTY(s.name, ''SpaceUsed'') * 8. / 1024)
        FROM sys.database_files s
        GROUP BY s.[type]
    ) t;'
    FROM sys.databases d
    WHERE d.[state] = 0
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')

EXEC sys.sp_executesql @SQL

SELECT
      d.database_id
    , d.name
    , d.state_desc
    , d.recovery_model_desc
    , t.total_size
    , t.data_size
    , s.data_used_size
    , t.log_size
    , s.log_used_size
FROM (
    SELECT
          database_id
        , log_size = CAST(SUM(CASE WHEN [type] = 1 THEN size END) * 8. / 1024 AS DECIMAL(18,2))
        , data_size = CAST(SUM(CASE WHEN [type] = 0 THEN size END) * 8. / 1024 AS DECIMAL(18,2))
        , total_size = CAST(SUM(size) * 8. / 1024 AS DECIMAL(18,2))
    FROM sys.master_files
    GROUP BY database_id
) t
JOIN sys.databases d ON d.database_id = t.database_id
LEFT JOIN #space s ON d.database_id = s.database_id
ORDER BY t.total_size DESC

How is attr_accessible used in Rails 4?

If you prefer attr_accessible, you could use it in Rails 4 too. You should install it like gem:

gem 'protected_attributes'

after that you could use attr_accessible in you models like in Rails 3

Also, and i think that is the best way- using form objects for dealing with mass assignment, and saving nested objects, and you can also use protected_attributes gem that way

class NestedForm
   include  ActiveModel::MassAssignmentSecurity
   attr_accessible :name,
                   :telephone, as: :create_params
   def create_objects(params)
      SomeModel.new(sanitized_params(params, :create_params))
   end
end

How to Sort Date in descending order From Arraylist Date in android?

Date's compareTo() you're using will work for ascending order.

To do descending, just reverse the value of compareTo() coming out. You can use a single Comparator class that takes in a flag/enum in the constructor that identifies the sort order

public int compare(MyObject lhs, MyObject rhs) {

    if(SortDirection.Ascending == m_sortDirection) {
        return lhs.MyDateTime.compareTo(rhs.MyDateTime);
    }

    return rhs.MyDateTime.compareTo(lhs.MyDateTime);
}

You need to call Collections.sort() to actually sort the list.

As a side note, I'm not sure why you're defining your map inside your for loop. I'm not exactly sure what your code is trying to do, but I assume you want to populate the indexed values from your for loop in to the map.

Check if a number has a decimal place/is a whole number

Here's an excerpt from my guard library (inspired by Effective JavaScript by David Herman):

var guard = {

    guard: function(x) {
        if (!this.test(x)) {
            throw new TypeError("expected " + this);
        }
    }

    // ...
};

// ...

var number = Object.create(guard);
number.test = function(x) {
    return typeof x === "number" || x instanceof Number;
};
number.toString = function() {
    return "number";
};


var uint32 = Object.create(guard);
uint32.test = function(x) {
    return typeof x === "number" && x === (x >>> 0);
};
uint32.toString = function() {
    return "uint32";
};


var decimal = Object.create(guard);
decimal.test = function(x) {
    return number.test(x) && !uint32.test(x);
};
decimal.toString = function() {
    return "decimal";
};


uint32.guard(1234);     // fine
uint32.guard(123.4);    // TypeError: expected uint32

decimal.guard(1234);    // TypeError: expected decimal
decimal.guard(123.4);   // fine

How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

In swift 4.2 I used following code to show and hide code using NSNotification

 @objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo? [UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        let keyboardheight = keyboardSize.height
        print(keyboardheight)
    }
}

How can I merge two commits into one if I already started rebase?

If your master branch git log looks something like following:

commit ac72a4308ba70cc42aace47509a5e
Author: <[email protected]>
Date:   Tue Jun 11 10:23:07 2013 +0500

    Added algorithms for Cosine-similarity

commit 77df2a40e53136c7a2d58fd847372
Author: <[email protected]>
Date:   Tue Jun 11 13:02:14 2013 -0700

    Set stage for similar objects

commit 249cf9392da197573a17c8426c282
Author: Ralph <[email protected]>
Date:   Thu Jun 13 16:44:12 2013 -0700

    Fixed a bug in space world automation

and you want to merge the top two commits just do following easy steps:

  1. First to be on safe side checkout the second last commit in a separate branch. You can name the branch anything. git checkout 77df2a40e53136c7a2d58fd847372 -b merged-commits
  2. Now, just cherry-pick your changes from the last commit into this new branch as: git cherry-pick -n -x ac72a4308ba70cc42aace47509a5e. (Resolve conflicts if arise any)
  3. So now, your changes in last commit are there in your second last commit. But you still have to commit, so first add the changes you just cherry-picked and then execute git commit --amend.

That's it. You may push this merged version in branch "merged-commits" if you like.

Also, you can discard the back-to-back two commits in your master branch now. Just update your master branch as:

git checkout master
git reset --hard origin/master (CAUTION: This command will remove any local changes to your master branch)
git pull

How to pretty-print a numpy.array without scientific notation and with given precision?

numpy.char.mod may also be useful, depending on the details of your application e.g.:numpy.char.mod('Value=%4.2f', numpy.arange(5, 10, 0.1)) will return a string array with elements "Value=5.00", "Value=5.10" etc. (as a somewhat contrived example).

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

double doubleVal = 1.745;
double doubleVal1 = 0.745;
System.out.println(new BigDecimal(doubleVal));
System.out.println(new BigDecimal(doubleVal1));

outputs:

1.74500000000000010658141036401502788066864013671875
0.74499999999999999555910790149937383830547332763671875

Which shows the real value of the two doubles and explains the result you get. As pointed out by others, don't use the double constructor (apart from the specific case where you want to see the actual value of a double).

More about double precision:

recursion versus iteration

Is it correct to say that everywhere recursion is used a for loop could be used?

Yes, because recursion in most CPUs is modeled with loops and a stack data structure.

And if recursion is usually slower what is the technical reason for using it?

It is not "usually slower": it's recursion that is applied incorrectly that's slower. On top of that, modern compilers are good at converting some recursions to loops without even asking.

And if it is always possible to convert an recursion into a for loop is there a rule of thumb way to do it?

Write iterative programs for algorithms best understood when explained iteratively; write recursive programs for algorithms best explained recursively.

For example, searching binary trees, running quicksort, and parsing expressions in many programming languages is often explained recursively. These are best coded recursively as well. On the other hand, computing factorials and calculating Fibonacci numbers are much easier to explain in terms of iterations. Using recursion for them is like swatting flies with a sledgehammer: it is not a good idea, even when the sledgehammer does a really good job at it+.


+ I borrowed the sledgehammer analogy from Dijkstra's "Discipline of Programming".

How to export a table dataframe in PySpark to csv?

If you cannot use spark-csv, you can do the following:

df.rdd.map(lambda x: ",".join(map(str, x))).coalesce(1).saveAsTextFile("file.csv")

If you need to handle strings with linebreaks or comma that will not work. Use this:

import csv
import cStringIO

def row2csv(row):
    buffer = cStringIO.StringIO()
    writer = csv.writer(buffer)
    writer.writerow([str(s).encode("utf-8") for s in row])
    buffer.seek(0)
    return buffer.read().strip()

df.rdd.map(row2csv).coalesce(1).saveAsTextFile("file.csv")

Dynamic Height Issue for UITableView Cells (Swift)

In addition to what others have said,

SET YOUR LABEL'S CONSTRAINTS RELATIVE TO THE SUPERVIEW!

So instead of placing your label's constraints relative to other things around it, constrain it to the table view cell's content view.

Then, make sure your label's height is set to more than or equal 0, and the number of lines is set to 0.

Then in ViewDidLoad add:

tableView.estimatedRowHeight = 695

tableView.rowHeight = UITableViewAutomaticDimension

Why use Optional.of over Optional.ofNullable?

This depends upon scenarios.

Let's say you have some business functionality and you need to process something with that value further but having null value at time of processing would impact it.

Then, in that case, you can use Optional<?>.

String nullName = null;

String name = Optional.ofNullable(nullName)
                      .map(<doSomething>)
                      .orElse("Default value in case of null");

Apply .gitignore on an existing repository already tracking large number of files

If you added your .gitignore too late, git will continue to track already commited files regardless. To fix this, you can always remove all cached instances of the unwanted files.

First, to check what files are you actually tracking, you can run:

git ls-tree --name-only --full-tree -r HEAD

Let say that you found unwanted files in a directory like cache/ so, it's safer to target that directory instead of all of your files.

So instead of:

git rm -r --cached .

It's safer to target the unwanted file or directory:

git rm -r --cached cache/

Then proceed to add all changes,

git add .

and commit...

git commit -m ".gitignore is now working"

Reference: https://amyetheredge.com/code/13.html

How to resize a custom view programmatically?

if you are overriding onMeasure, don't forget to update the new sizes

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(newWidth, newHeight);
}

How to call a method after bean initialization is complete?

You could deploy a custom BeanPostProcessor in your application context to do it. Or if you don't mind implementing a Spring interface in your bean, you could use the InitializingBean interface or the "init-method" directive (same link).

Use cases for the 'setdefault' dict method

The different use case for setdefault() is when you don't want to overwrite the value of an already set key. defaultdict overwrites, while setdefault() does not. For nested dictionaries it is more often the case that you want to set a default only if the key is not set yet, because you don't want to remove the present sub dictionary. This is when you use setdefault().

Example with defaultdict:

>>> from collection import defaultdict()
>>> foo = defaultdict()
>>> foo['a'] = 4
>>> foo['a'] = 2
>>> print(foo)
defaultdict(None, {'a': 2})

setdefault doesn't overwrite:

>>> bar = dict()
>>> bar.setdefault('a', 4)
>>> bar.setdefault('a', 2)
>>> print(bar)
{'a': 4}

Converting Milliseconds to Minutes and Seconds?

I would suggest using TimeUnit. You can use it like this:

long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);

SSL "Peer Not Authenticated" error with HttpClient 4.1

Im not a java developer but was using a java app to test a RESTful API. In order for me to fix the error I had to install the intermediate certificates in the webserver in order to make the error go away. I was using lighttpd, the original certificate was installed on an IIS server. Hope it helps. These were the certificates I had missing on the server.

  • CA.crt
  • UTNAddTrustServer_CA.crt
  • AddTrustExternalCARoot.crt

When creating a service with sc.exe how to pass in context parameters?

Be sure to have quotes at beginning and end of your binPath value.

Javascript close alert box

If you do it programmatically in JS it will be like reinventing the wheel. I recommend using a jQuery plugin called jGrowl

How to change FontSize By JavaScript?

Please never do this in real projects:

_x000D_
_x000D_
document.getElementById("span").innerHTML = "String".fontsize(25);
_x000D_
<span id="span"></span>
_x000D_
_x000D_
_x000D_

Rename a file using Java

Yes, you can use File.renameTo(). But remember to have the correct path while renaming it to a new file.

import java.util.Arrays;
import java.util.List;

public class FileRenameUtility {
public static void main(String[] a) {
    System.out.println("FileRenameUtility");
    FileRenameUtility renameUtility = new FileRenameUtility();
    renameUtility.fileRename("c:/Temp");
}

private void fileRename(String folder){
    File file = new File(folder);
    System.out.println("Reading this "+file.toString());
    if(file.isDirectory()){
        File[] files = file.listFiles();
        List<File> filelist = Arrays.asList(files);
        filelist.forEach(f->{
           if(!f.isDirectory() && f.getName().startsWith("Old")){
               System.out.println(f.getAbsolutePath());
               String newName = f.getAbsolutePath().replace("Old","New");
               boolean isRenamed = f.renameTo(new File(newName));
               if(isRenamed)
                   System.out.println(String.format("Renamed this file %s to  %s",f.getName(),newName));
               else
                   System.out.println(String.format("%s file is not renamed to %s",f.getName(),newName));
           }
        });

    }
}

}

Disable-web-security in Chrome 48+

I'm seeing the same thing. A quick google found this question and a bug on the chromium forums. It seems that the --user-data-dir flag is now required. Edit to add user-data-dir guide

Unit test naming best practices

I recently came up with the following convention for naming my tests, their classes and containing projects in order to maximize their descriptivenes:

Lets say I am testing the Settings class in a project in the MyApp.Serialization namespace.

First I will create a test project with the MyApp.Serialization.Tests namespace.

Within this project and of course the namespace I will create a class called IfSettings (saved as IfSettings.cs).

Lets say I am testing the SaveStrings() method. -> I will name the test CanSaveStrings().

When I run this test it will show the following heading:

MyApp.Serialization.Tests.IfSettings.CanSaveStrings

I think this tells me very well, what it is testing.

Of course it is usefull that in English the noun "Tests" is the same as the verb "tests".

There is no limit to your creativity in naming the tests, so that we get full sentence headings for them.

Usually the Test names will have to start with a verb.

Examples include:

  • Detects (e.g. DetectsInvalidUserInput)
  • Throws (e.g. ThrowsOnNotFound)
  • Will (e.g. WillCloseTheDatabaseAfterTheTransaction)

etc.

Another option is to use "that" instead of "if".

The latter saves me keystrokes though and describes more exactly what I am doing, since I don't know, that the tested behavior is present, but am testing if it is.

[Edit]

After using above naming convention for a little longer now, I have found, that the If prefix can be confusing, when working with interfaces. It just so happens, that the testing class IfSerializer.cs looks very similar to the interface ISerializer.cs in the "Open Files Tab". This can get very annoying when switching back and forth between the tests, the class being tested and its interface. As a result I would now choose That over If as a prefix.

Additionally I now use - only for methods in my test classes as it is not considered best practice anywhere else - the "_" to separate words in my test method names as in:

[Test] public void detects_invalid_User_Input()

I find this to be easier to read.

[End Edit]

I hope this spawns some more ideas, since I consider naming tests of great importance as it can save you a lot of time that would otherwise have been spent trying to understand what the tests are doing (e.g. after resuming a project after an extended hiatus).

Read XML file into XmlDocument

If your .NET version is newer than 3.0 you can try using System.Xml.Linq.XDocument instead of XmlDocument. It is easier to process data with XDocument.

Clear History and Reload Page on Login/Logout Using Ionic Framework

The controller is called only once, and you SHOULD preserve this logic model, what I usually do is:

I create a method $scope.reload(params)

At the beginning of this method I call $ionicLoading.show({template:..}) to show my custom spinner

When may reload process is finished, I can call $ionicLoading.hide() as a callback

Finally, Inside the button REFRESH, I add ng-click = "reload(params)"

The only downside of this solution is that you lose the ionic navigation history system

Hope this helps!

Hide text within HTML?

you can use css property to hide style="display:none;"

<div style="display:none;">CREDITS_HERE</div>

Check string for palindrome

Using Stream API:

private static boolean isPalindrome(char[] warray) {
    return IntStream.range(0, warray.length - 1)
            .takeWhile(i -> i < warray.length / 2)
            .noneMatch(i -> warray[i] != warray[warray.length - 1 - i]);
}

Using python map and other functional tools

Are you familiar with other functional languages? i.e. are you trying to learn how python does functional programming, or are you trying to learn about functional programming and using python as the vehicle?

Also, do you understand list comprehensions?

map(f, sequence)

is directly equivalent (*) to:

[f(x) for x in sequence]

In fact, I think map() was once slated for removal from python 3.0 as being redundant (that didn't happen).

map(f, sequence1, sequence2)

is mostly equivalent to:

[f(x1, x2) for x1, x2 in zip(sequence1, sequence2)]

(there is a difference in how it handles the case where the sequences are of different length. As you saw, map() fills in None when one of the sequences runs out, whereas zip() stops when the shortest sequence stops)

So, to address your specific question, you're trying to produce the result:

foos[0], bars
foos[1], bars
foos[2], bars
# etc.

You could do this by writing a function that takes a single argument and prints it, followed by bars:

def maptest(x):
     print x, bars
map(maptest, foos)

Alternatively, you could create a list that looks like this:

[bars, bars, bars, ] # etc.

and use your original maptest:

def maptest(x, y):
    print x, y

One way to do this would be to explicitely build the list beforehand:

barses = [bars] * len(foos)
map(maptest, foos, barses)

Alternatively, you could pull in the itertools module. itertools contains many clever functions that help you do functional-style lazy-evaluation programming in python. In this case, we want itertools.repeat, which will output its argument indefinitely as you iterate over it. This last fact means that if you do:

map(maptest, foos, itertools.repeat(bars))

you will get endless output, since map() keeps going as long as one of the arguments is still producing output. However, itertools.imap is just like map(), but stops as soon as the shortest iterable stops.

itertools.imap(maptest, foos, itertools.repeat(bars))

Hope this helps :-)

(*) It's a little different in python 3.0. There, map() essentially returns a generator expression.

No tests found with test runner 'JUnit 4'

This happened to me too. I found that in Eclipse I didn't make a new Java Class file and so that's why it wasn't compiling. Try copying your code into a java class file if it's not already there and then compile.

Mocking python function based on input arguments

You can also use partial from functools if you want to use a function that takes parameters but the function you are mocking does not. E.g. like this:

def mock_year(year):
    return datetime.datetime(year, 11, 28, tzinfo=timezone.utc)
@patch('django.utils.timezone.now', side_effect=partial(mock_year, year=2020))

This will return a callable that doesn't accept parameters (like Django's timezone.now()), but my mock_year function does.

PowerShell Script to Find and Replace for all Files with a Specific Extension

I have written a little helper function to replace text in a file:

function Replace-TextInFile
{
    Param(
        [string]$FilePath,
        [string]$Pattern,
        [string]$Replacement
    )

    [System.IO.File]::WriteAllText(
        $FilePath,
        ([System.IO.File]::ReadAllText($FilePath) -replace $Pattern, $Replacement)
    )
}

Example:

Get-ChildItem . *.config -rec | ForEach-Object { 
    Replace-TextInFile -FilePath $_ -Pattern 'old' -Replacement 'new' 
}

How do I copy a 2 Dimensional array in Java?

public  static byte[][] arrayCopy(byte[][] arr){
    if(arr!=null){
        int[][] arrCopy = new int[arr.length][] ;
        System.arraycopy(arr, 0, arrCopy, 0, arr.length);
        return arrCopy;
    }else { return new int[][]{};}
}

Load an image from a url into a PictureBox

Try this:

var request = WebRequest.Create("http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG");

using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
    pictureBox1.Image = Bitmap.FromStream(stream);
}

Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat

Got the solution and it's working fine. Set the environment variables as:

  • CATALINA_HOME=C:\Program Files\Java\apache-tomcat-7.0.59\apache-tomcat-7.0.59 (path where your Apache Tomcat is)
  • JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25; (path where your JDK is)
  • JRE_Home=C:\Program Files\Java\jre1.8.0_25; (path where your JRE is)
  • CLASSPATH=%JAVA_HOME%\bin;%JRE_HOME%\bin;%CATALINA_HOME%\lib

Border Height on CSS

table {
 border-spacing: 10px 0px;
}

.rightborder {
border-right: 1px solid #fff;
}

Then with your code you can:

<td class="rightborder">whatever</td>

Hope that helps!

GitHub: invalid username or password

I did:

$git pull origin master

Then it asked for the [Username] & [Password] and it seems to be working fine now.

Bootstrap 3 - jumbotron background image effect

After inspecting the sample website you provided, I found that the author might achieve the effect by using a library called Stellar.js, take a look at the library site, cheers!

How to rename uploaded file before saving it into a directory?

You can simply change the name of the file by changing the name of the file in the second parameter of move_uploaded_file.

Instead of

move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $_FILES["file"]["name"]);

Use

$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);

Changed to reflect your question, will product a random number based on the current time and append the extension from the originally uploaded file.

Changing case in Vim

Visual select the text, then U for uppercase or u for lowercase. To swap all casing in a visual selection, press ~ (tilde).

Without using a visual selection, gU<motion> will make the characters in motion uppercase, or use gu<motion> for lowercase.

For more of these, see Section 3 in Vim's change.txt help file.

push_back vs emplace_back

Optimization for emplace_back can be demonstrated in next example.

For emplace_back constructor A (int x_arg) will be called. And for push_back A (int x_arg) is called first and move A (A &&rhs) is called afterwards.

Of course, the constructor has to be marked as explicit, but for current example is good to remove explicitness.

#include <iostream>
#include <vector>
class A
{
public:
  A (int x_arg) : x (x_arg) { std::cout << "A (x_arg)\n"; }
  A () { x = 0; std::cout << "A ()\n"; }
  A (const A &rhs) noexcept { x = rhs.x; std::cout << "A (A &)\n"; }
  A (A &&rhs) noexcept { x = rhs.x; std::cout << "A (A &&)\n"; }

private:
  int x;
};

int main ()
{
  {
    std::vector<A> a;
    std::cout << "call emplace_back:\n";
    a.emplace_back (0);
  }
  {
    std::vector<A> a;
    std::cout << "call push_back:\n";
    a.push_back (1);
  }
  return 0;
}

output:

call emplace_back:
A (x_arg)

call push_back:
A (x_arg)
A (A &&)

Angular 1.6.0: "Possibly unhandled rejection" error

I was also facing the same issue after updating to Angular 1.6.7 but when I looked into the code, error was thrown for $interval.cancel(interval); for my case

My issue got resolved once I updated angular-mocks to latest version(1.7.0).

How to prevent Browser cache on Angular 2 site?

Found a way to do this, simply add a querystring to load your components, like so:

@Component({
  selector: 'some-component',
  templateUrl: `./app/component/stuff/component.html?v=${new Date().getTime()}`,
  styleUrls: [`./app/component/stuff/component.css?v=${new Date().getTime()}`]
})

This should force the client to load the server's copy of the template instead of the browser's. If you would like it to refresh only after a certain period of time you could use this ISOString instead:

new Date().toISOString() //2016-09-24T00:43:21.584Z

And substring some characters so that it will only change after an hour for example:

new Date().toISOString().substr(0,13) //2016-09-24T00

Hope this helps

Sort hash by key, return hash in Ruby

No, it is not (Ruby 1.9.x)

require 'benchmark'

h = {"a"=>1, "c"=>3, "b"=>2, "d"=>4}
many = 100_000

Benchmark.bm do |b|
  GC.start

  b.report("hash sort") do
    many.times do
      Hash[h.sort]
    end
  end

  GC.start

  b.report("keys sort") do
    many.times do
      nh = {}
      h.keys.sort.each do |k|
        nh[k] = h[k]
      end
    end
  end
end

       user     system      total        real
hash sort  0.400000   0.000000   0.400000 (  0.405588)
keys sort  0.250000   0.010000   0.260000 (  0.260303)

For big hashes difference will grow up to 10x and more

Post an object as data using Jquery Ajax

All arrays passed to php must be object literals. Here's an example from JS/jQuery:

var myarray = {};  //must be declared as an object literal first

myarray[fld1] = val;  // then you can add elements and values
myarray[fld2] = val;
myarray[fld3] = Array();  // array assigned to an element must also be declared as object literal

etc...`

It can now be sent via Ajax in the data: parameter as follows:

data: { new_name: myarray },

php picks this up and reads it as a normal array without any decoding necessary. Here's an example:

$array = $_POST['new_name'];  // myarray became new_name (see above)
$fld1 = array['fld1'];
$fld2 = array['fld2'];
etc...

However, when you return an array to jQuery via Ajax it must first be encoded using json. Here's an example in php:

$return_array = json_encode($return_aray));
print_r($return_array);

And the output from that looks something like this:

{"fname":"James","lname":"Feducia","vip":"true","owner":"false","cell_phone":"(801) 666-0909","email":"[email protected]", "contact_pk":"","travel_agent":""}

{again we see the object literal encoding tags} now this can be read by JS/jQuery as an array without any further action inside JS/JQuery... Here's an example in jquery ajax:

success: function(result) {
console.log(result);
alert( "Return Values: " + result['fname'] + " " + result['lname'] );
}

What is the best collation to use for MySQL with PHP?

Actually, you probably want to use utf8_unicode_ci or utf8_general_ci.

  • utf8_general_ci sorts by stripping away all accents and sorting as if it were ASCII
  • utf8_unicode_ci uses the Unicode sort order, so it sorts correctly in more languages

However, if you are only using this to store English text, these shouldn't differ.

Count number of tables in Oracle

If you'd like a list of owners, and the count of the number of tables per owner, try:

    SELECT distinct owner, count(table_name) FROM dba_tables GROUP BY owner;

Using ConfigurationManager to load config from an arbitrary location

This should do the trick :

AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", "newAppConfig.config);

Source : https://www.codeproject.com/Articles/616065/Why-Where-and-How-of-NET-Configuration-Files

Convert timestamp to string

new Date().toString();

http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/

Dateformatter can make it to any string you want

Matlab: Running an m-file from command-line

On Linux you can do the same and you can actually send back to the shell a custom error code, like the following:

#!/bin/bash
matlab -nodisplay -nojvm -nosplash -nodesktop -r \ 
      "try, run('/foo/bar/my_script.m'), catch, exit(1), end, exit(0);"
echo "matlab exit code: $?"

it prints matlab exit code: 1 if the script throws an exception, matlab exit code: 0 otherwise.

Extract XML Value in bash script

I agree with Charles Duffy that a proper XML parser is the right way to go.

But as to what's wrong with your sed command (or did you do it on purpose?).

  • $data was not quoted, so $data is subject to shell's word splitting, filename expansion among other things. One of the consequences being that the spacing in the XML snippet is not preserved.

So given your specific XML structure, this modified sed command should work

title=$(sed -ne '/title/{s/.*<title>\(.*\)<\/title>.*/\1/p;q;}' <<< "$data")

Basically for the line that contains title, extract the text between the tags, then quit (so you don't extract the 2nd <title>)

How to format column to number format in Excel sheet?

This will format column A as text, B as General, C as a number.

Sub formatColumns()
 Columns(1).NumberFormat = "@"
 Columns(2).NumberFormat = "General"
 Columns(3).NumberFormat = "0"
End Sub

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`

Add a prop 'key' to the rendering root component of the list.

<ScrollView>
      <List>
          {this.state.nationalities.map((prop, key) => {
             return (
               <ListItem key={key}>
                  <Text>{prop.name}</Text>
               </ListItem>
             );
          })}
      </List>
</ScrollView>

How to make space between LinearLayout children?

Using padding in the layout of Child View.

layout.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_margin="5dp"
          android:background="@drawable/backage_text"
          android:textColor="#999999"
           >

</TextView>

backage_text.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="@color/white"/>
    <corners android:radius="2dp"/>
    <stroke
        android:width="1dp"
        android:color="#999999"/>
    <padding
        android:bottom="5dp"
        android:left="10dp"
        android:right="10dp"
        android:top="5dp" />
</shape>

Foreach loop in C++ equivalent of C#

After getting used to the var keyword in C#, I'm starting to use the auto keyword in C++11. They both determine type by inference and are useful when you just want the compiler to figure out the type for you. Here's the C++11 port of your code:

#include <array>
#include <string>

using namespace std;

array<string, 3> strarr = {"ram", "mohan", "sita"};
for(auto str: strarr) {
  listbox.items.add(str);
}

Tools: replace not replacing in Android manifest

I also went through this problem and changed that:

<application  android:debuggable="true" android:icon="@drawable/app_icon" android:label="@string/app_name" android:supportsRtl="true" android:allowBackup="false" android:fullBackupOnly="false" android:theme="@style/UnityThemeSelector">

to

 <application tools:replace="android:allowBackup" android:debuggable="true" android:icon="@drawable/app_icon" android:label="@string/app_name" android:supportsRtl="true" android:allowBackup="false" android:fullBackupOnly="false" android:theme="@style/UnityThemeSelector">

GridLayout and Row/Column Span Woe

You have to set both layout_gravity and layout_columntWeight on your columns

<android.support.v7.widget.GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView android:text="??? ???"
        app:layout_gravity="fill_horizontal"
        app:layout_columnWeight="1"
        />

    <TextView android:text="??? ???"
        app:layout_gravity="fill_horizontal"
        app:layout_columnWeight="1"
        />

    <TextView android:text="??? ???"
        app:layout_gravity="fill_horizontal"
        app:layout_columnWeight="1"
        />
 </android.support.v7.widget.GridLayout>

Call a url from javascript

var req ;

// Browser compatibility check          
if (window.XMLHttpRequest) {
   req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {

 try {
   req = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {

   try {
     req = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (e) {}
 }

}


var req = new XMLHttpRequest();
req.open("GET", "test.html",true);
req.onreadystatechange = function () {
    //document.getElementById('divTxt').innerHTML = "Contents : " + req.responseText;
}

req.send(null);

How do I convert two lists into a dictionary?

A more natural way is to use dictionary comprehension

keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')    
dict = {keys[i]: values[i] for i in range(len(keys))}

Parse JSON response using jQuery

Original question was to parse a list of topics, however starting with the original example to have a function return a single value may also useful. To that end, here is an example of (one way) to do that:

<script type='text/javascript'>
    function getSingleValueUsingJQuery() {
      var value = "";
      var url = "rest/endpointName/" + document.getElementById('someJSPFieldName').value;
      jQuery.ajax({
        type: 'GET',
        url: url,
        async: false,
        contentType: "application/json",
        dataType: 'json',
        success: function(json) {
          console.log(json.value);   // needs to match the payload (i.e. json must have {value: "foo"}
          value = json.value;
        },
        error: function(e) {
          console.log("jQuery error message = "+e.message);
        }
      });
      return value;
    }
    </script>
    

nginx: send all requests to a single html page

This worked for me:

location / {
    try_files $uri $uri/ /base.html;
}

json_encode sparse PHP array as JSON array, not JSON object

Try this,

<?php
$arr1=array('result1'=>'abcd','result2'=>'efg'); 
$arr2=array('result1'=>'hijk','result2'=>'lmn'); 
$arr3=array($arr1,$arr2); 
print (json_encode($arr3)); 
?>

What is the difference between concurrent programming and parallel programming?

Parallel programming happens when code is being executed at the same time and each execution is independent of the other. Therefore, there is usually not a preoccupation about shared variables and such because that won't likely happen.

However, concurrent programming consists on code being executed by different processes/threads that share variables and such, therefore on concurrent programming we must establish some sort of rule to decide which process/thread executes first, we want this so that we can be sure there will be consistency and that we can know with certainty what will happen. If there is no control and all threads compute at the same time and store things on the same variables, how would we know what to expect in the end? Maybe a thread is faster than the other, maybe one of the threads even stopped in the middle of its execution and another continued a different computation with a corrupted (not yet fully computed) variable, the possibilities are endless. It's in these situations that we usually use concurrent programming instead of parallel.