Programs & Examples On #Input parameters

Type datetime for input parameter in procedure

You should use the ISO-8601 format for string representations of dates - anything else is dependent on the SQL Server language and dateformat settings.

The ISO-8601 format for a DATETIME when using only the date is: YYYYMMDD (no dashes or antyhing!)

For a DATETIME with the time portion, it's YYYY-MM-DDTHH:MM:SS (with dashes, and a T in the middle to separate date and time portions).

If you want to convert a string to a DATE for SQL Server 2008 or newer, you can use YYYY-MM-DD (with the dashes) to achieve the same result. And don't ask me why this is so inconsistent and confusing - it just is, and you'll have to work with that for now.

So in your case, you should try:

declare @a datetime
declare @b datetime 

set @a = '2012-04-06T12:23:45'   -- 6th of April, 2012
set @b = '2012-08-06T21:10:12'   -- 6th of August, 2012

exec LogProcedure 'AccountLog', N'test', @a, @b

Furthermore - your stored proc has problem, since you're concatenating together datetime and string into a string, but you're not converting the datetime to string first, and also, you're forgetting the close quotes in your statement after both dates.

So change this line here to this:

IF @DateFirst <> '' and @DateLast <> ''
   SET @FinalSQL  = @FinalSQL + '  OR CONVERT(Date, DateLog) >= ''' + 
                    CONVERT(VARCHAR(50), @DateFirst, 126) +   -- convert @DateFirst to string for concatenation!
                    ''' AND CONVERT(Date, DateLog) <=''' +  -- you need closing quotes after @DateFirst!
                    CONVERT(VARCHAR(50), @DateLast, 126) + ''''      -- convert @DateLast to string and also: closing tags after that missing!

With these settings, and once you've fixed your stored procedure which contains problems right now, it will work.

Maven – Always download sources and javadocs

For the sources on dependency level ( pom.xml) you can add :

<classifier>sources</classifier>

How to simulate key presses or a click with JavaScript?

For simulating keyboard events in Chrome:

There is a related bug in webkit that keyboard events when initialized with initKeyboardEvent get an incorrect keyCode and charCode of 0: https://bugs.webkit.org/show_bug.cgi?id=16735

A working solution for it is posted in this SO answer.

Setting different color for each series in scatter plot on matplotlib

An easy fix

If you have only one type of collections (e.g. scatter with no error bars) you can also change the colours after that you have plotted them, this sometimes is easier to perform.

import matplotlib.pyplot as plt
from random import randint
import numpy as np

#Let's generate some random X, Y data X = [ [frst group],[second group] ...]
X = [ [randint(0,50) for i in range(0,5)] for i in range(0,24)]
Y = [ [randint(0,50) for i in range(0,5)] for i in range(0,24)]
labels = range(1,len(X)+1)

fig = plt.figure()
ax = fig.add_subplot(111)
for x,y,lab in zip(X,Y,labels):
        ax.scatter(x,y,label=lab)

The only piece of code that you need:

#Now this is actually the code that you need, an easy fix your colors just cut and paste not you need ax.
colormap = plt.cm.gist_ncar #nipy_spectral, Set1,Paired  
colorst = [colormap(i) for i in np.linspace(0, 0.9,len(ax.collections))]       
for t,j1 in enumerate(ax.collections):
    j1.set_color(colorst[t])


ax.legend(fontsize='small')

The output gives you differnent colors even when you have many different scatter plots in the same subplot.

enter image description here

Django database query: How to get object by id?

I got here for the same problem, but for a different reason:

Class.objects.get(id=1)

This code was raising an ImportError exception. What was confusing me was that the code below executed fine and returned a result set as expected:

Class.objects.all()

Tail of the traceback for the get() method:

File "django/db/models/loading.py", line 197, in get_models
    self._populate()
File "django/db/models/loading.py", line 72, in _populate
    self.load_app(app_name, True)
File "django/db/models/loading.py", line 94, in load_app
    app_module = import_module(app_name)
File "django/utils/importlib.py", line 35, in import_module
    __import__(name)
ImportError: No module named myapp

Reading the code inside Django's loading.py, I came to the conclusion that my settings.py had a bad path to my app which contains my Class model definition. All I had to do was correct the path to the app and the get() method executed fine.

Here is my settings.py with the corrected path:

INSTALLED_APPS = (
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    # ...
    'mywebproject.myapp',

)

All the confusion was caused because I am using Django's ORM as a standalone, so the namespace had to reflect that.

How to calculate moving average without keeping the count and data-total?

From a blog on running sample variance calculations, where the mean is also calculated using Welford's method:

enter image description here

Too bad we can't upload SVG images.

How to cast DATETIME as a DATE in mysql?

Use DATE() function:

select * from follow_queue group by DATE(follow_date)

How do I sort a two-dimensional (rectangular) array in C#?

I know its late but here is my thought you might wanna consider.

for example this is array

{
m,m,m
a,a,a
b,b,b
j,j,j
k,l,m
}

and you want to convert it by column number 2, then

string[] newArr = new string[arr.length]
for(int a=0;a<arr.length;a++)
    newArr[a] = arr[a][1] + a;

// create new array that contains index number at the end and also the column values
Array.Sort(newArr);
for(int a=0;a<newArr.length;a++)
{
    int index = Convert.ToInt32(newArr[a][newArr[a].Length -1]);
    //swap whole row with tow at current index
    if(index != a)
    {
        string[] arr2 = arr[a];
        arr[a] = arr[index];
        arr[index] = arr2;
    }
}

Congratulations you have sorted the array by desired column. You can edit this to make it work with other data types

What is the "right" JSON date format?

The following code has worked for me. This code will print date in DD-MM-YYYY format.

DateValue=DateValue.substring(6,8)+"-"+DateValue.substring(4,6)+"-"+DateValue.substring(0,4);

else, you can also use:

DateValue=DateValue.substring(0,4)+"-"+DateValue.substring(4,6)+"-"+DateValue.substring(6,8);

Difference between "\n" and Environment.NewLine

From the docs ...

A string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms.

How can I get a list of locally installed Python modules?

There are many ideas, initially I am pondering on these two:

pip

cons: not always installed

help('modules')

cons: output to console; with broken modules (see ubuntu...) can segfault

I need an easy approach, using basic libraries and compatible with old python 2.x

And I see the light: listmodules.py

Hidden in the documentation source directory in 2.5 is a small script that lists all available modules for a Python installation.

Pros:

uses only imp, sys, os, re, time

designed to run on Python 1.5.2 and newer

the source code is really compact, so you can easy tinkering with it, for example to pass an exception list of buggy modules (don't try to import them)

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

@JoinColumn could be used on both sides of the relationship. The question was about using @JoinColumn on the @OneToMany side (rare case). And the point here is in physical information duplication (column name) along with not optimized SQL query that will produce some additional UPDATE statements.

According to documentation:

Since many to one are (almost) always the owner side of a bidirectional relationship in the JPA spec, the one to many association is annotated by @OneToMany(mappedBy=...)

@Entity
public class Troop {
    @OneToMany(mappedBy="troop")
    public Set<Soldier> getSoldiers() {
    ...
}

@Entity
public class Soldier {
    @ManyToOne
    @JoinColumn(name="troop_fk")
    public Troop getTroop() {
    ...
} 

Troop has a bidirectional one to many relationship with Soldier through the troop property. You don't have to (must not) define any physical mapping in the mappedBy side.

To map a bidirectional one to many, with the one-to-many side as the owning side, you have to remove the mappedBy element and set the many to one @JoinColumn as insertable and updatable to false. This solution is not optimized and will produce some additional UPDATE statements.

@Entity
public class Troop {
    @OneToMany
    @JoinColumn(name="troop_fk") //we need to duplicate the physical information
    public Set<Soldier> getSoldiers() {
    ...
}

@Entity
public class Soldier {
    @ManyToOne
    @JoinColumn(name="troop_fk", insertable=false, updatable=false)
    public Troop getTroop() {
    ...
}

How to pop an alert message box using PHP?

See this example :

<?php
echo "<div id='div1'>text</div>"
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="js/jquery1.3.2/jquery.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {
            $('#div1').click(function () {
                alert('I clicked');
            });
        });
</script>
</head>
<body>

</body>
</html>

Format numbers in django templates

If you don't want to get involved with locales here is a function that formats numbers:

def int_format(value, decimal_points=3, seperator=u'.'):
    value = str(value)
    if len(value) <= decimal_points:
        return value
    # say here we have value = '12345' and the default params above
    parts = []
    while value:
        parts.append(value[-decimal_points:])
        value = value[:-decimal_points]
    # now we should have parts = ['345', '12']
    parts.reverse()
    # and the return value should be u'12.345'
    return seperator.join(parts)

Creating a custom template filter from this function is trivial.

Actual meaning of 'shell=True' in subprocess

The benefit of not calling via the shell is that you are not invoking a 'mystery program.' On POSIX, the environment variable SHELL controls which binary is invoked as the "shell." On Windows, there is no bourne shell descendent, only cmd.exe.

So invoking the shell invokes a program of the user's choosing and is platform-dependent. Generally speaking, avoid invocations via the shell.

Invoking via the shell does allow you to expand environment variables and file globs according to the shell's usual mechanism. On POSIX systems, the shell expands file globs to a list of files. On Windows, a file glob (e.g., "*.*") is not expanded by the shell, anyway (but environment variables on a command line are expanded by cmd.exe).

If you think you want environment variable expansions and file globs, research the ILS attacks of 1992-ish on network services which performed subprogram invocations via the shell. Examples include the various sendmail backdoors involving ILS.

In summary, use shell=False.

Python MYSQL update statement

@Esteban Küber is absolutely right.

Maybe one additional hint for bloody beginners like me. If you speciify the variables with %s, you have to follow this principle for EVERY input value, which means for the SET-variables as well as for the WHERE-variables.

Otherwise, you will have to face a termination message like 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s WHERE'

HTML Tags in Javascript Alert() method

alert() doesn't support HTML, but you have some alternatives to format your message.

You can use Unicode characters as others stated, or you can make use of the ES6 Template literals. For example:

...
.catch(function (error) {
  const alertMessage = `Error retrieving resource. Please make sure:
    • the resource server is accessible
    • you're logged in

    Error: ${error}`;
  window.alert(alertMessage);
}

Output: enter image description here

As you can see, it maintains the line breaks and spaces that we included in the variable, with no extra characters.

Insert NULL value into INT column

If column is not NOT NULL (nullable).

You just put NULL instead of value in INSERT statement.

SQL Case Sensitive String Compare

You Can easily Convert columns to VARBINARY(Max Length), The length must be the maximum you expect to avoid defective comparison, It's enough to set length as the column length. Trim column help you to compare the real value except space has a meaning and valued in your table columns, This is a simple sample and as you can see I Trim the columns value and then convert and compare.:

CONVERT(VARBINARY(250),LTRIM(RTRIM(Column1))) = CONVERT(VARBINARY(250),LTRIM(RTRIM(Column2)))

Hope this help.

How to detect orientation change?

For Swift 3

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    if UIDevice.current.orientation.isLandscape {
        //Landscape
    }
    else if UIDevice.current.orientation.isFlat {
        //isFlat
    }
    else {
        //Portrait
    }
}

Writing a dict to txt file and reading it back?

Your code is almost right! You are right, you are just missing one step. When you read in the file, you are reading it as a string; but you want to turn the string back into a dictionary.

The error message you saw was because self.whip was a string, not a dictionary.

I first wrote that you could just feed the string into dict() but that doesn't work! You need to do something else.

Example

Here is the simplest way: feed the string into eval(). Like so:

def reading(self):
    s = open('deed.txt', 'r').read()
    self.whip = eval(s)

You can do it in one line, but I think it looks messy this way:

def reading(self):
    self.whip = eval(open('deed.txt', 'r').read())

But eval() is sometimes not recommended. The problem is that eval() will evaluate any string, and if someone tricked you into running a really tricky string, something bad might happen. In this case, you are just running eval() on your own file, so it should be okay.

But because eval() is useful, someone made an alternative to it that is safer. This is called literal_eval and you get it from a Python module called ast.

import ast

def reading(self):
    s = open('deed.txt', 'r').read()
    self.whip = ast.literal_eval(s)

ast.literal_eval() will only evaluate strings that turn into the basic Python types, so there is no way that a tricky string can do something bad on your computer.

EDIT

Actually, best practice in Python is to use a with statement to make sure the file gets properly closed. Rewriting the above to use a with statement:

import ast

def reading(self):
    with open('deed.txt', 'r') as f:
        s = f.read()
        self.whip = ast.literal_eval(s)

In the most popular Python, known as "CPython", you usually don't need the with statement as the built-in "garbage collection" features will figure out that you are done with the file and will close it for you. But other Python implementations, like "Jython" (Python for the Java VM) or "PyPy" (a really cool experimental system with just-in-time code optimization) might not figure out to close the file for you. It's good to get in the habit of using with, and I think it makes the code pretty easy to understand.

Is there a "not equal" operator in Python?

You can use both != or <>.

However, note that != is preferred where <> is deprecated.

How to use a Bootstrap 3 glyphicon in an html select

I ended up using the bootstrap 3 dropdown button, I'm posting my solution here in case it helps someone in future. Adding the bootstrap 3 list-inline to the class for the ul causes it to display in a nicely compact format as well.

<div class="btn-group">
    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
        Select icon <span class="caret"></span>
    </button>
    <ul class="dropdown-menu list-inline" role="menu">
        <li><span class="glyphicon glyphicon-cutlery"></span></li>
        <li><span class="glyphicon glyphicon-fire"></span></li>
        <li><span class="glyphicon glyphicon-glass"></span></li>
        <li><span class="glyphicon glyphicon-heart"></span></li>          
    </ul>
</div>

I'm using Angular.js so this is the actual code I used:

<div class="btn-group">
            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                Avatar <span class="caret"></span>
            </button>
            <ul class="dropdown-menu list-inline" role="menu">
                <li ng-repeat="avatar in avatars" ng-click="avatarSelected(avatar)">
                    <span ng-class="getAvatar(avatar)"></span>
                </li>
            </ul>
        </div>

And in my controller:

$scope.avatars=['cutlery','eye-open','flag','flash','glass','fire','hand-right','heart','heart-empty','leaf','music','send','star','star-empty','tint','tower','tree-conifer','tree-deciduous','usd','user','wrench','time','road','cloud'];

$scope.getAvatar=function(avatar){
     return 'glyphicon glyphicon-'+avatar;
};

Update elements in a JSONObject

Hello I can suggest you universal method. use recursion.

    public static JSONObject function(JSONObject obj, String keyMain,String valueMain, String newValue) throws Exception {
    // We need to know keys of Jsonobject
    JSONObject json = new JSONObject()
    Iterator iterator = obj.keys();
    String key = null;
    while (iterator.hasNext()) {
        key = (String) iterator.next();
        // if object is just string we change value in key
        if ((obj.optJSONArray(key)==null) && (obj.optJSONObject(key)==null)) {
            if ((key.equals(keyMain)) && (obj.get(key).toString().equals(valueMain))) {
                // put new value
                obj.put(key, newValue);
                return obj;
            }
        }

        // if it's jsonobject
        if (obj.optJSONObject(key) != null) {
            function(obj.getJSONObject(key), keyMain, valueMain, newValue);
        }

        // if it's jsonarray
        if (obj.optJSONArray(key) != null) {
            JSONArray jArray = obj.getJSONArray(key);
            for (int i=0;i<jArray.length();i++) {
                    function(jArray.getJSONObject(i), keyMain, valueMain, newValue);
            }
        }
    }
    return obj;
}

It should work. If you have questions, go ahead.. I'm ready.

Highlight Anchor Links when user manually scrolls?

You can use Jquery's on method and listen for the scroll event.

What is the difference between a 'closure' and a 'lambda'?

Not all closures are lambdas and not all lambdas are closures. Both are functions, but not necessarily in the manner we're used to knowing.

A lambda is essentially a function that is defined inline rather than the standard method of declaring functions. Lambdas can frequently be passed around as objects.

A closure is a function that encloses its surrounding state by referencing fields external to its body. The enclosed state remains across invocations of the closure.

In an object-oriented language, closures are normally provided through objects. However, some OO languages (e.g. C#) implement special functionality that is closer to the definition of closures provided by purely functional languages (such as lisp) that do not have objects to enclose state.

What's interesting is that the introduction of Lambdas and Closures in C# brings functional programming closer to mainstream usage.

Create new project on Android, Error: Studio Unknown host 'services.gradle.org'

I tried above answers and they didn't help in my case.

I solved it with this link help: http://vjscrazzy.blogspot.co.il/2016/02/failed-to-sync-gradle-project.html

step 1) file>Setttings>appearance and behaviour> system setttings>HTTP proxy> set No Proxy

step 2) build,execution and deployment> Build tools > gradle> now under project level settings > select local gradle distribution> gradle home = F:/Program Files/Android/Android Studio/gradle/gradle-2.4

After that, I did these changes(because it still wrote me some other errors)

Android Studio asked me:

  1. Android Studio asked me to update my Gradle version (which he didn't before)

  2. Enable - Tools> Android> Enable ADB integration.

Also, if your working in a team with repositories, it's important to check that the version of the Andorid Studio is the same.

get list of pandas dataframe columns based on data type

The most direct way to get a list of columns of certain dtype e.g. 'object':

df.select_dtypes(include='object').columns

For example:

>>df = pd.DataFrame([[1, 2.3456, 'c', 'd', 78]], columns=list("ABCDE"))
>>df.dtypes

A      int64
B    float64
C     object
D     object
E      int64
dtype: object

To get all 'object' dtype columns:

>>df.select_dtypes(include='object').columns

Index(['C', 'D'], dtype='object')

For just the list:

>>list(df.select_dtypes(include='object').columns)

['C', 'D']   

How to install pip in CentOS 7?

curl https://bootstrap.pypa.io/get-pip.py | python3.4

Or if you don't have curl for some reason:

wget https://bootstrap.pypa.io/get-pip.py
python3.4 get-pip.py

After this you should be able to run

$ pip3

Make div stay at bottom of page's content all the time even when there are scrollbars

You didn't close your ; after position: absolute. Otherwise your above code would have worked perfectly!

#footer {
   position:absolute;
   bottom:30px;
   width:100%;
}

Removing index column in pandas when reading a csv

One thing that i do is df=df.reset_index() then df=df.drop(['index'],axis=1)

What does "exec sp_reset_connection" mean in Sql Server Profiler?

Note however:

If you issue SET TRANSACTION ISOLATION LEVEL in a stored procedure or trigger, when the object returns control the isolation level is reset to the level in effect when the object was invoked. For example, if you set REPEATABLE READ in a batch, and the batch then calls a stored procedure that sets the isolation level to SERIALIZABLE, the isolation level setting reverts to REPEATABLE READ when the stored procedure returns control to the batch.

http://msdn.microsoft.com/en-us/library/ms173763.aspx

How to copy a file along with directory structure/path using python?

take a look at shutil. shutil.copyfile(src, dst) will copy a file to another file.

Note that shutil.copyfile will not create directories that do not already exist. for that, use os.makedirs

How to change current working directory using a batch file

A simpler syntax might be

pushd %root%

YAML Multi-Line Arrays

have you tried this?

-
  name: Jack
  age: 32
-
  name: Claudia
  age: 25

I get this: [{"name"=>"Jack", "age"=>32}, {"name"=>"Claudia", "age"=>25}] (I use the YAML Ruby class).

Set encoding and fileencoding to utf-8 in Vim

set encoding=utf-8  " The encoding displayed.
set fileencoding=utf-8  " The encoding written to file.

You may as well set both in your ~/.vimrc if you always want to work with utf-8.

Returning string from C function

I came across this thread while working on my understanding of Cython. My extension to the original question might be of use to others working at the C / Cython interface. So this is the extension of the original question: how do I return a string from a C function, making it available to Cython & thus to Python?

For those not familiar with it, Cython allows you to statically type Python code that you need to speed up. So the process is, enjoy writing Python :), find its a bit slow somewhere, profile it, calve off a function or two and cythonize them. Wow. Close to C speed (it compiles to C) Fixed. Yay. The other use is importing C functions or libraries into Python as done here.

This will print a string and return the same or another string to Python. There are 3 files, the c file c_hello.c, the cython file sayhello.pyx, and the cython setup file sayhello.pyx. When they are compiled using python setup.py build_ext --inplace they generate a shared library file that can be imported into python or ipython and the function sayhello.hello run.

c_hello.c

#include <stdio.h>

char *c_hello() {
  char *mystr = "Hello World!\n";
  return mystr;
  // return "this string";  // alterative
}

sayhello.pyx

cdef extern from "c_hello.c":
    cdef char* c_hello()

def hello():
    return c_hello()

setup.py

from setuptools import setup
from setuptools.extension import Extension
from Cython.Distutils import build_ext
from Cython.Build import cythonize


ext_modules = cythonize([Extension("sayhello", ["sayhello.pyx"])])


setup(
name = 'Hello world app',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)

Create line after text with css

This is the most easy way I found to achieve the result: Just use hr tag before the text, and set the margin top for text. Very short and easy to understand! jsfiddle

_x000D_
_x000D_
h2 {_x000D_
  background-color: #ffffff;_x000D_
  margin-top: -22px;_x000D_
  width: 25%;_x000D_
}_x000D_
_x000D_
hr {_x000D_
  border: 1px solid #e9a216;_x000D_
}
_x000D_
<br>_x000D_
_x000D_
<hr>_x000D_
<h2>ABOUT US</h2>
_x000D_
_x000D_
_x000D_

What is the purpose of nameof?

Another use-case where nameof feature of C# 6.0 becomes handy - Consider a library like Dapper which makes DB retrievals much easier. Albeit this is a great library, you need to hardcode property/field names within query. What this means is that if you decide to rename your property/field, there are high chances that you will forget to update query to use new field names. With string interpolation and nameof features, code becomes much easier to maintain and typesafe.

From the example given in link

without nameof

var dog = connection.Query<Dog>("select Age = @Age, Id = @Id", new { Age = (int?)null, Id = guid });

with nameof

var dog = connection.Query<Dog>($"select {nameof(Dog.Age)} = @Age, {nameof(Dog.Id)} = @Id", new { Age = (int?)null, Id = guid });

Regular expression to match any character being repeated more than 10 times

On some apps you need to remove the slashes to make it work.

/(.)\1{9,}/

or this:

(.)\1{9,}

IE7 Z-Index Layering Issues

This bug seems to be somewhat of a separate issue than the standard separate stacking context IE bug. I had a similar issue with multiple stacked inputs (essentially a table with an autocompleter in each row). The only solution I found was to give each cell a decreasing z-index value.

Set a persistent environment variable from cmd.exe

Indeed SET TEST_VARIABLE=value works for current process only, so SETX is required. A quick example for permanently storing an environment variable at user level.

  1. In cmd, SETX TEST_VARIABLE etc. Not applied yet (echo %TEST_VARIABLE% shows %TEST_VARIABLE%,
  2. Quick check: open cmd, echo %TEST_VARIABLE% shows etc.
  3. GUI check: System Properties -> Advanced -> Environment variables -> User variables for -> you should see Varible TEST_VARIABLE with value etc.

add commas to a number in jQuery

Number(10000).toLocaleString('en');  // "10,000"

Calling a rest api with username and password - how to

Here is the solution for Rest API

class Program
{
    static void Main(string[] args)
    {
        BaseClient clientbase = new BaseClient("https://website.com/api/v2/", "username", "password");
        BaseResponse response = new BaseResponse();
        BaseResponse response = clientbase.GetCallV2Async("Candidate").Result;
    }


    public async Task<BaseResponse> GetCallAsync(string endpoint)
    {
        try
        {
            HttpResponseMessage response = await client.GetAsync(endpoint + "/").ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            else
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            return baseresponse;
        }
        catch (Exception ex)
        {
            baseresponse.StatusCode = 0;
            baseresponse.ResponseMessage = (ex.Message ?? ex.InnerException.ToString());
        }
        return baseresponse;
    }
}


public class BaseResponse
{
    public int StatusCode { get; set; }
    public string ResponseMessage { get; set; }
}

public class BaseClient
{
    readonly HttpClient client;
    readonly BaseResponse baseresponse;

    public BaseClient(string baseAddress, string username, string password)
    {
        HttpClientHandler handler = new HttpClientHandler()
        {
            Proxy = new WebProxy("http://127.0.0.1:8888"),
            UseProxy = false,
        };

        client = new HttpClient(handler);
        client.BaseAddress = new Uri(baseAddress);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);

        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

        baseresponse = new BaseResponse();

    }
}

Appropriate datatype for holding percent values?

I agree with Thomas and I would choose the DECIMAL(5,4) solution at least for WPF applications.

Have a look to the MSDN Numeric Format String to know why : http://msdn.microsoft.com/en-us/library/dwhawy9k#PFormatString

The percent ("P") format specifier multiplies a number by 100 and converts it to a string that represents a percentage.

Then you would be able to use this in your XAML code:

DataFormatString="{}{0:P}"

SQL Insert Multiple Rows

We will import the CSV file into the destination table in the simplest form. I placed my sample CSV file on the C: drive and now we will create a table which we will import data from the CSV file.

DROP TABLE IF EXISTS Sales 

CREATE TABLE [dbo].[Sales](
    [Region] [varchar](50) ,
    [Country] [varchar](50) ,
    [ItemType] [varchar](50) NULL,
    [SalesChannel] [varchar](50) NULL,
    [OrderPriority] [varchar](50) NULL,
    [OrderDate]  datetime,
    [OrderID] bigint NULL,
    [ShipDate] datetime,
    [UnitsSold]  float,
    [UnitPrice] float,
    [UnitCost] float,
    [TotalRevenue] float,
    [TotalCost]  float,
    [TotalProfit] float
)

The following BULK INSERT statement imports the CSV file to the Sales table.

BULK INSERT Sales
FROM 'C:\1500000 Sales Records.csv'
WITH (FIRSTROW = 2,
    FIELDTERMINATOR = ',',
    ROWTERMINATOR='\n' );

Get a list of dates between two dates using a function

SELECT  dateadd(dd,DAYS,'2013-09-07 00:00:00') DATES
INTO        #TEMP1
FROM
(SELECT TOP 365 colorder - 1 AS DAYS from master..syscolumns 
    WHERE id = -519536829 order by colorder) a

WHERE datediff(dd,dateadd(dd,DAYS,'2013-09-07 00:00:00'),'2013-09-13 00:00:00' ) >= 0 
    AND  dateadd(dd,DAYS,'2013-09-07 00:00:00') <=  '2013-09-13 00:00:00'  
    SELECT * FROM #TEMP1

Customize the Authorization HTTP header

In the case of CROSS ORIGIN request read this:

I faced this situation and at first I chose to use the Authorization Header and later removed it after facing the following issue.

Authorization Header is considered a custom header. So if a cross-domain request is made with the Autorization Header set, the browser first sends a preflight request. A preflight request is an HTTP request by the OPTIONS method, this request strips all the parameters from the request. Your server needs to respond with Access-Control-Allow-Headers Header having the value of your custom header (Authorization header).

So for each request the client (browser) sends, an additional HTTP request(OPTIONS) was being sent by the browser. This deteriorated the performance of my API. You should check if adding this degrades your performance. As a workaround I am sending tokens in http parameters, which I know is not the best way of doing it but I couldn't compromise with the performance.

Simple 'if' or logic statement in Python

If key isn't an int or float but a string, you need to convert it to an int first by doing

key = int(key)

or to a float by doing

key = float(key)

Otherwise, what you have in your question should work, but

if (key < 1) or (key > 34):

or

if not (1 <= key <= 34):

would be a bit clearer.

Clear and reset form input fields

I don't know if this is still relevant. But when I had similar issue this is how I resolved it.

Where you need to clear an uncontrolled form you simply do this after submission.

this.<ref-name-goes-here>.setState({value: ''});

Hope this helps.

Trigger an event on `click` and `enter`

Use keypress event on usersSearch textbox and look for Enter button. If enter button is pressed then trigger the search button click event which will do the rest of work. Try this.

$('document').ready(function(){
    $('#searchButton').click(function(){
        var search = $('#usersSearch').val();
        $.post('../searchusers.php',{search: search},function(response){
            $('#userSearchResultsTable').html(response);
        });
    })
    $('#usersSearch').keypress(function(e){
        if(e.which == 13){//Enter key pressed
            $('#searchButton').click();//Trigger search button click event
        }
    });

});

Demo

How can I go back/route-back on vue-router?

You can use Programmatic Navigation.In order to go back, you use this:

router.go(n) 

Where n can be positive or negative (to go back). This is the same as history.back().So you can have your element like this:

<a @click="$router.go(-1)">back</a>

In C#, what's the difference between \n and \r\n?

\n is the line break used by Unix(-like) systems, \r\n is used by windows. This has nothing to do with C#.

Eclipse projects not showing up after placing project files in workspace/projects

Yeah.... i kinda see what you need. I just came across same problem.

Here is exactly what i did. Now, bear in mind, this some low level knowledge, since i'm just starting. I made my life complicated, so i needed solution. I kinda found it on my own, using different directions from above answers.

I switched from win 10 on HDD to linux on SSD, so i needed my few of .class and .java imported into new workspace.

First i made a mistake, not using export option on windows and i just simply copied all of files from src and bin folders on win 10 to src and bin folders on linux. Of course workspace did not see those files.

Solution was found in IMPORT tool (which i should have used right away).

  1. I put all of files in src folder into zipp file, and moved this file to some arbitrary folder (Home folder in my case).

  2. Go back to src folder and delete all of .java files (you won't be needing them anymore).

  3. Then i opened my empty project and selected import from File menu in Eclipse. In import window, under option General (first one) select Import Archive.

  4. Now simply find your zip file, and Voila! All is where it should be.

How do I implement Toastr JS?

You dont need jquery-migrate. Summarizing previous answers, here is a working html:

<html>
<body>
  <a id='linkButton'>ClickMe</a>
  <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/css/toastr.css" rel="stylesheet"/>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/js/toastr.js"></script>
  <script type="text/javascript">
  $(document).ready(function() {
    toastr.options.timeOut = 1500; // 1.5s
    toastr.info('Page Loaded!');
    $('#linkButton').click(function() {
       toastr.success('Click Button');
    });
  });
  </script>
</body>
</html>

Best C++ Code Formatter/Beautifier

AStyle can be customized in great detail for C++ and Java (and others too)

This is a source code formatting tool.


clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.

It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).

It can be configured with a variety of options listed here.

When using config files (named .clang-format) styles can be per directory - the closest such file in parent directories shall be used for a particular file.

Styles can be inherited from a preset (say LLVM or Google) and can later override different options

It is used by Google and others and is production ready.


Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.


Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.

Recommended way to embed PDF in HTML?

PdfToImageServlet using ImageMagick's convert command.

Usage example: <img src='/webAppDirectory/PdfToImageServlet?pdfFile=/usr/share/cups/data/default-testpage.pdf'>

How to print a string multiple times?

EDIT: Old answer erased in response to updated question.

You just store the string in a variable:

separator = "!" * int(raw_input("Enter number: "))
print separator
do_stuff()
print separator
other_stuff()
print separator

Changing SVG image color with javascript

If it is just about the color and there is no specific need for JavaScript, you could also convert them to a font. This link gives you an opportunity to create a font based on the SVG. However, it is not possible to use img attributes afterwards - like "alt". This also limits the accessibility of your website for blind people and so on.

Find the 2nd largest element in an array with minimum number of comparisons

Sorry, JS code...

Tested with the two inputs:

a = [55,11,66,77,72];
a = [ 0, 12, 13, 4, 5, 32, 8 ];

var first = Number.MIN_VALUE;
var second = Number.MIN_VALUE;
for (var i = -1, len = a.length; ++i < len;) {
    var dist = a[i];
    // get the largest 2
    if (dist > first) {
        second = first;
        first = dist;
    } else if (dist > second) { // && dist < first) { // this is actually not needed, I believe
        second = dist;
    }
}

console.log('largest, second largest',first,second);
largest, second largest 32 13

This should have a maximum of a.length*2 comparisons and only goes through the list once.

Display images in asp.net mvc

It is possible to use a handler to do this, even in MVC4. Here's an example from one i made earlier:

public class ImageHandler : IHttpHandler
{
    byte[] bytes;

    public void ProcessRequest(HttpContext context)
    {
        int param;
        if (int.TryParse(context.Request.QueryString["id"], out param))
        {
            using (var db = new MusicLibContext())
            {
                if (param == -1)
                {
                    bytes = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/add.png"));

                    context.Response.ContentType = "image/png";
                }
                else
                {
                    var data = (from x in db.Images
                                where x.ImageID == (short)param
                                select x).FirstOrDefault();

                    bytes = data.ImageData;

                    context.Response.ContentType = "image/" + data.ImageFileType;
                }

                context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                context.Response.BinaryWrite(bytes);
                context.Response.Flush();
                context.Response.End();
            }
        }
        else
        {
            //image not found
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

In the view, i added the ID of the photo to the query string of the handler.

How to Multi-thread an Operation Within a Loop in Python

Edit 2018-02-06: revision based on this comment

Edit: forgot to mention that this works on Python 2.7.x

There's multiprocesing.pool, and the following sample illustrates how to use one of them:

from multiprocessing.pool import ThreadPool as Pool
# from multiprocessing import Pool

pool_size = 5  # your "parallelness"

# define worker function before a Pool is instantiated
def worker(item):
    try:
        api.my_operation(item)
    except:
        print('error with item')

pool = Pool(pool_size)

for item in items:
    pool.apply_async(worker, (item,))

pool.close()
pool.join()

Now if you indeed identify that your process is CPU bound as @abarnert mentioned, change ThreadPool to the process pool implementation (commented under ThreadPool import). You can find more details here: http://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers

What does the term "canonical form" or "canonical representation" in Java mean?

Wikipedia points to the term Canonicalization.

A process for converting data that has more than one possible representation into a "standard" canonical representation. This can be done to compare different representations for equivalence, to count the number of distinct data structures, to improve the efficiency of various algorithms by eliminating repeated calculations, or to make it possible to impose a meaningful sorting order.

The Unicode example made the most sense to me:

Variable-length encodings in the Unicode standard, in particular UTF-8, have more than one possible encoding for most common characters. This makes string validation more complicated, since every possible encoding of each string character must be considered. A software implementation which does not consider all character encodings runs the risk of accepting strings considered invalid in the application design, which could cause bugs or allow attacks. The solution is to allow a single encoding for each character. Canonicalization is then the process of translating every string character to its single allowed encoding. An alternative is for software to determine whether a string is canonicalized, and then reject it if it is not. In this case, in a client/server context, the canonicalization would be the responsibility of the client.

In summary, a standard form of representation for data. From this form you can then convert to any representation you may need.

What is the meaning of the prefix N in T-SQL statements and when should I use it?

1. Performance:

Assume your where clause is like this:

WHERE NAME='JON'

If the NAME column is of any type other than nvarchar or nchar, then you should not specify the N prefix. However, if the NAME column is of type nvarchar or nchar, then if you do not specify the N prefix, then 'JON' is treated as non-unicode. This means the data type of NAME column and string 'JON' are different and so SQL Server implicitly converts one operand’s type to the other. If the SQL Server converts the literal’s type to the column’s type then there is no issue, but if it does the other way then performance will get hurt because the column's index (if available) wont be used.

2. Character set:

If the column is of type nvarchar or nchar, then always use the prefix N while specifying the character string in the WHERE criteria/UPDATE/INSERT clause. If you do not do this and one of the characters in your string is unicode (like international characters - example - a) then it will fail or suffer data corruption.

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

Laravel check if collection is empty

You can always count the collection. For example $mentor->intern->count() will return how many intern does a mentor have.

https://laravel.com/docs/5.2/collections#method-count

In your code you can do something like this

foreach($mentors as $mentor)
    @if($mentor->intern->count() > 0)
    @foreach($mentor->intern as $intern)
        <tr class="table-row-link" data-href="/werknemer/{!! $intern->employee->EmployeeId !!}">
            <td>{{ $intern->employee->FirstName }}</td>
            <td>{{  $intern->employee->LastName }}</td>
        </tr>
    @endforeach
    @else
        Mentor don't have any intern
    @endif
@endforeach

Sending multipart/formdata with jQuery.ajax

If the file input name indicates an array and flags multiple, and you parse the entire form with FormData, it is not necessary to iteratively append() the input files. FormData will automatically handle multiple files.

_x000D_
_x000D_
$('#submit_1').on('click', function() {_x000D_
  let data = new FormData($("#my_form")[0]);_x000D_
_x000D_
  $.ajax({_x000D_
    url: '/path/to/php_file',_x000D_
    type: 'POST',_x000D_
    data: data,_x000D_
    processData: false,_x000D_
    contentType: false,_x000D_
    success: function(r) {_x000D_
      console.log('success', r);_x000D_
    },_x000D_
    error: function(r) {_x000D_
      console.log('error', r);_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form id="my_form">_x000D_
  <input type="file" name="multi_img_file[]" id="multi_img_file" accept=".gif,.jpg,.jpeg,.png,.svg" multiple="multiple" />_x000D_
  <button type="button" name="submit_1" id="submit_1">Not type='submit'</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Note that a regular button type="button" is used, not type="submit". This shows there is no dependency on using submit to get this functionality.

The resulting $_FILES entry is like this in Chrome dev tools:

multi_img_file:
  error: (2) [0, 0]
  name: (2) ["pic1.jpg", "pic2.jpg"]
  size: (2) [1978036, 2446180]
  tmp_name: (2) ["/tmp/phphnrdPz", "/tmp/phpBrGSZN"]
  type: (2) ["image/jpeg", "image/jpeg"]

Note: There are cases where some images will upload just fine when uploaded as a single file, but they will fail when uploaded in a set of multiple files. The symptom is that PHP reports empty $_POST and $_FILES without AJAX throwing any errors. Issue occurs with Chrome 75.0.3770.100 and PHP 7.0. Only seems to happen with 1 out of several dozen images in my test set.

Removing "bullets" from unordered list <ul>

In my case

li {
  list-style-type : none;
}

It doesn't show the bullet but leaved some space for the bullet.

I use

li {
  list-style-type : '';
}

It works perfectly.

What are Runtime.getRuntime().totalMemory() and freeMemory()?

Runtime#totalMemory - the memory that the JVM has allocated thus far. This isn't necessarily what is in use or the maximum.

Runtime#maxMemory - the maximum amount of memory that the JVM has been configured to use. Once your process reaches this amount, the JVM will not allocate more and instead GC much more frequently.

Runtime#freeMemory - I'm not sure if this is measured from the max or the portion of the total that is unused. I am guessing it is a measurement of the portion of total which is unused.

How to change the map center in Leaflet.js

Use map.panTo(); does not do anything if the point is in the current view. Use map.setView() instead.

I had a polyline and I had to center map to a new point in polyline at every second. Check the code : GOOD: https://jsfiddle.net/nstudor/xcmdwfjk/

mymap.setView(point, 11, { animation: true });        

BAD: https://jsfiddle.net/nstudor/Lgahv905/

mymap.panTo(point);
mymap.setZoom(11);

Negative list index?

Negative numbers mean that you count from the right instead of the left. So, list[-1] refers to the last element, list[-2] is the second-last, and so on.

jquery disable form submit on enter

3 years later and not a single person has answered this question completely.

The asker wants to cancel the default form submission and call their own Ajax. This is a simple request with a simple solution. There is no need to intercept every character entered into each input.

Assuming the form has a submit button, whether a <button id="save-form"> or an <input id="save-form" type="submit">, do:

$("#save-form").on("click", function () {
    $.ajax({
        ...
    });
    return false;
});

How can I concatenate two arrays in Java?

Just wanted to add, you can use System.arraycopy too:

import static java.lang.System.out;
import static java.lang.System.arraycopy;
import java.lang.reflect.Array;
class Playground {
    @SuppressWarnings("unchecked")
    public static <T>T[] combineArrays(T[] a1, T[] a2) {
        T[] result = (T[]) Array.newInstance(a1.getClass().getComponentType(), a1.length+a2.length);
        arraycopy(a1,0,result,0,a1.length);
        arraycopy(a2,0,result,a1.length,a2.length);
        return result;
    }
    public static void main(String[ ] args) {
        String monthsString = "JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC";
        String[] months = monthsString.split("(?<=\\G.{3})");
        String daysString = "SUNMONTUEWEDTHUFRISAT";
        String[] days = daysString.split("(?<=\\G.{3})");
        for (String m : months) {
            out.println(m);
        }
        out.println("===");
         for (String d : days) {
            out.println(d);
        }
        out.println("===");
        String[] results = combineArrays(months, days);
        for (String r : results) {
            out.println(r);
        }
        out.println("===");
    }
}

How do I run a node.js app as a background service?

use nssm the best solution for windows, just download nssm, open cmd to nssm directory and type

nssm install <service name> <node path> <app.js path> 

eg: nssm install myservice "C:\Program Files\nodejs" "C:\myapp\app.js" 

this will install a new windows service which will be listed at services.msc from there you can start or stop the service, this service will auto start and you can configure to restart if it fails.

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

Google's (bad) approach, from HN thread. Store RLE-style counts.

Your initial data structure is '99999999:0' (all zeros, haven't seen any numbers) and then lets say you see the number 3,866,344 so your data structure becomes '3866343:0,1:1,96133654:0' as you can see the numbers will always alternate between number of zero bits and number of '1' bits so you can just assume the odd numbers represent 0 bits and the even numbers 1 bits. This becomes (3866343,1,96133654)

Their problem doesn't seem to cover duplicates, but let's say they use "0:1" for duplicates.

Big problem #1: insertions for 1M integers would take ages.

Big problem #2: like all plain delta encoding solutions, some distributions can't be covered this way. For example, 1m integers with distances 0:99 (e.g. +99 each one). Now think the same but with random distance in the range of 0:99. (Note: 99999999/1000000 = 99.99)

Google's approach is both unworthy (slow) and incorrect. But to their defense, their problem might have been slightly different.

Splitting string into multiple rows in Oracle

Without using connect by or regexp:

    with mytable as (
      select 108 name, 'test' project, 'Err1,Err2,Err3' error from dual
      union all
      select 109, 'test2', 'Err1' from dual
    )
    ,x as (
      select name
      ,project
      ,','||error||',' error
      from mytable
    )
    ,iter as (SELECT rownum AS pos
        FROM all_objects
    )
    select x.name,x.project
    ,SUBSTR(x.error
      ,INSTR(x.error, ',', 1, iter.pos) + 1
      ,INSTR(x.error, ',', 1, iter.pos + 1)-INSTR(x.error, ',', 1, iter.pos)-1
    ) error
    from x, iter
    where iter.pos < = (LENGTH(x.error) - LENGTH(REPLACE(x.error, ','))) - 1;

Get custom product attributes in Woocommerce

Edited: The woocommerce_get_product_terms is deprecated since Woocommerce version 3

Go with the following as @datafeedr wrote in his answer:

global $product;
$koostis = array_shift( wc_get_product_terms( $product->id, 'pa_koostis', array( 'fields' => 'names' ) ) );

or even more compact:

global $product;
$koostis = $product->get_attribute( 'pa_koostis' );

Original answer:

$result = array_shift(woocommerce_get_product_terms($product->id, 'pa_koostis', 'names'));

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

What I see in this case is that if I pull the client machine's network cable and make the call, the ajax success handler is called (why, I don't know), and the data parameter is an empty string. So if you factor out the real error handling, you can do something like this:

function handleError(jqXHR, textStatus, errorThrown) {
    ...
}

jQuery.ajax({
    ...
    success: function(data, textStatus, jqXHR) {
        if (data == "") handleError(jqXHR, "clientNetworkError", "");
    },
    error: handleError
});

How can I remove non-ASCII characters but leave periods and spaces using Python?

You may use the following code to remove non-English letters:

import re
str = "123456790 ABC#%? .(???)"
result = re.sub(r'[^\x00-\x7f]',r'', str)
print(result)

This will return

123456790 ABC#%? .()

How to take MySQL database backup using MySQL Workbench?

In Window in new version you can export like this

enter image description here enter image description here

enter image description here

CSS Always On Top

Ensure position is on your element and set the z-index to a value higher than the elements you want to cover.

element {
    position: fixed;
    z-index: 999;
}

div {
    position: relative;
    z-index: 99;
}

It will probably require some more work than that but it's a start since you didn't post any code.

Change values of select box of "show 10 entries" of jquery datatable

According to datatables.net the proper way to do this is adding the lengthMenu property with an array of values.

$(document).ready(function() {
    $('#example').dataTable( {
        "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
    } );
} );

How can I specify the schema to run an sql file against in the Postgresql command line

Main Example

The example below will run myfile.sql on database mydatabase using schema myschema.

psql "dbname=mydatabase options=--search_path=myschema" -a -f myfile.sql

The way this works is the first argument to the psql command is the dbname argument. The docs mention a connection string can be provided.

If this parameter contains an = sign or starts with a valid URI prefix (postgresql:// or postgres://), it is treated as a conninfo string

The dbname keyword specifies the database to connect to and the options keyword lets you specify command-line options to send to the server at connection startup. Those options are detailed in the server configuration chapter. The option we are using to select the schema is search_path.

Another Example

The example below will connect to host myhost on database mydatabase using schema myschema. The = special character must be url escaped with the escape sequence %3D.

psql postgres://myuser@myhost?options=--search_path%3Dmyschema

How could I put a border on my grid control in WPF?

If someone is interested in the similar problem, but is not working with XAML, here's my solution:

var B1 = new Border();
B1.BorderBrush = Brushes.Black;
B1.BorderThickness = new Thickness(0, 1, 0, 0); // You can specify here which borders do you want
YourPanel.Children.Add(B1);

Regex for 1 or 2 digits, optional non-alphanumeric, 2 known alphas

^\d{1,2}[\W_]?po$

\d defines a number and {1,2} means 1 or two of the expression before, \W defines a non word character.

How to use both onclick and target="_blank"

Instead use window.open():

The syntax is:

window.open(strUrl, strWindowName[, strWindowFeatures]);

Your code should have:

window.open('Prosjektplan.pdf');

Your code should be:

<p class="downloadBoks"
   onclick="window.open('Prosjektplan.pdf')">Prosjektbeskrivelse</p>

How to download file from database/folder using php

You can also use the following code:

<?php
$filename = $_GET["nama"];
$contenttype = "application/force-download";
header("Content-Type: " . $contenttype);
header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\";");
readfile("your file uploaded path".$filename);
exit();
?>

How do I put a variable inside a string?

I had a need for an extended version of this: instead of embedding a single number in a string, I needed to generate a series of file names of the form 'file1.pdf', 'file2.pdf' etc. This is how it worked:

['file' + str(i) + '.pdf' for i in range(1,4)]

How to change the playing speed of videos in HTML5?

javascript:document.getElementsByClassName("video-stream html5-main-video")[0].playbackRate = 0.1;

you can put any number here just don't go to far so you don't overun your computer.

String.Format for Hex

Translate composed UInt32 color Value to CSS in .NET

I know the question applies to 3 input values (red green blue). But there may be the situation where you already have a composed 32bit Value. It looks like you want to send the data to some HTML CSS renderer (because of the #HEX format). Actually CSS wants you to print 6 or at least 3 zero filled hex digits here. so #{0:X06} or #{0:X03} would be required. Due to some strange behaviour, this always prints 8 digits instead of 6.

Solve this by:

String.Format("#{0:X02}{1:X02}{2:X02}", (Value & 0x00FF0000) >> 16, (Value & 0x0000FF00) >> 8, (Value & 0x000000FF) >> 0)

How do I disable form resizing for users?

Change this property and try this at design time:

FormBorderStyle = FormBorderStyle.FixedDialog;

Designer view before the change:

Enter image description here

Redefining the Index in a Pandas DataFrame object

If you don't want 'a' in the index

In :

col = ['a','b','c']

data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)

data

Out:

    a   b   c
0   1   2   3
1  10  11  12
2  20  21  22

In :

data2 = data.set_index('a')

Out:

     b   c
a
1    2   3
10  11  12
20  21  22

In :

data2.index.name = None

Out:

     b   c
 1   2   3
10  11  12
20  21  22

Regular expression to stop at first match

Use of Lazy quantifiers ? with no global flag is the answer.

Eg,

enter image description here

If you had global flag /g then, it would have matched all the lowest length matches as below. enter image description here

How to set an iframe src attribute from a variable in AngularJS

It is the $sce service that blocks URLs with external domains, it is a service that provides Strict Contextual Escaping services to AngularJS, to prevent security vulnerabilities such as XSS, clickjacking, etc. it's enabled by default in Angular 1.2.

You can disable it completely, but it's not recommended

angular.module('myAppWithSceDisabledmyApp', [])
   .config(function($sceProvider) {
       $sceProvider.enabled(false);
   });

for more info https://docs.angularjs.org/api/ng/service/$sce

Background color in input and text fields

input[type="text"], textarea {

  background-color : #d1d1d1; 

}

Hope that helps :)

Edit: working example, http://jsfiddle.net/C5WxK/

Best way to strip punctuation from a string

Here's one other easy way to do it using RegEx

import re

punct = re.compile(r'(\w+)')

sentence = 'This ! is : a # sample $ sentence.' # Text with punctuation
tokenized = [m.group() for m in punct.finditer(sentence)]
sentence = ' '.join(tokenized)
print(sentence) 
'This is a sample sentence'

How can I make an entire HTML form "readonly"?

On the confirmation page, don't put the content in editable controls, just write them to the page.

UICollectionView - dynamic cell height?

Seems like it's quite a popular question, so I will try to make my humble contribution.


The code below is Swift 4 solution for no-storyboard setup. It utilizes some approaches from previous answers, therefore it prevents Auto Layout warning caused on device rotation.

I am sorry if code samples are a bit long. I want to provide an "easy-to-use" solution fully hosted by StackOverflow. If you have any suggestions to the post - please, share the idea and I will update it accordingly.

The setup:

Two classes: ViewController.swift and MultilineLabelCell.swift - Cell containing single UILabel.

MultilineLabelCell.swift

import UIKit

class MultilineLabelCell: UICollectionViewCell {
    static let reuseId = "MultilineLabelCellReuseId"

    private let label: UILabel = UILabel(frame: .zero)

    override init(frame: CGRect) {
        super.init(frame: frame)

        layer.borderColor = UIColor.red.cgColor
        layer.borderWidth = 1.0

        label.numberOfLines = 0
        label.lineBreakMode = .byWordWrapping

        let labelInset = UIEdgeInsets(top: 10, left: 10, bottom: -10, right: -10)
        contentView.addSubview(label)
        label.translatesAutoresizingMaskIntoConstraints = false
        label.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor, constant: labelInset.top).isActive = true
        label.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor, constant: labelInset.left).isActive = true
        label.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor, constant: labelInset.right).isActive = true
        label.bottomAnchor.constraint(equalTo: contentView.layoutMarginsGuide.bottomAnchor, constant: labelInset.bottom).isActive = true

        label.layer.borderColor = UIColor.black.cgColor
        label.layer.borderWidth = 1.0
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("Storyboards are quicker, easier, more seductive. Not stronger then Code.")
    }

    func configure(text: String?) {
        label.text = text
    }

    override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
        label.preferredMaxLayoutWidth = layoutAttributes.size.width - contentView.layoutMargins.left - contentView.layoutMargins.left
        layoutAttributes.bounds.size.height = systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
        return layoutAttributes
    }
}

ViewController.swift

import UIKit

let samuelQuotes = [
    "Samuel says", 
    "Add different length strings here for better testing"
]

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    private(set) var collectionView: UICollectionView

    // Initializers
    init() {
        // Create new `UICollectionView` and set `UICollectionViewFlowLayout` as its layout
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        // Create new `UICollectionView` and set `UICollectionViewFlowLayout` as its layout
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
        super.init(coder: aDecoder)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "Dynamic size sample"

        // Register Cells
        collectionView.register(MultilineLabelCell.self, forCellWithReuseIdentifier: MultilineLabelCell.reuseId)

        // Add `coolectionView` to display hierarchy and setup its appearance
        view.addSubview(collectionView)
        collectionView.backgroundColor = .white
        collectionView.contentInsetAdjustmentBehavior = .always
        collectionView.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

        // Setup Autolayout constraints
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
        collectionView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
        collectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
        collectionView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true

        // Setup `dataSource` and `delegate`
        collectionView.dataSource = self
        collectionView.delegate = self

        (collectionView.collectionViewLayout as! UICollectionViewFlowLayout).estimatedItemSize = UICollectionViewFlowLayout.automaticSize
        (collectionView.collectionViewLayout as! UICollectionViewFlowLayout).sectionInsetReference = .fromLayoutMargins
    }

    // MARK: - UICollectionViewDataSource -
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MultilineLabelCell.reuseId, for: indexPath) as! MultilineLabelCell
        cell.configure(text: samuelQuotes[indexPath.row])
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return samuelQuotes.count
    }

    // MARK: - UICollectionViewDelegateFlowLayout -
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let sectionInset = (collectionViewLayout as! UICollectionViewFlowLayout).sectionInset
        let referenceHeight: CGFloat = 100 // Approximate height of your cell
        let referenceWidth = collectionView.safeAreaLayoutGuide.layoutFrame.width
            - sectionInset.left
            - sectionInset.right
            - collectionView.contentInset.left
            - collectionView.contentInset.right
        return CGSize(width: referenceWidth, height: referenceHeight)
    }
}

To run this sample create new Xcode project, create corresponding files and replace AppDelegate contents with the following code:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var navigationController: UINavigationController?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)

        if let window = window {
            let vc = ViewController()
            navigationController = UINavigationController(rootViewController: vc)
            window.rootViewController = navigationController
            window.makeKeyAndVisible()
        }

        return true
    }
}

How to list all available Kafka brokers in a cluster?

If you are using new version of Kafka e.g. 5.3.3, you can use

kafka-broker-api-versions  --bootstrap-server BROKER | grep 9092

You just need to pass one of the brokers

Will Google Android ever support .NET?

.NET for Android seems like a real possibility to me. There is news that Microsoft will release proper Silverlight for Android- Never underestimate the advantages to Microsoft for putting the boot into Apple. A smartphone that is faster, more feature rich, faster development lifecycle, impressive hardware, Flash & Silverlight as a standard installable.

Microsoft has a vested interest in improving Android, and at the same time, applications will be devloped for Silverlight on Android will also work on Windows Phone 7 OS with multi-touch, GPS, etc., etc.

generate a random number between 1 and 10 in c

You need a different seed at every execution.

You can start to call at the beginning of your program:

srand(time(NULL));

Note that % 10 yields a result from 0 to 9 and not from 1 to 10: just add 1 to your % expression to get 1 to 10.

How to retrieve absolute path given relative

If you want to transform a variable containing a relative path into an absolute one, this works :

   dir=`cd "$dir"`

"cd" echoes without changing the working directory, because executed here in a sub-shell.

How to get tf.exe (TFS command line client)?

For reference: these are the required DLLs for Visual Studio 2017 (as did @ijprest for the VS 2010)

TF.exe
TF.exe.config
Microsoft.TeamFoundation.Client.dll
Microsoft.TeamFoundation.Common.dll
Microsoft.TeamFoundation.Core.WebApi.dll
Microsoft.TeamFoundation.VersionControl.Client.dll
Microsoft.TeamFoundation.VersionControl.Common.dll
Microsoft.TeamFoundation.VersionControl.Controls.dll
Microsoft.VisualStudio.Services.Client.Interactive.dll
Microsoft.VisualStudio.Services.Common.dll
Microsoft.VisualStudio.Services.WebApi.dll

They will be in my base VM image. I'm going to use it to pull the latest deployment scripts from VC to a temporary local workspace folder when installing a new server.

tf workspace /new ... 
tf workfold /map ...
tf get "%WorkSpaceLocalFolder%" /recursive
tf workfold /unmap 
tf workspace /delete

<run deployment scripts from "%WorkSpaceLocalFolder%" >

rmdir "%WorkSpaceLocalFolder%"

(Sorry to post this as an answer, but I don't have enough reputation to comment, which I believe it should have been)

jQuery OR Selector?

Daniel A. White Solution works great for classes.

I've got a situation where I had to find input fields like donee_1_card where 1 is an index.

My solution has been

$("input[name^='donee']" && "input[name*='card']")

Though I am not sure how optimal it is.

Addition for BigDecimal

You can also do it like this:

BigDecimal A = new BigDecimal("10000000000");
BigDecimal B = new BigDecimal("20000000000");
BigDecimal C = new BigDecimal("30000000000");
BigDecimal resultSum = (A).add(B).add(C);
System.out.println("A+B+C= " + resultSum);

Prints:

A+B+C= 60000000000

How do I run Java .class files?

  1. Go to the path where you saved the java file you want to compile.
  2. Replace path by typing cmd and press enter.
  3. Command Prompt Directory will pop up containing the path file like C:/blah/blah/foldercontainJava
  4. Enter javac javafile.java
  5. Press Enter. It will automatically generate java class file

Resolving MSB3247 - Found conflicts between different versions of the same dependent assembly

I had this problem too and used AMissico's advice too discover the problem (Although had to set verbosity level to Detailed.

The problem was actually quite straight forward though after finding the culprit.

Background: I upgraded my project from VS2008 to VS2010. In VS2008 the target framework was 3.5 and when I brought it into VS2010 I switched it to 4 (Full). I also upgraded some third party components including Crystal reports.

It turned out most of System references where pointing at version 4.0.0.0 but a couple had not been automatically changed (System and System.Web.Services) and were still looking at 2.0.0.0. Crystal reports is referencing 4.0.0.0 and so this was where the conflicts were occuring. Simply putting the cursor at the first System library in the solution explorer, cursor down the list and looking for any references to 2.0.0.0, removing and re-adding newer 4.0.0.0 version did the trick.

The strange this was that most of the references had been correctly updated and if it weren't for Crystal reports, I probably would never had noticed...

In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

At the very core, the file extension you use makes no difference as to how perl interprets those files.

However, putting modules in .pm files following a certain directory structure that follows the package name provides a convenience. So, if you have a module Example::Plot::FourD and you put it in a directory Example/Plot/FourD.pm in a path in your @INC, then use and require will do the right thing when given the package name as in use Example::Plot::FourD.

The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with 1; unless you're sure it'll return true otherwise. But it's better just to put the 1;, in case you add more statements.

If EXPR is a bareword, the require assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace.

All use does is to figure out the filename from the package name provided, require it in a BEGIN block and invoke import on the package. There is nothing preventing you from not using use but taking those steps manually.

For example, below I put the Example::Plot::FourD package in a file called t.pl, loaded it in a script in file s.pl.

C:\Temp> cat t.pl
package Example::Plot::FourD;

use strict; use warnings;

sub new { bless {} => shift }

sub something { print "something\n" }

"Example::Plot::FourD"

C:\Temp> cat s.pl
#!/usr/bin/perl
use strict; use warnings;

BEGIN {
    require 't.pl';
}

my $p = Example::Plot::FourD->new;
$p->something;


C:\Temp> s
something

This example shows that module files do not have to end in 1, any true value will do.

Configure hibernate (using JPA) to store Y/N for type Boolean instead of 0/1

I used the concept from the answer posted by @marcg and it works great with JPA 2.1. His code wasn't quite right, so I'm posted my working implementation. This will convert Boolean entity fields to a Y/N character column in the database.

From my entity class:

@Convert(converter=BooleanToYNStringConverter.class)
@Column(name="LOADED", length=1)
private Boolean isLoadedSuccessfully;

My converter class:

/**
 * Converts a Boolean entity attribute to a single-character
 * Y/N string that will be stored in the database, and vice-versa
 * 
 * @author jtough
 */
public class BooleanToYNStringConverter 
        implements AttributeConverter<Boolean, String> {

    /**
     * This implementation will return "Y" if the parameter is Boolean.TRUE,
     * otherwise it will return "N" when the parameter is Boolean.FALSE. 
     * A null input value will yield a null return value.
     * @param b Boolean
     */
    @Override
    public String convertToDatabaseColumn(Boolean b) {
        if (b == null) {
            return null;
        }
        if (b.booleanValue()) {
            return "Y";
        }
        return "N";
    }

    /**
     * This implementation will return Boolean.TRUE if the string
     * is "Y" or "y", otherwise it will ignore the value and return
     * Boolean.FALSE (it does not actually look for "N") for any
     * other non-null string. A null input value will yield a null
     * return value.
     * @param s String
     */
    @Override
    public Boolean convertToEntityAttribute(String s) {
        if (s == null) {
            return null;
        }
        if (s.equals("Y") || s.equals("y")) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

}

This variant is also fun if you love emoticons and are just sick and tired of Y/N or T/F in your database. In this case, your database column must be two characters instead of one. Probably not a big deal.

/**
 * Converts a Boolean entity attribute to a happy face or sad face
 * that will be stored in the database, and vice-versa
 * 
 * @author jtough
 */
public class BooleanToHappySadConverter 
        implements AttributeConverter<Boolean, String> {

    public static final String HAPPY = ":)";
    public static final String SAD = ":(";

    /**
     * This implementation will return ":)" if the parameter is Boolean.TRUE,
     * otherwise it will return ":(" when the parameter is Boolean.FALSE. 
     * A null input value will yield a null return value.
     * @param b Boolean
     * @return String or null
     */
    @Override
    public String convertToDatabaseColumn(Boolean b) {
        if (b == null) {
            return null;
        }
        if (b) {
            return HAPPY;
        }
        return SAD;
    }

    /**
     * This implementation will return Boolean.TRUE if the string
     * is ":)", otherwise it will ignore the value and return
     * Boolean.FALSE (it does not actually look for ":(") for any
     * other non-null string. A null input value will yield a null
     * return value.
     * @param s String
     * @return Boolean or null
     */
    @Override
    public Boolean convertToEntityAttribute(String s) {
        if (s == null) {
            return null;
        }
        if (HAPPY.equals(s)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

}

Android ImageButton with a selected state?

if (iv_new_pwd.isSelected()) {
                iv_new_pwd.setSelected(false);
                Log.d("mytag", "in case 1");
                edt_new_pwd.setInputType(InputType.TYPE_CLASS_TEXT);
            } else {
                Log.d("mytag", "in case 1");
                iv_new_pwd.setSelected(true);
                edt_new_pwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            }

Reading from text file until EOF repeats last line

The EOF pattern needs a prime read to 'bootstrap' the EOF checking process. Consider the empty file will not initially have its EOF set until the first read. The prime read will catch the EOF in this instance and properly skip the loop completely.

What you need to remember here is that you don't get the EOF until the first attempt to read past the available data of the file. Reading the exact amount of data will not flag the EOF.

I should point out if the file was empty your given code would have printed since the EOF will have prevented a value from being set to x on entry into the loop.

  • 0

So add a prime read and move the loop's read to the end:

int x;

iFile >> x; // prime read here
while (!iFile.eof()) {
    cerr << x << endl;
    iFile >> x;
}

Difference between logical addresses, and physical addresses?

logical address is address relative to program. It tells how much memory a particular process will take, not tell what will the exact location of the process and this exact location will we generated by using some mapping, and is known as physical address.

Exiting out of a FOR loop in a batch file?

Assuming that the OP is invoking a batch file with cmd.exe, to properly break out of a for loop just goto a label;

Change this:

For /L %%f In (1,1,1000000) Do If Not Exist %%f Goto :EOF

To this:

For /L %%f In (1,1,1000000) Do If Not Exist %%f Goto:fileError
.. do something
.. then exit or do somethign else

:fileError
GOTO:EOF

Better still, add some error reporting:

set filename=
For /L %%f In (1,1,1000000) Do(
    set filename=%%f
    If Not Exist %%f set tempGoto:fileError
)
.. do something
.. then exit or do somethign else

:fileError
echo file does not exist '%filename%'
GOTO:EOF

I find this to be a helpful site about lesser known cmd.exe/DOS batch file functions and tricks: https://www.dostips.com/

Making a mocked method return an argument that was passed to it

If you have Mockito 1.9.5 or higher, there is a new static method that can make the Answer object for you. You need to write something like

import static org.mockito.Mockito.when;
import static org.mockito.AdditionalAnswers.returnsFirstArg;

when(myMock.myFunction(anyString())).then(returnsFirstArg());

or alternatively

doAnswer(returnsFirstArg()).when(myMock).myFunction(anyString());

Note that the returnsFirstArg() method is static in the AdditionalAnswers class, which is new to Mockito 1.9.5; so you'll need the right static import.

How do I remove the "extended attributes" on a file in Mac OS X?


Answer (Individual Files)


1. Showcase keys to use in selection.

xattr ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
    # com.apple.FinderInfo
    # com.apple.lastuseddate#PS
    # com.apple.metadata:kMDItemIsScreenCapture
    # com.apple.metadata:kMDItemScreenCaptureGlobalRect
    # com.apple.metadata:kMDItemScreenCaptureType

2. Pick a Key to delete.

xattr -d com.apple.lastuseddate#PS ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
xattr -d kMDItemIsScreenCapture ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png

3. Showcase keys again to see they have been removed.

xattr -l ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
    # com.apple.FinderInfo
    # com.apple.metadata:kMDItemScreenCaptureGlobalRect
    # com.apple.metadata:kMDItemScreenCaptureType

4. Lastly, REMOVE ALL keys for a particular file

xattr -c ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png

Answer (All Files In A Directory)


1. Showcase keys to use in selection.

xattr -r ~/Desktop

2. Remove a Specific Key for EVERY FILE in a directory

xattr -rd com.apple.FinderInfo ~/Desktop

3. Remove ALL keys on EVERY FILE in a directory

xattr -rc ~/Desktop

WARN: Once you delete these you DON'T get them back!
FAULT ERROR: There is NO UNDO.


Errors


I wanted to address the error's people are getting. Because the errors drove me nuts too... On a mac if you install xattr in python, then your environment may have an issue.

There are two different paths on my mac for xattr

type -a xattr

    # xattr is /usr/local/bin/xattr    # PYTHON Installed Version
    # xattr is /usr/bin/xattr          # Mac OSX Installed Version

So in one of the example's where -c will not work in xargs is because in bash you default to the non-python version.

Works with -c

/usr/bin/xattr -c

Does NOT Work with -c

/usr/local/bin/xattr -c
    # option -c not recognized

My Shell/Terminal defaults to /usr/local/bin/xattr because my $PATH /usr/local/bin: is before /usr/bin: which I believe is the default.

I can prove this because, if you try to uninstall the python xattr you will see:

pip3 uninstall xattr
Uninstalling xattr-0.9.6:
  Would remove:
    /usr/local/bin/xattr
    /usr/local/lib/python3.7/site-packages/xattr-0.9.6.dist-info/*
    /usr/local/lib/python3.7/site-packages/xattr/*
Proceed (y/n)?

Workarounds


To Fix option -c not recognized Errors.

  1. Uninstall any Python xattr you may have: pip3 uninstall xattr
  2. Close all Terminal windows & quit Terminal
  3. Reopen a new Terminal window.
  4. ReRun xattr command and it should now work.

OR

If you want to keep the Python xattr then use

/usr/bin/xattr

for any Shell commands in Terminal


Example:


Python's version of xattr doesn't handle images at all:

Good-Mac:~ JayRizzo$ xattr ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
    # com.apple.FinderInfo
    # Traceback (most recent call last):
    #   File "/usr/local/bin/xattr", line 8, in <module>
    #     sys.exit(main())
    #   File "/usr/local/lib/python3.7/site-packages/xattr/tool.py", line 196, in main
    #     attr_value = attr_value.decode('utf-8')
    # UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb0 in position 2: invalid start byte

Good-Mac:~ JayRizzo$ /usr/bin/xattr ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
    # com.apple.FinderInfo
    # com.apple.lastuseddate#PS
    # com.apple.metadata:kMDItemIsScreenCapture
    # com.apple.metadata:kMDItemScreenCaptureGlobalRect
    # com.apple.metadata:kMDItemScreenCaptureType

Man Pages

MAN PAGE for OSX xattr

MAN PAGE for Python xattr VERSION 0.6.4

NOTE: I could not find the python help page for current VERSION 0.9.6

Thanks for Reading!

What Language is Used To Develop Using Unity

All development is done using your choice of C#, Boo, or a dialect of JavaScript.

  • C# needs no explanation :)
  • Boo is a CLI language with very similar syntax to Python; it is, however, statically typed and has a few other differences. It's not "really" Python; it just looks similar.
  • The version of JavaScript used by Unity is also a CLI language, and is compiled. Newcomers often assume JS isn't as good as the other three, but it's compiled and just as fast and functional.

Most of the example code in the documentation is in JavaScript; if you poke around the official forums and wiki you'll see a pretty even mix of C# and Javascript. Very few people seem to use Boo, but it's just as good; pick the language you already know or are the happiest learning.

Unity takes your C#/JS/Boo code and compiles it to run on iOS, Android, PC, Mac, XBox, PS3, Wii, or web plugin. Depending on the platform that might end up being Objective C or something else, but that's completely transparent to you. There's really no benefit to knowing Objective C; you can't program in it.


Update 2019/31/01

Starting from Unity 2017.2 "UnityScript" (Unity's version of JavaScript, but not identical to) took its first step towards complete deprecation by removing the option to add a "JavaScript" file from the UI. Though JS files could still be used, support for it will completely be dropped in later versions.

This also means that Boo will become unusable as its compiler is actually built as a layer on top of UnityScript and will thus be removed as well.

This means that in the future only C# will have native support.

unity has released a full article on the deprecation of UnityScript and Boo back in August 2017.

Javascript parse float is ignoring the decimals after my comma

In my case, I already had a period(.) and also a comma(,), so what worked for me was to replace the comma(,) with an empty string like below:

parseFloat('3,000.78'.replace(',', '')) 

This is assuming that the amount from the existing database is 3,000.78. The results are: 3000.78 without the initial comma(,).

SQL: How do I SELECT only the rows with a unique value on certain column?

Assuming your table of data is called ProjectInfo:

SELECT DISTINCT Contract, Activity
    FROM ProjectInfo
    WHERE Contract = (SELECT Contract
                          FROM (SELECT DISTINCT Contract, Activity
                                    FROM ProjectInfo) AS ContractActivities
                          GROUP BY Contract
                          HAVING COUNT(*) = 1);

The innermost query identifies the contracts and the activities. The next level of the query (the middle one) identifies the contracts where there is just one activity. The outermost query then pulls the contract and activity from the ProjectInfo table for the contracts that have a single activity.

Tested using IBM Informix Dynamic Server 11.50 - should work elsewhere too.

Check if a div does NOT exist with javascript

All these answers do NOT take into account that you asked specifically about a DIV element.

document.querySelector("div#the-div-id")

@see https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

Prevent WebView from displaying "web page not available"

Finally, I solved this. (It works till now..)

My solution is like this...

  1. Prepare the layout to show when an error occurred instead of Web Page (a dirty 'page not found message') The layout has one button, "RELOAD" with some guide messages.

  2. If an error occurred, Remember using boolean and show the layout we prepare.

  3. If user click "RELOAD" button, set mbErrorOccured to false. And Set mbReloadPressed to true.
  4. if mbErrorOccured is false and mbReloadPressed is true, it means webview loaded page successfully. 'Cause if error occurred again, mbErrorOccured will be set true on onReceivedError(...)

Here is my full source. Check this out.

public class MyWebViewActivity extends ActionBarActivity implements OnClickListener {

    private final String TAG = MyWebViewActivity.class.getSimpleName();
    private WebView mWebView = null;
    private final String URL = "http://www.google.com";
    private LinearLayout mlLayoutRequestError = null;
    private Handler mhErrorLayoutHide = null;

    private boolean mbErrorOccured = false;
    private boolean mbReloadPressed = false;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);

        ((Button) findViewById(R.id.btnRetry)).setOnClickListener(this);
        mlLayoutRequestError = (LinearLayout) findViewById(R.id.lLayoutRequestError);
        mhErrorLayoutHide = getErrorLayoutHideHandler();

        mWebView = (WebView) findViewById(R.id.webviewMain);
        mWebView.setWebViewClient(new MyWebViewClient());
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        mWebView.setWebChromeClient(getChromeClient());
        mWebView.loadUrl(URL);
    }

    @Override
    public boolean onSupportNavigateUp() {
        return super.onSupportNavigateUp();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.btnRetry) {
            if (!mbErrorOccured) {
                return;
            }

            mbReloadPressed = true;
            mWebView.reload();
            mbErrorOccured = false;
        }
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
            return;
        }
        else {
            finish();
        }

        super.onBackPressed();
    }

    class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (mbErrorOccured == false && mbReloadPressed) {
                hideErrorLayout();
                mbReloadPressed = false;
            }

            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            mbErrorOccured = true;
            showErrorLayout();
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    }

    private WebChromeClient getChromeClient() {
        final ProgressDialog progressDialog = new ProgressDialog(MyWebViewActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(false);

        return new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }
        };
    }

    private void showErrorLayout() {
        mlLayoutRequestError.setVisibility(View.VISIBLE);
    }

    private void hideErrorLayout() {
        mhErrorLayoutHide.sendEmptyMessageDelayed(10000, 200);
    }

    private Handler getErrorLayoutHideHandler() {
        return new Handler() {
            @Override
            public void handleMessage(Message msg) {
                mlLayoutRequestError.setVisibility(View.GONE);
                super.handleMessage(msg);
            }
        };
    }
}

Addition:Here is layout....

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rLayoutWithWebView"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<WebView
    android:id="@+id/webviewMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<LinearLayout
    android:id="@+id/lLayoutRequestError"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    android:background="@color/white"
    android:gravity="center"
    android:orientation="vertical"
    android:visibility="gone" >

    <Button
        android:id="@+id/btnRetry"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:minWidth="120dp"
        android:text="RELOAD"
        android:textSize="20dp"
        android:textStyle="bold" />
</LinearLayout>

Convert UTC Epoch to local date

Addition to the above answer by @djechlin

d = '1394104654000';
new Date(parseInt(d));

converts EPOCH time to human readable date. Just don't forget that type of EPOCH time must be an Integer.

Why not inherit from List<T>?

There are a lot excellent answers here, but I want to touch on something I didn't see mentioned: Object oriented design is about empowering objects.

You want to encapsulate all your rules, additional work and internal details inside an appropriate object. In this way other objects interacting with this one don't have to worry about it all. In fact, you want to go a step further and actively prevent other objects from bypassing these internals.

When you inherit from List, all other objects can see you as a List. They have direct access to the methods for adding and removing players. And you'll have lost your control; for example:

Suppose you want to differentiate when a player leaves by knowing whether they retired, resigned or were fired. You could implement a RemovePlayer method that takes an appropriate input enum. However, by inheriting from List, you would be unable to prevent direct access to Remove, RemoveAll and even Clear. As a result, you've actually disempowered your FootballTeam class.


Additional thoughts on encapsulation... You raised the following concern:

It makes my code needlessly verbose. I must now call my_team.Players.Count instead of just my_team.Count.

You're correct, that would be needlessly verbose for all clients to use you team. However, that problem is very small in comparison to the fact that you've exposed List Players to all and sundry so they can fiddle with your team without your consent.

You go on to say:

It just plain doesn't make any sense. A football team doesn't "have" a list of players. It is the list of players. You don't say "John McFootballer has joined SomeTeam's players". You say "John has joined SomeTeam".

You're wrong about the first bit: Drop the word 'list', and it's actually obvious that a team does have players.
However, you hit the nail on the head with the second. You don't want clients calling ateam.Players.Add(...). You do want them calling ateam.AddPlayer(...). And your implemention would (possibly amongst other things) call Players.Add(...) internally.


Hopefully you can see how important encapsulation is to the objective of empowering your objects. You want to allow each class to do its job well without fear of interference from other objects.

Spell Checker for Python

Maybe it is too late, but I am answering for future searches. TO perform spelling mistake correction, you first need to make sure the word is not absurd or from slang like, caaaar, amazzzing etc. with repeated alphabets. So, we first need to get rid of these alphabets. As we know in English language words usually have a maximum of 2 repeated alphabets, e.g., hello., so we remove the extra repetitions from the words first and then check them for spelling. For removing the extra alphabets, you can use Regular Expression module in Python.

Once this is done use Pyspellchecker library from Python for correcting spellings.

For implementation visit this link: https://rustyonrampage.github.io/text-mining/2017/11/28/spelling-correction-with-python-and-nltk.html

how to get the value of a textarea in jquery?

You can also get the value by element's name attribute.

var message = $("#formId textarea[name=message]").val();

Char Comparison in C

A char variable is actually an 8-bit integral value. It will have values from 0 to 255. These are ASCII codes. 0 stands for the C-null character, and 255 stands for an empty symbol.

So, when you write the following assignment:

char a = 'a'; 

It is the same thing as:

char a = 97;

So, you can compare two char variables using the >, <, ==, <=, >= operators:

char a = 'a';
char b = 'b';

if( a < b ) printf("%c is smaller than %c", a, b);
if( a > b ) printf("%c is smaller than %c", a, b);
if( a == b ) printf("%c is equal to %c", a, b);

Disabling swap files creation in vim

If you put set directory="" in your exrc file, you will turn off the swap file. However, doing so will disable recovery.

More info here.

Convert Promise to Observable

You can add a wrapper around promise functionality to return an Observable to observer.

  • Creating a Lazy Observable using defer() operator which allows you to create the Observable only when the Observer subscribes.
import { of, Observable, defer } from 'rxjs'; 
import { map } from 'rxjs/operators';


function getTodos$(): Observable<any> {
  return defer(()=>{
    return fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(json => {
        return json;
      })
  });
}

getTodos$().
 subscribe(
   (next)=>{
     console.log('Data is:', next);
   }
)

Drawing a dot on HTML5 canvas

If you are planning to draw a lot of pixel, it's a lot more efficient to use the image data of the canvas to do pixel drawing.

var canvas = document.getElementById("myCanvas");
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var ctx = canvas.getContext("2d");
var canvasData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);

// That's how you define the value of a pixel //
function drawPixel (x, y, r, g, b, a) {
    var index = (x + y * canvasWidth) * 4;

    canvasData.data[index + 0] = r;
    canvasData.data[index + 1] = g;
    canvasData.data[index + 2] = b;
    canvasData.data[index + 3] = a;
}

// That's how you update the canvas, so that your //
// modification are taken in consideration //
function updateCanvas() {
    ctx.putImageData(canvasData, 0, 0);
}

Then, you can use it in this way :

drawPixel(1, 1, 255, 0, 0, 255);
drawPixel(1, 2, 255, 0, 0, 255);
drawPixel(1, 3, 255, 0, 0, 255);
updateCanvas();

For more information, you can take a look at this Mozilla blog post : http://hacks.mozilla.org/2009/06/pushing-pixels-with-canvas/

Is there an easy way to return a string repeated X number of times?

public static class StringExtensions
{
    public static string Repeat(this string input, int count)
    {
        if (!string.IsNullOrEmpty(input))
        {
            StringBuilder builder = new StringBuilder(input.Length * count);

            for(int i = 0; i < count; i++) builder.Append(input);

            return builder.ToString();
        }

        return string.Empty;
    }
}

How to clear input buffer in C?

Short, portable and declared in stdio.h

stdin = freopen(NULL,"r",stdin);

Doesn't get hung in an infinite loop when there is nothing on stdin to flush like the following well know line:

while ((c = getchar()) != '\n' && c != EOF) { }

A little expensive so don't use it in a program that needs to repeatedly clear the buffer.

Stole from a coworker :)

json_decode returns NULL after webservice call

Try using json_encode on the string prior to using json_decode... idk if will work for you but it did for me... I'm using laravel 4 ajaxing through a route param.

$username = "{username: john}";
public function getAjaxSearchName($username)
{
    $username = json_encode($username);
    die(var_dump(json_decode($username, true)));
}

How I can delete in VIM all text from current line to end of file?

Just add another way , in normal mode , type ctrl+v then G, select the rest, then D, I don't think it is effective , you should do like @Ed Guiness, head -n 20 > filename in linux.

What is {this.props.children} and when you should use it?

props.children represents the content between the opening and the closing tags when invoking/rendering a component:

const Foo = props => (
  <div>
    <p>I'm {Foo.name}</p>
    <p>abc is: {props.abc}</p>

    <p>I have {props.children.length} children.</p>
    <p>They are: {props.children}.</p>
    <p>{Array.isArray(props.children) ? 'My kids are an array.' : ''}</p>
  </div>
);

const Baz = () => <span>{Baz.name} and</span>;
const Bar = () => <span> {Bar.name}</span>;

invoke/call/render Foo:

<Foo abc={123}>
  <Baz />
  <Bar />
</Foo>

props and props.children

Docker error: invalid reference format: repository name must be lowercase

A "reference" in docker is a pointer to an image. It may be an image name, an image ID, include a registry server in the name, use a sha256 tag to pin the image, and anything else that can be used to point to the image you want to run.

The invalid reference format error message means docker cannot convert the string you've provided to an image. This may be an invalid name, or it may be from a parsing error earlier in the docker run command line if that's how you run the image. With a compose file, if you expand a variable in the image name, that variable may not be expanding correctly.

With the docker run command line, this is often the result in not quoting parameters with spaces, and mistaking the order of the command line. The command line is ordered as:

docker ${args_to_docker} run ${args_to_run} image_ref ${cmd_to_exec}

The most common error in passing args to the run is a volume mapping expanding a path name that includes a space in it, and not quoting the path or escaping the space. E.g.

docker run -v $(pwd):/data image_ref

And the fix is as easy as:

docker run -v "$(pwd):/data" image_ref

How to access the local Django webserver from outside world

UPDATED 2020 TRY THIS WAY

python manage.py runserver yourIp:8000

ALLOWED_HOSTS = ["*"]

Not Equal to This OR That in Lua

Your problem stems from a misunderstanding of the or operator that is common to people learning programming languages like this. Yes, your immediate problem can be solved by writing x ~= 0 and x ~= 1, but I'll go into a little more detail about why your attempted solution doesn't work.

When you read x ~=(0 or 1) or x ~= 0 or 1 it's natural to parse this as you would the sentence "x is not equal to zero or one". In the ordinary understanding of that statement, "x" is the subject, "is not equal to" is the predicate or verb phrase, and "zero or one" is the object, a set of possibilities joined by a conjunction. You apply the subject with the verb to each item in the set.

However, Lua does not parse this based on the rules of English grammar, it parses it in binary comparisons of two elements based on its order of operations. Each operator has a precedence which determines the order in which it will be evaluated. or has a lower precedence than ~=, just as addition in mathematics has a lower precedence than multiplication. Everything has a lower precedence than parentheses.

As a result, when evaluating x ~=(0 or 1), the interpreter will first compute 0 or 1 (because of the parentheses) and then x ~= the result of the first computation, and in the second example, it will compute x ~= 0 and then apply the result of that computation to or 1.

The logical operator or "returns its first argument if this value is different from nil and false; otherwise, or returns its second argument". The relational operator ~= is the inverse of the equality operator ==; it returns true if its arguments are different types (x is a number, right?), and otherwise compares its arguments normally.

Using these rules, x ~=(0 or 1) will decompose to x ~= 0 (after applying the or operator) and this will return 'true' if x is anything other than 0, including 1, which is undesirable. The other form, x ~= 0 or 1 will first evaluate x ~= 0 (which may return true or false, depending on the value of x). Then, it will decompose to one of false or 1 or true or 1. In the first case, the statement will return 1, and in the second case, the statement will return true. Because control structures in Lua only consider nil and false to be false, and anything else to be true, this will always enter the if statement, which is not what you want either.

There is no way that you can use binary operators like those provided in programming languages to compare a single variable to a list of values. Instead, you need to compare the variable to each value one by one. There are a few ways to do this. The simplest way is to use De Morgan's laws to express the statement 'not one or zero' (which can't be evaluated with binary operators) as 'not one and not zero', which can trivially be written with binary operators:

if x ~= 1 and x ~= 0 then
    print( "X must be equal to 1 or 0" )
    return
end

Alternatively, you can use a loop to check these values:

local x_is_ok = false
for i = 0,1 do 
    if x == i then
        x_is_ok = true
    end
end
if not x_is_ok then
    print( "X must be equal to 1 or 0" )
    return
end

Finally, you could use relational operators to check a range and then test that x was an integer in the range (you don't want 0.5, right?)

if not (x >= 0 and x <= 1 and math.floor(x) == x) then
    print( "X must be equal to 1 or 0" )
    return
end

Note that I wrote x >= 0 and x <= 1. If you understood the above explanation, you should now be able to explain why I didn't write 0 <= x <= 1, and what this erroneous expression would return!

Interactive shell using Docker Compose

Using docker-compose, I found the easiest way to do this is to do a docker ps -a (after starting my containers with docker-compose up) and get the ID of the container I want to have an interactive shell in (let's call it xyz123).

Then it's a simple matter to execute docker exec -ti xyz123 /bin/bash

and voila, an interactive shell.

How to get certain commit from GitHub project

First, clone the repository using git, e.g. with:

git clone git://github.com/facebook/facebook-ios-sdk.git

That downloads the complete history of the repository, so you can switch to any version. Next, change into the newly cloned repository:

cd facebook-ios-sdk

... and use git checkout <COMMIT> to change to the right commit:

git checkout 91f25642453

That will give you a warning, since you're no longer on a branch, and have switched directly to a particular version. (This is known as "detached HEAD" state.) Since it sounds as if you only want to use this SDK, rather than actively develop it, this isn't something you need to worry about, unless you're interested in finding out more about how git works.

Import data.sql MySQL Docker Container

do docker cp file.sql <CONTAINER NAME>:/file.sql first

then docker exec -i <CONTAINER NAME> mysql -u user -p

then inside mysql container execute source \file.sql

eclipse won't start - no java virtual machine was found

I had same problem after updating java. Then I paste

-vm
C:\Program Files\Java\jre6\bin\javaw.exe

to show the path of javaw.exe in eclipse.ini file.

Hope this will help you.

What is a 'Closure'?

From Lua.org:

When a function is written enclosed in another function, it has full access to local variables from the enclosing function; this feature is called lexical scoping. Although that may sound obvious, it is not. Lexical scoping, plus first-class functions, is a powerful concept in a programming language, but few languages support that concept.

Creating a thumbnail from an uploaded image

UPDATE:

If you want to take advantage of Imagick (if it is installed on your server). Note: I didn't use Imagick's nature writeFile because I was having issues with it on my server. File put contents works just as well.

<?php
/**
 * 
 * Generate Thumbnail using Imagick class
 *  
 * @param string $img
 * @param string $width
 * @param string $height
 * @param int $quality
 * @return boolean on true
 * @throws Exception
 * @throws ImagickException
 */
function generateThumbnail($img, $width, $height, $quality = 90)
{
    if (is_file($img)) {
        $imagick = new Imagick(realpath($img));
        $imagick->setImageFormat('jpeg');
        $imagick->setImageCompression(Imagick::COMPRESSION_JPEG);
        $imagick->setImageCompressionQuality($quality);
        $imagick->thumbnailImage($width, $height, false, false);
        $filename_no_ext = reset(explode('.', $img));
        if (file_put_contents($filename_no_ext . '_thumb' . '.jpg', $imagick) === false) {
            throw new Exception("Could not put contents.");
        }
        return true;
    }
    else {
        throw new Exception("No valid image provided with {$img}.");
    }
}

// example usage
try {
    generateThumbnail('test.jpg', 100, 50, 65);
}
catch (ImagickException $e) {
    echo $e->getMessage();
}
catch (Exception $e) {
    echo $e->getMessage();
}
?>

I have been using this, just execute the function after you store the original image and use that location to create the thumbnail. Edit it to your liking...

function makeThumbnails($updir, $img, $id)
{
    $thumbnail_width = 134;
    $thumbnail_height = 189;
    $thumb_beforeword = "thumb";
    $arr_image_details = getimagesize("$updir" . $id . '_' . "$img"); // pass id to thumb name
    $original_width = $arr_image_details[0];
    $original_height = $arr_image_details[1];
    if ($original_width > $original_height) {
        $new_width = $thumbnail_width;
        $new_height = intval($original_height * $new_width / $original_width);
    } else {
        $new_height = $thumbnail_height;
        $new_width = intval($original_width * $new_height / $original_height);
    }
    $dest_x = intval(($thumbnail_width - $new_width) / 2);
    $dest_y = intval(($thumbnail_height - $new_height) / 2);
    if ($arr_image_details[2] == IMAGETYPE_GIF) {
        $imgt = "ImageGIF";
        $imgcreatefrom = "ImageCreateFromGIF";
    }
    if ($arr_image_details[2] == IMAGETYPE_JPEG) {
        $imgt = "ImageJPEG";
        $imgcreatefrom = "ImageCreateFromJPEG";
    }
    if ($arr_image_details[2] == IMAGETYPE_PNG) {
        $imgt = "ImagePNG";
        $imgcreatefrom = "ImageCreateFromPNG";
    }
    if ($imgt) {
        $old_image = $imgcreatefrom("$updir" . $id . '_' . "$img");
        $new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
        imagecopyresized($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
        $imgt($new_image, "$updir" . $id . '_' . "$thumb_beforeword" . "$img");
    }
}

The above function creates images with a uniform thumbnail size. If the image doesn't have the same dimensions as the specified thumbnail size (proportionally), it just has blackspace on the top and bottom.

Can't bind to 'ngForOf' since it isn't a known property of 'tr' (final release)

Things to remember:

When custom modules are used (modules other than AppModule) then it is necessary to import the common module in it.

yourmodule.module.ts

import { CommonModule } from '@angular/common';

@NgModule({
  imports: [
    CommonModule
  ],
  exports:[ ],
  declarations: []
})

How to add List<> to a List<> in asp.net

  1. Use Concat or Union extension methods. You have to make sure that you have this direction using System.Linq; in order to use LINQ extensions methods.

  2. Use the AddRange method.

Excel VBA Open workbook, perform actions, save as, close

After discussion posting updated answer:

Option Explicit
Sub test()

    Dim wk As String, yr As String
    Dim fname As String, fpath As String
    Dim owb As Workbook

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    wk = ComboBox1.Value
    yr = ComboBox2.Value
    fname = yr & "W" & wk
    fpath = "C:\Documents and Settings\jammil\Desktop\AutoFinance\ProjectControl\Data"

    On Error GoTo ErrorHandler
    Set owb = Application.Workbooks.Open(fpath & "\" & fname)

    'Do Some Stuff

    With owb
        .SaveAs fpath & Format(Date, "yyyymm") & "DB" & ".xlsx", 51
        .Close
    End With

    With Application
        .DisplayAlerts = True
        .ScreenUpdating = True
        .EnableEvents = True
    End With

Exit Sub
ErrorHandler: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then

Else: Call Clear

End Sub

Error Handling:

You could try something like this to catch a specific error:

    On Error Resume Next
    Set owb = Application.Workbooks.Open(fpath & "\" & fname)
    If Err.Number = 1004 Then
    GoTo FileNotFound
    Else
    End If

    ...
    Exit Sub
    FileNotFound: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then

    Else: Call Clear

Create an Oracle function that returns a table

  CREATE OR REPLACE PACKAGE BODY TEST AS 

   FUNCTION GET_UPS(
   TIMESPAN_IN IN VARCHAR2 DEFAULT 'MONTLHY',
   STARTING_DATE_IN DATE,
   ENDING_DATE_IN DATE
   )RETURN MEASURE_TABLE IS

    T MEASURE_TABLE;

 BEGIN

    **SELECT   MEASURE_RECORD(L4_ID , L6_ID ,L8_ID ,YEAR ,
             PERIOD,VALUE )  BULK COLLECT  INTO    T
    FROM    ...**

  ;

   RETURN T;

   END GET_UPS;

END TEST;

VBScript - How to make program wait until process has finished?

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")
objWMIService.Create "notepad.exe", null, null, intProcessID
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colMonitoredProcesses = objWMIService.ExecNotificationQuery _
    ("Select * From __InstanceDeletionEvent Within 1 Where TargetInstance ISA 'Win32_Process'")
Do Until i = 1
    Set objLatestProcess = colMonitoredProcesses.NextEvent
    If objLatestProcess.TargetInstance.ProcessID = intProcessID Then
        i = 1
    End If
Loop
Wscript.Echo "Notepad has been terminated."

Cannot connect to MySQL 4.1+ using old authentication

you can do these line on your mysql query browser or something

SET old_passwords = 0;
UPDATE mysql.user SET Password = PASSWORD('testpass') WHERE User = 'testuser' limit 1;
SELECT LENGTH(Password) FROM mysql.user WHERE User = 'testuser';
FLUSH PRIVILEGES;

note:your username and password

after that it should able to work. I just solved mine too

Java 8, Streams to find the duplicate elements

My StreamEx library which enhances the Java 8 streams provides a special operation distinct(atLeast) which can retain only elements appearing at least the specified number of times. So your problem can be solved like this:

List<Integer> repeatingNumbers = StreamEx.of(numbers).distinct(2).toList();

Internally it's similar to @Dave solution, it counts objects, to support other wanted quantities and it's parallel-friendly (it uses ConcurrentHashMap for parallelized stream, but HashMap for sequential). For big amounts of data you can get a speed-up using .parallel().distinct(2).

Maximum Length of Command Line String

In Windows 10, it's still 8191 characters...at least on my machine.

It just cuts off any text after 8191 characters. Well, actually, I got 8196 characters, and after 8196, then it just won't let me type any more.

Here's a script that will test how long of a statement you can use. Well, assuming you have gawk/awk installed.

echo rem this is a test of how long of a line that a .cmd script can generate >testbat.bat
gawk 'BEGIN {printf "echo -----";for (i=10;i^<=100000;i +=10) printf "%%06d----",i;print;print "pause";}' >>testbat.bat
testbat.bat

Error: Cannot pull with rebase: You have unstaged changes

Pulling with rebase is a good practice in general.

However you cannot do that if your index is not clean, i.e. you have made changes that have not been committed.

You can do this to work around, assuming you want to keep your changes:

  1. stash your changes with: git stash
  2. pull from master with rebase
  3. reapply the changes you stashed in (1) with: git stash apply stash@{0} or the simpler git stash pop

Use own username/password with git and bitbucket

I figured I should share my solution, since I wasn't able to find it anywhere, and only figured it out through trial and error.

I indeed was able to transfer ownership of the repository to a team on BitBucket.

Don't add the remote URL that BitBuckets suggests:

git remote add origin https://[email protected]/teamName/repo.git

Instead, add the remote URL without your username:

git remote add origin https://bitbucket.org/teamName/repo.git

This way, when you go to pull from or push to a repo, it prompts you for your username, then for your password: everyone on the team has access to it under their own credentials. This approach only works with teams on BitBucket, even though you can manage user permissions on single-owner repos.

How to customize the back button on ActionBar

tray this:

getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close);

inside onCreate();

Closing JFrame with button click

JButton b3 = new JButton("CLOSE");

b3.setBounds(50, 375, 250, 50);

b3.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e)
    {
        System.exit(0);
    }
});

Subset and ggplot2

@agstudy's answer didn't work for me with the latest version of ggplot2, but this did, using maggritr pipes:

ggplot(data=dat)+ 
  geom_line(aes(Value1, Value2, group=ID, colour=ID),
                data = . %>% filter(ID %in% c("P1" , "P3")))

It works because if geom_line sees that data is a function, it will call that function with the inherited version of data and use the output of that function as data.

How to get the current date/time in Java

just try this code:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CurrentTimeDateCalendar {
    public static void getCurrentTimeUsingDate() {
        Date date = new Date();
        String strDateFormat = "hh:mm:ss a";
        DateFormat dateFormat = new SimpleDateFormat(strDateFormat);
        String formattedDate= dateFormat.format(date);
        System.out.println("Current time of the day using Date - 12 hour format: " + formattedDate);
    }
    public static void getCurrentTimeUsingCalendar() {
        Calendar cal = Calendar.getInstance();
        Date date=cal.getTime();
        DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        String formattedDate=dateFormat.format(date);
        System.out.println("Current time of the day using Calendar - 24 hour format: "+ formattedDate);
    }
}

which the sample output is:

Current time of the day using Date - 12 hour format: 11:13:01 PM

Current time of the day using Calendar - 24 hour format: 23:13:01

more information on:

Getting Current Date Time in Java

Get textarea text with javascript or Jquery

READING the <textarea>'s content:

var text1 = document.getElementById('myTextArea').value;     // plain JavaScript
var text2 = $("#myTextArea").val();                          // jQuery

WRITING to the <textarea>':

document.getElementById('myTextArea').value = 'new value';   // plain JavaScript
$("#myTextArea").val('new value');                           // jQuery

See DEMO JSFiddle here.


Do not use .html() or .innerHTML!

jQuery's .html() and JavaScript's .innerHTML should not be used, as they do not pick up changes to the textarea's text.

When the user types on the textarea, the .html() won't return the typed value, but the original one -- check demo fiddle above for an example.

Can an int be null in Java?

Since you ask for another way to accomplish your goal, I suggest you use a wrapper class:

new Integer(null);

How to link to a <div> on another page?

Create an anchor:

<a name="anchor" id="anchor"></a> 

then link to it:

<a href="http://server/page.html#anchor">Link text</a>

Change hash without reload in jQuery

You could try catching the onload event. And stopping the propagation dependent on some flag.

var changeHash = false;

$('ul.questions li a').click(function(event) {
    var $this = $(this)
    $('.tab').hide();  //you can improve the speed of this selector.
    $($this.attr('href')).fadeIn('slow');
    StopEvent(event);  //notice I've changed this
    changeHash = true;
    window.location.hash = $this.attr('href');
});

$(window).onload(function(event){
    if (changeHash){
        changeHash = false;
        StopEvent(event);
    }
}

function StopEvent(event){
    event.preventDefault();
    event.stopPropagation();
    if ($.browser.msie) {
        event.originalEvent.keyCode = 0;
        event.originalEvent.cancelBubble = true;
        event.originalEvent.returnValue = false;
    }
}

Not tested, so can't say if it would work

Remove HTML Tags from an NSString on the iPhone

Take a look at NSXMLParser. It's a SAX-style parser. You should be able to use it to detect tags or other unwanted elements in the XML document and ignore them, capturing only pure text.

Replace HTML page with contents retrieved via AJAX

try this with jQuery:

$('body').load( url,[data],[callback] );

Read more at docs.jquery.com / Ajax / load

How much overhead does SSL impose?

I second @erickson: The pure data-transfer speed penalty is negligible. Modern CPUs reach a crypto/AES throughput of several hundred MBit/s. So unless you are on resource constrained system (mobile phone) TLS/SSL is fast enough for slinging data around.

But keep in mind that encryption makes caching and load balancing much harder. This might result in a huge performance penalty.

But connection setup is really a show stopper for many application. On low bandwidth, high packet loss, high latency connections (mobile device in the countryside) the additional roundtrips required by TLS might render something slow into something unusable.

For example we had to drop the encryption requirement for access to some of our internal web apps - they where next to unusable if used from china.

CSS3 :unchecked pseudo-class

The way I handled this was switching the className of a label based on a condition. This way you only need one label and you can have different classes for different states... Hope that helps!

GridView Hide Column by code

If you wanna hide that column while grid populating, you can do it in aspx page itself like this

<asp:BoundField DataField="test" HeaderText="test" Visible="False" />

Define variable to use with IN operator (T-SQL)

slight improvement on @LukeH, there is no need to repeat the "INSERT INTO": and @realPT's answer - no need to have the SELECT:

DECLARE @MyList TABLE (Value INT) 
INSERT INTO @MyList VALUES (1),(2),(3),(4)

SELECT * FROM MyTable
WHERE MyColumn IN (SELECT Value FROM @MyList)

Selecting data from two different servers in SQL Server

Querying across 2 different databases is a distributed query. Here is a list of some techniques plus the pros and cons:

  1. Linked servers: Provide access to a wider variety of data sources than SQL Server replication provides
  2. Linked servers: Connect with data sources that replication does not support or which require ad hoc access
  3. Linked servers: Perform better than OPENDATASOURCE or OPENROWSET
  4. OPENDATASOURCE and OPENROWSET functions: Convenient for retrieving data from data sources on an ad hoc basis. OPENROWSET has BULK facilities as well that may/may not require a format file which might be fiddley
  5. OPENQUERY: Doesn't support variables
  6. All are T-SQL solutions. Relatively easy to implement and set up
  7. All are dependent on connection between source and destionation which might affect performance and scalability

Synchronously waiting for an async operation, and why does Wait() freeze the program here

With small custom synchronization context, sync function can wait for completion of async function, without creating deadlock. Here is small example for WinForms app.

Imports System.Threading
Imports System.Runtime.CompilerServices

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        SyncMethod()
    End Sub

    ' waiting inside Sync method for finishing async method
    Public Sub SyncMethod()
        Dim sc As New SC
        sc.WaitForTask(AsyncMethod())
        sc.Release()
    End Sub

    Public Async Function AsyncMethod() As Task(Of Boolean)
        Await Task.Delay(1000)
        Return True
    End Function

End Class

Public Class SC
    Inherits SynchronizationContext

    Dim OldContext As SynchronizationContext
    Dim ContextThread As Thread

    Sub New()
        OldContext = SynchronizationContext.Current
        ContextThread = Thread.CurrentThread
        SynchronizationContext.SetSynchronizationContext(Me)
    End Sub

    Dim DataAcquired As New Object
    Dim WorkWaitingCount As Long = 0
    Dim ExtProc As SendOrPostCallback
    Dim ExtProcArg As Object

    <MethodImpl(MethodImplOptions.Synchronized)>
    Public Overrides Sub Post(d As SendOrPostCallback, state As Object)
        Interlocked.Increment(WorkWaitingCount)
        Monitor.Enter(DataAcquired)
        ExtProc = d
        ExtProcArg = state
        AwakeThread()
        Monitor.Wait(DataAcquired)
        Monitor.Exit(DataAcquired)
    End Sub

    Dim ThreadSleep As Long = 0

    Private Sub AwakeThread()
        If Interlocked.Read(ThreadSleep) > 0 Then ContextThread.Resume()
    End Sub

    Public Sub WaitForTask(Tsk As Task)
        Dim aw = Tsk.GetAwaiter

        If aw.IsCompleted Then Exit Sub

        While Interlocked.Read(WorkWaitingCount) > 0 Or aw.IsCompleted = False
            If Interlocked.Read(WorkWaitingCount) = 0 Then
                Interlocked.Increment(ThreadSleep)
                ContextThread.Suspend()
                Interlocked.Decrement(ThreadSleep)
            Else
                Interlocked.Decrement(WorkWaitingCount)
                Monitor.Enter(DataAcquired)
                Dim Proc = ExtProc
                Dim ProcArg = ExtProcArg
                Monitor.Pulse(DataAcquired)
                Monitor.Exit(DataAcquired)
                Proc(ProcArg)
            End If
        End While

    End Sub

     Public Sub Release()
         SynchronizationContext.SetSynchronizationContext(OldContext)
     End Sub

End Class

How to set text color in submit button?

.btn{
    font-size: 20px;
    color:black;
}

Setting up a cron job in Windows

  1. Make sure you logged on as an administrator or you have the same access as an administrator.
  2. Start->Control Panel->System and Security->Administrative Tools->Task Scheduler
  3. Action->Create Basic Task->Type a name and Click Next
  4. Follow through the wizard.

How do you make websites with Java?

Look into creating Applets if you want to make a website with Java. You most likely wont need to use anything but regular Java, unless you want something more specialized.

Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

If it is a windows system, then it may be because you are using 32 bit winpcap library in a 64 bit pc or vie versa. If it is a 64 bit pc then copy the winpcap library and header packet.lib and wpcap.lib from winpcap/lib/x64 to the winpcap/lib directory and overwrite the existing

What is a good practice to check if an environmental variable exists or not?

To be on the safe side use

os.getenv('FOO') or 'bar'

A corner case with the above answers is when the environment variable is set but is empty

For this special case you get

print(os.getenv('FOO', 'bar'))
# prints new line - though you expected `bar`

or

if "FOO" in os.environ:
    print("FOO is here")
# prints FOO is here - however its not

To avoid this just use or

os.getenv('FOO') or 'bar'

Then you get

print(os.getenv('FOO') or 'bar')
# bar

When do we have empty environment variables?

You forgot to set the value in the .env file

# .env
FOO=

or exported as

$ export FOO=

or forgot to set it in settings.py

# settings.py
os.environ['FOO'] = ''

Update: if in doubt, check out these one-liners

>>> import os; os.environ['FOO'] = ''; print(os.getenv('FOO', 'bar'))

$ FOO= python -c "import os; print(os.getenv('FOO', 'bar'))"

Iterating on a file doesn't work the second time

Of course. That is normal and sane behaviour. Instead of closing and re-opening, you could rewind the file.

How to delete a file via PHP?

The following should help

  • realpath — Returns canonicalized absolute pathname
  • is_writable — Tells whether the filename is writable
  • unlink — Deletes a file

Run your filepath through realpath, then check if the returned path is writable and if so, unlink it.

jQuery limit to 2 decimal places

Here is a working example in both Javascript and jQuery:

http://jsfiddle.net/GuLYN/312/

//In jQuery
$("#calculate").click(function() {
    var num = parseFloat($("#textbox").val());
    var new_num = $("#textbox").val(num.toFixed(2));
});


// In javascript
document.getElementById('calculate').onclick = function() {
    var num = parseFloat(document.getElementById('textbox').value);
    var new_num = num.toFixed(2);
    document.getElementById('textbox').value = new_num;
};
?

How do I get the current mouse screen coordinates in WPF?

This works without having to use forms or import any DLLs:

   using System.Windows;
   using System.Windows.Input;

    /// <summary>
    /// Gets the current mouse position on screen
    /// </summary>
    private Point GetMousePosition()
    {
        // Position of the mouse relative to the window
        var position = Mouse.GetPosition(Window);

        // Add the window position
        return new Point(position.X + Window.Left, position.Y + Window.Top);
    }

Check for special characters (/*-+_@&$#%) in a string?

Use the regular Expression below in to validate a string to make sure it contains numbers, letters, or space only:

[a-zA-Z0-9 ]

number_format() with MySQL

http://blogs.mysql.com/peterg/2009/04/

In Mysql 6.1 you will be able to do FORMAT(X,D [,locale_name] )

As in

 SELECT format(1234567,2,’de_DE’);

For now this ability does not exist, though you MAY be able to set your locale in your database my.ini check it out.

How do I remove accents from characters in a PHP string?

If the main task is just to use the string in a URL, why not to use slugyfier?

composer require cocur/slugify

then

use Cocur\Slugify\Slugify;

$slugify = new Slugify();
echo $slugify->slugify('Fóø Bår');

It also has many bridges for popular frameworks. E.g. you can use Doctrine Extensions Sluggable behaviour to generate automatically unique slug for each entity in DB and use it in URL.

If you want just to wipe out all accents you can play around with rulesets to satisfy the requirements.

Difference between java.exe and javaw.exe

The difference is in the subsystem that each executable targets.

  • java.exe targets the CONSOLE subsystem.
  • javaw.exe targets the WINDOWS subsystem.

Aligning a float:left div to center?

try it like this:

  <div id="divContainer">
    <div class="divImageHolder">
    IMG HERE
    </div>
    <div class="divImageHolder">
    IMG HERE
    </div>
    <div class="divImageHolder">
    IMG HERE
    </div>
    <br class="clear" />
    </div>

    <style type="text/css">
    #divContainer { margin: 0 auto; width: 800px; }
    .divImageHolder { float:left; }
    .clear { clear:both; }
    </style>

'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?

Example 1:

This is how the and operator works.

x and y => if x is false, then x, else y

So in other words, since mylist1 is not False, the result of the expression is mylist2. (Only empty lists evaluate to False.)

Example 2:

The & operator is for a bitwise and, as you mention. Bitwise operations only work on numbers. The result of a & b is a number composed of 1s in bits that are 1 in both a and b. For example:

>>> 3 & 1
1

It's easier to see what's happening using a binary literal (same numbers as above):

>>> 0b0011 & 0b0001
0b0001

Bitwise operations are similar in concept to boolean (truth) operations, but they work only on bits.

So, given a couple statements about my car

  1. My car is red
  2. My car has wheels

The logical "and" of these two statements is:

(is my car red?) and (does car have wheels?) => logical true of false value

Both of which are true, for my car at least. So the value of the statement as a whole is logically true.

The bitwise "and" of these two statements is a little more nebulous:

(the numeric value of the statement 'my car is red') & (the numeric value of the statement 'my car has wheels') => number

If python knows how to convert the statements to numeric values, then it will do so and compute the bitwise-and of the two values. This may lead you to believe that & is interchangeable with and, but as with the above example they are different things. Also, for the objects that can't be converted, you'll just get a TypeError.

Example 3 and 4:

Numpy implements arithmetic operations for arrays:

Arithmetic and comparison operations on ndarrays are defined as element-wise operations, and generally yield ndarray objects as results.

But does not implement logical operations for arrays, because you can't overload logical operators in python. That's why example three doesn't work, but example four does.

So to answer your and vs & question: Use and.

The bitwise operations are used for examining the structure of a number (which bits are set, which bits aren't set). This kind of information is mostly used in low-level operating system interfaces (unix permission bits, for example). Most python programs won't need to know that.

The logical operations (and, or, not), however, are used all the time.

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

Even when you asked finally for the opposite, to reform 0s and 1s into Trues and Falses, however, I post an answer about how to transform falses and trues into ones and zeros (1s and 0s), for a whole dataframe, in a single line.

Example given

df <- structure(list(p1_1 = c(TRUE, FALSE, FALSE, NA, TRUE, FALSE, 
                NA), p1_2 = c(FALSE, TRUE, FALSE, NA, FALSE, NA, 
                TRUE), p1_3 = c(TRUE, 
                TRUE, FALSE, NA, NA, FALSE, TRUE), p1_4 = c(FALSE, NA, 
                FALSE,  FALSE, TRUE, FALSE, NA), p1_5 = c(TRUE, NA, 
                FALSE, TRUE, FALSE, NA, TRUE), p1_6 = c(TRUE, NA, 
                FALSE, TRUE, FALSE, NA, TRUE), p1_7 = c(TRUE, NA, 
                FALSE, TRUE, NA, FALSE, TRUE), p1_8 = c(FALSE, 
                FALSE, NA, FALSE, TRUE, FALSE, NA), p1_9 = c(TRUE, 
                FALSE,  NA, FALSE, FALSE, NA, TRUE), p1_10 = c(TRUE, 
                FALSE, NA, FALSE, FALSE, NA, TRUE), p1_11 = c(FALSE, 
                FALSE, NA, FALSE, NA, FALSE, TRUE)), .Names = 
                c("p1_1", "p1_2", "p1_3", "p1_4", "p1_5", "p1_6", 
                "p1_7", "p1_8", "p1_9", "p1_10", "p1_11"), row.names = 
                 c(NA, -7L), class = "data.frame")

   p1_1  p1_2  p1_3  p1_4  p1_5  p1_6  p1_7  p1_8  p1_9 p1_10 p1_11
1  TRUE FALSE  TRUE FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE FALSE
2 FALSE  TRUE  TRUE    NA    NA    NA    NA FALSE FALSE FALSE FALSE
3 FALSE FALSE FALSE FALSE FALSE FALSE FALSE    NA    NA    NA    NA
4    NA    NA    NA FALSE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE
5  TRUE FALSE    NA  TRUE FALSE FALSE    NA  TRUE FALSE FALSE    NA
6 FALSE    NA FALSE FALSE    NA    NA FALSE FALSE    NA    NA FALSE
7    NA  TRUE  TRUE    NA  TRUE  TRUE  TRUE    NA  TRUE  TRUE  TRUE

Then by running that: df * 1 all Falses and Trues are trasnformed into 1s and 0s. At least, this was happen in the R version that I have (R version 3.4.4 (2018-03-15) ).

> df*1
  p1_1 p1_2 p1_3 p1_4 p1_5 p1_6 p1_7 p1_8 p1_9 p1_10 p1_11
1    1    0    1    0    1    1    1    0    1     1     0
2    0    1    1   NA   NA   NA   NA    0    0     0     0
3    0    0    0    0    0    0    0   NA   NA    NA    NA
4   NA   NA   NA    0    1    1    1    0    0     0     0
5    1    0   NA    1    0    0   NA    1    0     0    NA
6    0   NA    0    0   NA   NA    0    0   NA    NA     0
7   NA    1    1   NA    1    1    1   NA    1     1     1

I do not know if it a total "safe" command, under all different conditions / dfs.

How can one create an overlay in css?

I'm late to the party, but if you want to do this to an arbitrary element using only CSS, without messing around with positioning, overlay divs etc., you can use an inset box shadow:

box-shadow: inset 0px 0px 0 2000px rgba(0,0,0,0.5);

This will work on any element smaller than 4000 pixels long or wide.

example: http://jsfiddle.net/jTwPc/

Extracting Path from OpenFileDialog path/filename

Use the Path class from System.IO. It contains useful calls for manipulating file paths, including GetDirectoryName which does what you want, returning the directory portion of the file path.

Usage is simple.

string directoryPath = Path.GetDirectoryName(filePath);

How to convert unsigned long to string

you can write a function which converts from unsigned long to str, similar to ltostr library function.

char *ultostr(unsigned long value, char *ptr, int base)
{
  unsigned long t = 0, res = 0;
  unsigned long tmp = value;
  int count = 0;

  if (NULL == ptr)
  {
    return NULL;
  }

  if (tmp == 0)
  {
    count++;
  }

  while(tmp > 0)
  {
    tmp = tmp/base;
    count++;
  }

  ptr += count;

  *ptr = '\0';

  do
  {
    res = value - base * (t = value / base);
    if (res < 10)
    {
      * -- ptr = '0' + res;
    }
    else if ((res >= 10) && (res < 16))
    {
        * --ptr = 'A' - 10 + res;
    }
  } while ((value = t) != 0);

  return(ptr);
}

you can refer to my blog here which explains implementation and usage with example.

Getting a HeadlessException: No X11 DISPLAY variable was set

Problem statement – Getting java.awt.HeadlessException while trying to initialize java.awt.Component from the application as the tomcat environment does not have any head(terminal).

Issue – The linux virtual environment was setup without a virtual display terminal. Tried to install virtual display – Xvfb, but Xvfb has been taken off by the redhat community.

Solution – Installed ‘xorg-x11-drv-vmware.x86_64’ using yum install xorg-x11-drv-vmware.x86_64 and executed startx. Finally set the display to :0.0 using export DISPLAY=:0.0 and then executed xhost +

Adding new files to a subversion repository

To add a new file in SVN

svn add file_name
svn commit -m "text about changes..."

To add a new file in a directory in SVN

svn add directory_name/file_name
svn commit -m "text about changes"

To add all new files in a directory with some targets (files) are already versioned (added):

svn add directory_name/*
svn commit -m "text about changes"

Length of string in bash

I wanted the simplest case, finally this is a result:

echo -n 'Tell me the length of this sentence.' | wc -m;
36

Underline text in UIlabel

Here is the easiest solution which works for me without writing additional codes.

// To underline text in UILable
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"Type your text here"];
[text addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(0, text.length)];
lblText.attributedText = text;

Python: import cx_Oracle ImportError: No module named cx_Oracle error is thown

Unknown92 answer helped me (on windows). Note that all versions must fit.

I've downloaded cx_Oracle here, for me the file cx_Oracle-5.2.1-12c.win-amd64-py3.5.exe worked with:

  • Python 3.5.1 64bit. for some reason the default download link from the main page is for the 32bit version.
  • And oracle instance client 12.1.0.2.0 (the file named instantclient-basic-windows.x64-12.1.0.2.0.zip) here.

String comparison technique used by Python

Python and just about every other computer language use the same principles as (I hope) you would use when finding a word in a printed dictionary:

(1) Depending on the human language involved, you have a notion of character ordering: 'a' < 'b' < 'c' etc

(2) First character has more weight than second character: 'az' < 'za' (whether the language is written left-to-right or right-to-left or boustrophedon is quite irrelevant)

(3) If you run out of characters to test, the shorter string is less than the longer string: 'foo' < 'food'

Typically, in a computer language the "notion of character ordering" is rather primitive: each character has a human-language-independent number ord(character) and characters are compared and sorted using that number. Often that ordering is not appropriate to the human language of the user, and then you need to get into "collating", a fun topic.

How to get the pure text without HTML element using JavaScript?

Try (short version of Gabi answer idea)

function get_content() {
   txt.innerHTML = txt.textContent;
}

_x000D_
_x000D_
function get_content() {_x000D_
   txt.innerHTML = txt.textContent ;_x000D_
}
_x000D_
span { background: #fbb}
_x000D_
<input type="button" onclick="get_content()" value="Get Content"/>_x000D_
<p id='txt'>_x000D_
<span class="A">I am</span>_x000D_
<span class="B">working in </span>_x000D_
<span class="C">ABC company.</span>_x000D_
</p>
_x000D_
_x000D_
_x000D_

TypeError: argument of type 'NoneType' is not iterable

If a function does not return anything, e.g.:

def test():
    pass

it has an implicit return value of None.

Thus, as your pick* methods do not return anything, e.g.:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")

the lines that call them, e.g.:

word = pickEasy()

set word to None, so wordInput in getInput is None. This means that:

if guess in wordInput:

is the equivalent of:

if guess in None:

and None is an instance of NoneType which does not provide iterator/iteration functionality, so you get that type error.

The fix is to add the return type:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")
    return word

How to capitalize the first character of each word in a string

public void capitaliseFirstLetterOfEachWord()
{
    String value="this will capitalise first character of each word of this string";
    String[] wordSplit=value.split(" ");
    StringBuilder sb=new StringBuilder();

    for (int i=0;i<wordSplit.length;i++){

        sb.append(wordSplit[i].substring(0,1).toUpperCase().
                concat(wordSplit[i].substring(1)).concat(" "));
    }
    System.out.println(sb);
}

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

Looks like you have a query that is taking longer than it should. From your stack trace and your code you should be able to determine exactly what query that is.

This type of timeout can have three causes;

  1. There's a deadlock somewhere
  2. The database's statistics and/or query plan cache are incorrect
  3. The query is too complex and needs to be tuned

A deadlock can be difficult to fix, but it's easy to determine whether that is the case. Connect to your database with Sql Server Management Studio. In the left pane right-click on the server node and select Activity Monitor. Take a look at the running processes. Normally most will be idle or running. When the problem occurs you can identify any blocked process by the process state. If you right-click on the process and select details it'll show you the last query executed by the process.

The second issue will cause the database to use a sub-optimal query plan. It can be resolved by clearing the statistics:

exec sp_updatestats

If that doesn't work you could also try

dbcc freeproccache

You should not do this when your server is under heavy load because it will temporarily incur a big performace hit as all stored procs and queries are recompiled when first executed. However, since you state the issue occurs sometimes, and the stack trace indicates your application is starting up, I think you're running a query that is only run on occasionally. You may be better off by forcing SQL Server not to reuse a previous query plan. See this answer for details on how to do that.

I've already touched on the third issue, but you can easily determine whether the query needs tuning by executing the query manually, for example using Sql Server Management Studio. If the query takes too long to complete, even after resetting the statistics you'll probably need to tune it. For help with that, you should post the exact query in a new question.

Custom Listview Adapter with filter Android

Just an update.

If the ticked answer is working fine for you but it shows nothing when the search text is empty. Here is the solution:

private class ItemFilter extends Filter {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        
        String filterString = constraint.toString().toLowerCase();
        
        FilterResults results = new FilterResults();

        if(constraint.length() == 0)
        {
            results.count = originalData.size();
            results.values = originalData;
        }else {

        
        final List<String> list = originalData;

        int count = list.size();
        final ArrayList<String> nlist = new ArrayList<String>(count);

        String filterableString ;
        
        for (int i = 0; i < count; i++) {
            filterableString = list.get(i);
            if (filterableString.toLowerCase().contains(filterString)) {
                nlist.add(filterableString);
            }
        }
        
        results.values = nlist;
        results.count = nlist.size();
     }
        return results;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        filteredData = (ArrayList<String>) results.values;
        notifyDataSetChanged();
      }

   }

For any query comment below

Why am I getting a "401 Unauthorized" error in Maven?

In Nexus version 3.13.0-01, the id in the POM's distributionManagement/repository section MUST match the servers/server/id and mirrors/mirror/id in your maven settings.xml. I just replaced nexus v3.10.4 (with 3.13.0-01) and it wasn't needed to match for 3.10.4.