Programs & Examples On #Multibyte

PHP (mbstring) provides multibyte specific string functions that help you deal with multibyte encodings

Difference between CLOB and BLOB from DB2 and Oracle Perspective?

BLOB is for binary data (videos, images, documents, other)

CLOB is for large text data (text)

Maximum size on MySQL 2GB

Maximum size on Oracle 128TB

Fatal error: Call to undefined function pg_connect()

On Gentoo, use USE flag postgres in /etc/portage/make.conf and re emerge "emerge php"

Convert char * to LPWSTR

The clean way to use mbstowcs is to call it twice to find the length of the result:

  const char * cs = <your input char*>
  size_t wn = mbsrtowcs(NULL, &cs, 0, NULL);

  // error if wn == size_t(-1)

  wchar_t * buf = new wchar_t[wn + 1]();  // value-initialize to 0 (see below)

  wn = mbsrtowcs(buf, &cs, wn + 1, NULL);

  // error if wn == size_t(-1)

  assert(cs == NULL); // successful conversion

  // result now in buf, return e.g. as std::wstring

  delete[] buf;

Don't forget to call setlocale(LC_CTYPE, ""); at the beginning of your program!

The advantage over the Windows MultiByteToWideChar is that this is entirely standard C, although on Windows you might prefer the Windows API function anyway.

I usually wrap this method, along with the opposite one, in two conversion functions string->wstring and wstring->string. If you also add trivial overloads string->string and wstring->wstring, you can easily write code that compiles with the Winapi TCHAR typedef in any setting.

[Edit:] I added zero-initialization to buf, in case you plan to use the C array directly. I would usually return the result as std::wstring(buf, wn), though, but do beware if you plan on using C-style null-terminated arrays.[/]

In a multithreaded environment you should pass a thread-local conversion state to the function as its final (currently invisible) parameter.

Here is a small rant of mine on this topic.

BSTR to std::string (std::wstring) and vice versa

Simply pass the BSTR directly to the wstring constructor, it is compatible with a wchar_t*:

BSTR btest = SysAllocString(L"Test");
assert(btest != NULL);
std::wstring wtest(btest);
assert(0 == wcscmp(wtest.c_str(), btest));

Converting BSTR to std::string requires a conversion to char* first. That's lossy since BSTR stores a utf-16 encoded Unicode string. Unless you want to encode in utf-8. You'll find helper methods to do this, as well as manipulate the resulting string, in the ICU library.

R: invalid multibyte string

I had a similarly strange problem with a file from the program e-prime (edat -> SPSS conversion), but then I discovered that there are many additional encodings you can use. this did the trick for me:

tbl <- read.delim("dir/file.txt", fileEncoding="UCS-2LE")

Finding and removing non ascii characters from an Oracle Varchar2

There's probably a more direct way using regular expressions. With luck, somebody else will provide it. But here's what I'd do without needing to go to the manuals.

Create a PLSQL function to receive your input string and return a varchar2.

In the PLSQL function, do an asciistr() of your input. The PLSQL is because that may return a string longer than 4000 and you have 32K available for varchar2 in PLSQL.

That function converts the non-ASCII characters to \xxxx notation. So you can use regular expressions to find and remove those. Then return the result.

MySQL "incorrect string value" error when save unicode string in Django

None of these answers solved the problem for me. The root cause being:

You cannot store 4-byte characters in MySQL with the utf-8 character set.

MySQL has a 3 byte limit on utf-8 characters (yes, it's wack, nicely summed up by a Django developer here)

To solve this you need to:

  1. Change your MySQL database, table and columns to use the utf8mb4 character set (only available from MySQL 5.5 onwards)
  2. Specify the charset in your Django settings file as below:

settings.py

DATABASES = {
    'default': {
        'ENGINE':'django.db.backends.mysql',
        ...
        'OPTIONS': {'charset': 'utf8mb4'},
    }
}

Note: When recreating your database you may run into the 'Specified key was too long' issue.

The most likely cause is a CharField which has a max_length of 255 and some kind of index on it (e.g. unique). Because utf8mb4 uses 33% more space than utf-8 you'll need to make these fields 33% smaller.

In this case, change the max_length from 255 to 191.

Alternatively you can edit your MySQL configuration to remove this restriction but not without some django hackery

UPDATE: I just ran into this issue again and ended up switching to PostgreSQL because I was unable to reduce my VARCHAR to 191 characters.

How to get size in bytes of a CLOB column in Oracle?

Check the LOB segment name from dba_lobs using the table name.

select TABLE_NAME,OWNER,COLUMN_NAME,SEGMENT_NAME from dba_lobs where TABLE_NAME='<<TABLE NAME>>';

Now use the segment name to find the bytes used in dba_segments.

select s.segment_name, s.partition_name, bytes/1048576 "Size (MB)"
from dba_segments s, dba_lobs l
where s.segment_name = l.segment_name
and s.owner = '<< OWNER >> ' order by s.segment_name, s.partition_name;

invalid multibyte char (US-ASCII) with Rails and Ruby 1.9

Have you tried adding a magic comment in the script where you use non-ASCII chars? It should go on top of the script.

#!/bin/env ruby
# encoding: utf-8

It worked for me like a charm.

How do you properly use WideCharToMultiByte

You use the lpMultiByteStr [out] parameter by creating a new char array. You then pass this char array in to get it filled. You only need to initialize the length of the string + 1 so that you can have a null terminated string after the conversion.

Here are a couple of useful helper functions for you, they show the usage of all parameters.

#include <string>

std::string wstrtostr(const std::wstring &wstr)
{
    // Convert a Unicode string to an ASCII string
    std::string strTo;
    char *szTo = new char[wstr.length() + 1];
    szTo[wstr.size()] = '\0';
    WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, szTo, (int)wstr.length(), NULL, NULL);
    strTo = szTo;
    delete[] szTo;
    return strTo;
}

std::wstring strtowstr(const std::string &str)
{
    // Convert an ASCII string to a Unicode String
    std::wstring wstrTo;
    wchar_t *wszTo = new wchar_t[str.length() + 1];
    wszTo[str.size()] = L'\0';
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, wszTo, (int)str.length());
    wstrTo = wszTo;
    delete[] wszTo;
    return wstrTo;
}

--

Anytime in documentation when you see that it has a parameter which is a pointer to a type, and they tell you it is an out variable, you will want to create that type, and then pass in a pointer to it. The function will use that pointer to fill your variable.

So you can understand this better:

//pX is an out parameter, it fills your variable with 10.
void fillXWith10(int *pX)
{
  *pX = 10;
}

int main(int argc, char ** argv)
{
  int X;
  fillXWith10(&X);
  return 0;
}

What is the difference between varchar and nvarchar?

My two cents

  1. Indexes can fail when not using the correct datatypes:
    In SQL Server: When you have an index over a VARCHAR column and present it a Unicode String, SQL Server does not make use of the index. The same thing happens when you present a BigInt to a indexed-column containing SmallInt. Even if the BigInt is small enough to be a SmallInt, SQL Server is not able to use the index. The other way around you do not have this problem (when providing SmallInt or Ansi-Code to an indexed BigInt ot NVARCHAR column).

  2. Datatypes can vary between different DBMS's (DataBase Management System):
    Know that every database has slightly different datatypes and VARCHAR does not means the same everywhere. While SQL Server has VARCHAR and NVARCHAR, an Apache/Derby database has only VARCHAR and there VARCHAR is in Unicode.

Publish to IIS, setting Environment Variable

I have my web applications (PRODUCTION, STAGING, TEST) hosted on IIS web server. So it was not possible to rely on ASPNETCORE_ENVIRONMENT operative's system enviroment variable, because setting it to a specific value (for example STAGING) has effect on others applications.

As work-around, I defined a custom file (envsettings.json) within my visualstudio solution:

enter image description here

with following content:

{
  // Possible string values reported below. When empty it use ENV variable value or Visual Studio setting.
  // - Production
  // - Staging
  // - Test
  // - Development
  "ASPNETCORE_ENVIRONMENT": ""
}

Then, based on my application type (Production, Staging or Test) I set this file accordly: supposing I am deploying TEST application, i will have:

"ASPNETCORE_ENVIRONMENT": "Test"

After that, in Program.cs file just retrieve this value and then set the webHostBuilder's enviroment:

    public class Program
    {
        public static void Main(string[] args)
        {
            var currentDirectoryPath = Directory.GetCurrentDirectory();
            var envSettingsPath = Path.Combine(currentDirectoryPath, "envsettings.json");
            var envSettings = JObject.Parse(File.ReadAllText(envSettingsPath));
            var enviromentValue = envSettings["ASPNETCORE_ENVIRONMENT"].ToString();

            var webHostBuilder = new WebHostBuilder()
                .UseKestrel()
                .CaptureStartupErrors(true)
                .UseSetting("detailedErrors", "true")
                .UseContentRoot(currentDirectoryPath)
                .UseIISIntegration()
                .UseStartup<Startup>();

            // If none is set it use Operative System hosting enviroment
            if (!string.IsNullOrWhiteSpace(enviromentValue)) 
            { 
                webHostBuilder.UseEnvironment(enviromentValue);
            }

            var host = webHostBuilder.Build();

            host.Run();
        }
    }

Remember to include the envsettings.json in the publishOptions (project.json):

  "publishOptions":
  {
    "include":
    [
      "wwwroot",
      "Views",
      "Areas/**/Views",
      "envsettings.json",
      "appsettings.json",
      "appsettings*.json",
      "web.config"
    ]
  },

This solution make me free to have ASP.NET CORE application hosted on same IIS, independently from envoroment variable value.

How to check if character is a letter in Javascript?

if( char.toUpperCase() != char.toLowerCase() ) 

Will return true only in case of letter

As point out in below comment, if your character is non English, High Ascii or double byte range then you need to add check for code point.

if( char.toUpperCase() != char.toLowerCase() || char.codePointAt(0) > 127 )

How to amend a commit without changing commit message (reusing the previous one)?

Using the accepted answer to create an alias

 oops = "!f(){ \
    git add -A; \
    if [ \"$1\" == '' ]; then \
        git commit --amend --no-edit; \
    else \
        git commit --amend \"$@\"; \
    fi;\
}; f"

then you can do

git oops

and it will add everything, and amend using the same message

or

git oops -m "new message"

to amend replacing the message

Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

Time::Piece::datetime() can eliminate T.

use Time::Piece;
print localtime->datetime(T => q{ });

How to use Visual Studio C++ Compiler?

In Visual Studio, you can't just open a .cpp file and expect it to run. You must create a project first, or open the .cpp in some existing project.

In your case, there is no project, so there is no project to build.

Go to File --> New --> Project --> Visual C++ --> Win32 Console Application. You can uncheck "create a directory for solution". On the next page, be sure to check "Empty project".

Then, You can add .cpp files you created outside the Visual Studio by right clicking in the Solution explorer on folder icon "Source" and Add->Existing Item.

Obviously You can create new .cpp this way too (Add --> New). The .cpp file will be created in your project directory.

Then you can press ctrl+F5 to compile without debugging and can see output on console window.

Extracting hours from a DateTime (SQL Server 2005)

try this one too:

   DATEPART(HOUR,GETDATE()) 

How to use Greek symbols in ggplot2?

Use expression(delta) where 'delta' for lowercase d and 'Delta' to get capital ?.

Here's full list of Greek characters:

? a alpha
? ß beta
G ? gamma
? d delta
? e epsilon
? ? zeta
? ? eta
T ? theta
? ? iota
? ? kappa
? ? lambda
? µ mu
? ? nu
? ? xi
? ? omicron
? p pi
? ? rho
S s sigma
? t tau
? ? upsilon
F f phi
? ? chi
? ? psi
O ? omega

EDIT: Copied from comments, when using in conjunction with other words use like: expression(Delta*"price")

How to call a PHP file from HTML or Javascript

As you have already stated in your question you have more than one option. A very basic approach would be using the tag referencing your PHP file in the method attribute. However as esoteric as it may sound AJAX is a more complete approach. Considering that an AJAX call (in combination with jQuery) can be as simple as:

$.post("yourfile.php", {data : "This can be as long as you want"});

And you get a more flexible solution, for example triggering a function after the server request is completed. Hope this helps.

Where should my npm modules be installed on Mac OS X?

npm root -g

to check the npm_modules global location

VBA vlookup reference in different sheet

The answer your question: the correct way to refer to a different sheet is by appropriately qualifying each Range you use. Please read this explanation and its conclusion, which I guess will give essential information.

The error you are getting is likely due to the sought-for value Sheet2!D2 not being found in the searched range Sheet1!A1:A65536. This may stem from two cases:

  1. The value is actually not present (pointed out by chris nielsen).

  2. You are searching the wrong Range. If the ActiveSheet is Sheet1, then using Range("D2") without qualifying it will be searching for Sheet1!D2, and it will throw the same error even if the sought-for value is present in the correct Range. Code accounting for this (and items below) follows:

    Sub srch()
        Dim ws1 As Worksheet, ws2 As Worksheet
        Dim srchres As Variant
    
        Set ws1 = Worksheets("Sheet1")
        Set ws2 = Worksheets("Sheet2")
    
        On Error Resume Next
        srchres = Application.WorksheetFunction.VLookup(ws2.Range("D2"), ws1.Range("A1:C65536"), 1, False)
        On Error GoTo 0
        If (IsEmpty(srchres)) Then
          ws2.Range("E2").Formula = CVErr(xlErrNA) ' Use whatever you want
        Else
          ws2.Range("E2").Value = srchres
        End If
    End Sub
    

I will point out a few additional notable points:

  1. Catching the error as done by chris nielsen is a good practice, probably mandatory if using Application.WorksheetFunction.VLookup (although it will not suitably handle case 2 above).

  2. This catching is actually performed by the function VLOOKUP as entered in a cell (and, if the sought-for value is not found, the result of the error is presented as #N/A in the result). That is why the first soluton by L42 does not need any extra error handling (it is taken care by =VLOOKUP...).

  3. Using =VLOOKUP... is fundamentally different from Application.WorksheetFunction.VLookup: the first leaves a formula, whose result may change if the cells referenced change; the second writes a fixed value.

  4. Both solutions by L42 qualify Ranges suitably.

  5. You are searching the first column of the range, and returning the value in that same column. Other functions are available for that (although yours works fine).

How to start a stopped Docker container with a different command?

I took @Dmitriusan's answer and made it into an alias:

alias docker-run-prev-container='prev_container_id="$(docker ps -aq | head -n1)" && docker commit "$prev_container_id" "prev_container/$prev_container_id" && docker run -it --entrypoint=bash "prev_container/$prev_container_id"'

Add this into your ~/.bashrc aliases file, and you'll have a nifty new docker-run-prev-container alias which'll drop you into a shell in the previous container.

Helpful for debugging failed docker builds.

Truncate a SQLite table if it exists?

After deleting I'm also using VACUUM command. So for full TRUNCATE equivalent I use this code:

DELETE FROM <table>;
UPDATE SQLITE_SEQUENCE SET seq = 0 WHERE name = '<table>';
VACUUM;

Deleting isn't working for me for reset Auto Increment

DELETE FROM "sqlite_sequence" WHERE "name"='<table>';

To read more about VACUUM you can go here: https://blogs.gnome.org/jnelson/2015/01/06/sqlite-vacuum-and-auto_vacuum/

How to overlay one div over another div

Here is a simple example to bring an overlay effect with a loading icon over another div.

<style>
    #overlay {
        position: absolute;
        width: 100%;
        height: 100%;
        background: black url('icons/loading.gif') center center no-repeat; /* Make sure the path and a fine named 'loading.gif' is there */
        background-size: 50px;
        z-index: 1;
        opacity: .6;
    }
    .wraper{
        position: relative;
        width:400px;  /* Just for testing, remove width and height if you have content inside this div */
        height:500px; /* Remove this if you have content inside */
    }
</style>

<h2>The overlay tester</h2>
<div class="wraper">
    <div id="overlay"></div>
    <h3>Apply the overlay over this div</h3>
</div>

Try it here: http://jsbin.com/fotozolucu/edit?html,css,output

How to check if number is divisible by a certain number?

n % x == 0

Means that n can be divided by x. So... for instance, in your case:

boolean isDivisibleBy20 = number % 20 == 0;

Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:

boolean even = (number & 1) == 0;
boolean odd  = (number & 1) != 0;

How to build PDF file from binary string returned from a web-service using javascript

I changed this:

var htmlText = '<embed width=100% height=100%'
                 + ' type="application/pdf"'
                 + ' src="data:application/pdf,'
                 + escape(pdfText)
                 + '"></embed>'; 

to

var htmlText = '<embed width=100% height=100%'
                 + ' type="application/pdf"'
                 + ' src="data:application/pdf;base64,'
                 + escape(pdfText)
                 + '"></embed>'; 

and it worked for me.

Set up an HTTP proxy to insert a header

You can also install Fiddler (http://www.fiddler2.com/fiddler2/) which is very easy to install (easier than Apache for example).

After launching it, it will register itself as system proxy. Then open the "Rules" menu, and choose "Customize Rules..." to open a JScript file which allow you to customize requests.

To add a custom header, just add a line in the OnBeforeRequest function:

oSession.oRequest.headers.Add("MyHeader", "MyValue");

ASP.Net MVC Redirect To A Different View

 if (true)
 {
   return View();
 }
 else
 {
   return View("another view name");
 }

SQL Server : converting varchar to INT

I would try triming the number to see what you get:

select len(rtrim(ltrim(userid))) from audit

if that return the correct value then just do:

select convert(int, rtrim(ltrim(userid))) from audit

if that doesn't return the correct value then I would do a replace to remove the empty space:

 select convert(int, replace(userid, char(0), '')) from audit

Android button onClickListener

This task can be accomplished using one of the android's main building block named as Intents and One of the methods public void startActivity (Intent intent) which belongs to your Activity class.

An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.

An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.

Refer the official docs -- http://developer.android.com/reference/android/content/Intent.html

public void startActivity (Intent intent) -- Used to launch a new activity.

So suppose you have two Activity class --

  1. PresentActivity -- This is your current activity from which you want to go the second activity.

  2. NextActivity -- This is your next Activity on which you want to move.

So the Intent would be like this

Intent(PresentActivity.this, NextActivity.class)

Finally this will be the complete code

public class PresentActivity extends Activity {
  protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    setContentView(R.layout.content_layout_id);

    final Button button = (Button) findViewById(R.id.button_id);
    button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
              // Perform action on click   
              Intent activityChangeIntent = new Intent(PresentActivity.this, NextActivity.class);

              // currentContext.startActivity(activityChangeIntent);

              PresentActivity.this.startActivity(activityChangeIntent);
            }
          });
  }
}

How to insert data into SQL Server

I think you lack to pass Connection object to your command object. and it is much better if you will use command and parameters for that.

using (SqlConnection connection = new SqlConnection("ConnectionStringHere"))
{
    using (SqlCommand command = new SqlCommand())
    {
        command.Connection = connection;            // <== lacking
        command.CommandType = CommandType.Text;
        command.CommandText = "INSERT into tbl_staff (staffName, userID, idDepartment) VALUES (@staffName, @userID, @idDepart)";
        command.Parameters.AddWithValue("@staffName", name);
        command.Parameters.AddWithValue("@userID", userId);
        command.Parameters.AddWithValue("@idDepart", idDepart);

        try
        {
            connection.Open();
            int recordsAffected = command.ExecuteNonQuery();
        }
        catch(SqlException)
        {
            // error here
        }
        finally
        {
            connection.Close();
        }
    }
}

Explain __dict__ attribute

Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes. Quoting from the documentation for __dict__

A dictionary or other mapping object used to store an object's (writable) attributes.

Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:

def func():
    pass

func.temp = 1

print(func.__dict__)

class TempClass:
    a = 1
    def temp_function(self):
        pass

print(TempClass.__dict__)

will output

{'temp': 1}
{'__module__': '__main__', 
 'a': 1, 
 'temp_function': <function TempClass.temp_function at 0x10a3a2950>, 
 '__dict__': <attribute '__dict__' of 'TempClass' objects>, 
 '__weakref__': <attribute '__weakref__' of 'TempClass' objects>, 
 '__doc__': None}

How to redirect stderr to null in cmd.exe

Your DOS command 2> nul

Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.

Count lines in large files

If your data resides on HDFS, perhaps the fastest approach is to use hadoop streaming. Apache Pig's COUNT UDF, operates on a bag, and therefore uses a single reducer to compute the number of rows. Instead you can manually set the number of reducers in a simple hadoop streaming script as follows:

$HADOOP_HOME/bin/hadoop jar $HADOOP_HOME/hadoop-streaming.jar -Dmapred.reduce.tasks=100 -input <input_path> -output <output_path> -mapper /bin/cat -reducer "wc -l"

Note that I manually set the number of reducers to 100, but you can tune this parameter. Once the map-reduce job is done, the result from each reducer is stored in a separate file. The final count of rows is the sum of numbers returned by all reducers. you can get the final count of rows as follows:

$HADOOP_HOME/bin/hadoop fs -cat <output_path>/* | paste -sd+ | bc

pandas resample documentation

There's more to it than this, but you're probably looking for this list:

B   business day frequency
C   custom business day frequency (experimental)
D   calendar day frequency
W   weekly frequency
M   month end frequency
BM  business month end frequency
MS  month start frequency
BMS business month start frequency
Q   quarter end frequency
BQ  business quarter endfrequency
QS  quarter start frequency
BQS business quarter start frequency
A   year end frequency
BA  business year end frequency
AS  year start frequency
BAS business year start frequency
H   hourly frequency
T   minutely frequency
S   secondly frequency
L   milliseconds
U   microseconds

Source: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases

Fastest way to convert an iterator to a list

@Robino was suggesting to add some tests which make sense, so here is a simple benchmark between 3 possible ways (maybe the most used ones) to convert an iterator to a list:

  1. by type constructor

list(my_iterator)

  1. by unpacking

[*my_iterator]

  1. using list comprehension

[e for e in my_iterator]

I have been using simple_bechmark library

from simple_benchmark import BenchmarkBuilder
from heapq import nsmallest

b = BenchmarkBuilder()

@b.add_function()
def convert_by_type_constructor(size):
    list(iter(range(size)))

@b.add_function()
def convert_by_list_comprehension(size):
    [e for e in iter(range(size))]

@b.add_function()
def convert_by_unpacking(size):
    [*iter(range(size))]


@b.add_arguments('Convert an iterator to a list')
def argument_provider():
    for exp in range(2, 22):
        size = 2**exp
        yield size, size

r = b.run()
r.plot()

enter image description here

As you can see there is very hard to make a difference between conversion by the constructor and conversion by unpacking, conversion by list comprehension is the “slowest” approach.


I have been testing also across different Python versions (3.6, 3.7, 3.8, 3.9) by using the following simple script:

import argparse
import timeit

parser = argparse.ArgumentParser(
    description='Test convert iterator to list')
parser.add_argument(
    '--size', help='The number of elements from iterator')

args = parser.parse_args()

size = int(args.size)
repeat_number = 10000

# do not wait too much if the size is too big
if size > 10000:
    repeat_number = 100


def test_convert_by_type_constructor():
    list(iter(range(size)))


def test_convert_by_list_comprehension():
    [e for e in iter(range(size))]


def test_convert_by_unpacking():
    [*iter(range(size))]


def get_avg_time_in_ms(func):
    avg_time = timeit.timeit(func, number=repeat_number) * 1000 / repeat_number
    return round(avg_time, 6)


funcs = [test_convert_by_type_constructor,
         test_convert_by_unpacking, test_convert_by_list_comprehension]

print(*map(get_avg_time_in_ms, funcs))

The script will be executed via a subprocess from a Jupyter Notebook (or a script), the size parameter will be passed through command-line arguments and the script results will be taken from standard output.

from subprocess import PIPE, run

import pandas

simple_data = {'constructor': [], 'unpacking': [], 'comprehension': [],
        'size': [], 'python version': []}


size_test = 100, 1000, 10_000, 100_000, 1_000_000
for version in ['3.6', '3.7', '3.8', '3.9']:
    print('test for python', version)
    for size in size_test:
        command = [f'python{version}', 'perf_test_convert_iterator.py', f'--size={size}']
        result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
        constructor, unpacking,  comprehension = result.stdout.split()
        
        simple_data['constructor'].append(float(constructor))
        simple_data['unpacking'].append(float(unpacking))
        simple_data['comprehension'].append(float(comprehension))
        simple_data['python version'].append(version)
        simple_data['size'].append(size)

df_ = pandas.DataFrame(simple_data)
df_

enter image description here

You can get my full notebook from here.

In most of the cases, in my tests, unpacking shows to be faster, but the difference is so small that the results may change from a run to the other. Again, the comprehension approach is the slowest, in fact, the other 2 methods are up to ~ 60% faster.

Change GitHub Account username

Yes, this is an old question. But it's misleading, as this was the first result in my search, and both the answers aren't correct anymore.

You can change your Github account name at any time.

To do this, click your profile picture > Settings > Account Settings > Change Username.

Links to your repositories will redirect to the new URLs, but they should be updated on other sites because someone who chooses your abandoned username can override the links. Links to your profile page will be 404'd.

For more information, see the official help page.

And furthermore, if you want to change your username to something else, but that specific username is being taken up by someone else who has been completely inactive for the entire time their account has existed, you can report their account for name squatting.

Create instance of generic type in Java?

You can do this now and it doesn't require a bunch of reflection code.

import com.google.common.reflect.TypeToken;

public class Q26289147
{
    public static void main(final String[] args) throws IllegalAccessException, InstantiationException
    {
        final StrawManParameterizedClass<String> smpc = new StrawManParameterizedClass<String>() {};
        final String string = (String) smpc.type.getRawType().newInstance();
        System.out.format("string = \"%s\"",string);
    }

    static abstract class StrawManParameterizedClass<T>
    {
        final TypeToken<T> type = new TypeToken<T>(getClass()) {};
    }
}

Of course if you need to call the constructor that will require some reflection, but that is very well documented, this trick isn't!

Here is the JavaDoc for TypeToken.

How can I check if a string only contains letters in Python?

(1) Use str.isalpha() when you print the string.

(2) Please check below program for your reference:-

 str = "this";  # No space & digit in this string
 print str.isalpha() # it gives return True

 str = "this is 2";
 print str.isalpha() # it gives return False

Note:- I checked above example in Ubuntu.

Passing an array using an HTML form hidden element

You can use serialize and base64_encode from the client side. After that, then use unserialize and base64_decode on the server side.

Like:

On the client side, use:

    $postvalue = array("a", "b", "c");
    $postvalue = base64_encode(serialize($array));

   // Your form hidden input
   <input type="hidden" name="result" value="<?php echo $postvalue; ?>">

On the server side, use:

    $postvalue = unserialize(base64_decode($_POST['result']));
    print_r($postvalue) // Your desired array data will be printed here

"The import org.springframework cannot be resolved."

Add these dependencies

</dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>4.3.7.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.7.RELEASE</version>
    </dependency>
</dependencies>

Location of my.cnf file on macOS

For me in sierra version

copy the default configuration at:

/usr/local/Cellar/mysql/5.6.27/support-files/my-default.cnf

to

/usr/local/Cellar/mysql/5.6.27/my.cnf

Call another rest api from my server in Spring-Boot

This website has some nice examples for using spring's RestTemplate. Here is a code example of how it can work to get a simple object:

private static void getEmployees()
{
    final String uri = "http://localhost:8080/springrestexample/employees.xml";

    RestTemplate restTemplate = new RestTemplate();
    String result = restTemplate.getForObject(uri, String.class);

    System.out.println(result);
}

Android Studio - Emulator - eglSurfaceAttrib not implemented

I've found the same thing, but only on emulators that have the Use Host GPU setting ticked. Try turning that off, you'll no longer see those warnings (and the emulator will run horribly, horribly slowly..)

In my experience those warnings are harmless. Notice that the "error" is EGL_SUCCESS, which would seem to indicate no error at all!

Is there a good jQuery Drag-and-drop file upload plugin?

http://blueimp.github.com/jQuery-File-Upload/ = great solution

According to their docs, the following browsers support drag & drop:

  • Firefox 4+
  • Safari 5+
  • Google Chrome
  • Microsoft Internet Explorer 10.0+

Checking if a field contains a string

Simplest way to accomplish this task

If you want the query to be case-sensitive

db.getCollection("users").find({'username':/Son/})

If you want the query to be case-insensitive

db.getCollection("users").find({'username':/Son/i})

Limiting the number of characters in a JTextField

Here is an optimized version of npinti's answer:

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;
import java.awt.*;

public class TextComponentLimit extends PlainDocument
{
    private int charactersLimit;

    private TextComponentLimit(int charactersLimit)
    {
        this.charactersLimit = charactersLimit;
    }

    @Override
    public void insertString(int offset, String input, AttributeSet attributeSet) throws BadLocationException
    {
        if (isAllowed(input))
        {
            super.insertString(offset, input, attributeSet);
        } else
        {
            Toolkit.getDefaultToolkit().beep();
        }
    }

    private boolean isAllowed(String string)
    {
        return (getLength() + string.length()) <= charactersLimit;
    }

    public static void addTo(JTextComponent textComponent, int charactersLimit)
    {
        TextComponentLimit textFieldLimit = new TextComponentLimit(charactersLimit);
        textComponent.setDocument(textFieldLimit);
    }
}

To add a limit to your JTextComponent, simply write the following line of code:

JTextFieldLimit.addTo(myTextField, myMaximumLength);

Efficient way to do batch INSERTS with JDBC

You can use this rewriteBatchedStatements parameter to make the batch insert even faster.

you can read here about the param: MySQL and JDBC with rewriteBatchedStatements=true

How do you find the current user in a Windows environment?

Via powershell (file.ps1) I use the following

$username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name

It returns the name of the user in the "Domain\Username" format. If you just want the username just write

$username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name.Split("\")[1]

The advantage is that It works with windows 10 windows 8 server 2016. As far as I remember with also other OS like Win7 etc. (not older) . And yeah via batch you can simply use

 $username = &whoami

How to create .pfx file from certificate and private key?

You will need to use openssl.

openssl pkcs12 -export -out domain.name.pfx -inkey domain.name.key -in domain.name.crt

The key file is just a text file with your private key in it.

If you have a root CA and intermediate certs, then include them as well using multiple -in params

openssl pkcs12 -export -out domain.name.pfx -inkey domain.name.key -in domain.name.crt -in intermediate.crt -in rootca.crt

You can install openssl from here: openssl

What is the difference between aggregation, composition and dependency?

Aggregation implies a relationship where the child can exist independently of the parent. Example: Class (parent) and Student (child). Delete the Class and the Students still exist.

Composition implies a relationship where the child cannot exist independent of the parent. Example: House (parent) and Room (child). Rooms don't exist separate to a House.

The above two are forms of containment (hence the parent-child relationships).

Dependency is a weaker form of relationship and in code terms indicates that a class uses another by parameter or return type.

Dependency is a form of association.

Bootstrap: add margin/padding space between columns

For those looking to control the space between a dynamic number of columns, try:

<div class="row no-gutters">
    <div class="col">
        <div class="inner">
            <!-- content here -->
        </div>
    </div>
    <div class="col">
        <div class="inner">
            <!-- content here -->
        </div>
    </div>
    <!-- etc. -->
</div>

CSS:

.col:not(:last-child) .inner {
  margin: 2px; // Or whatever you want your spacing to be
}

Use latest version of Internet Explorer in the webbrowser control

var appName = System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe";

using (var Key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true))
    Key.SetValue(appName, 99999, RegistryValueKind.DWord);

According to what I read here (Controlling WebBrowser Control Compatibility:

What Happens if I Set the FEATURE_BROWSER_EMULATION Document Mode Value Higher than the IE Version on the Client?

Obviously, the browser control can only support a document mode that is less than or equal to the IE version installed on the client. Using the FEATURE_BROWSER_EMULATION key works best for enterprise line of business apps where there is a deployed and support version of the browser. In the case you set the value to a browser mode that is a higher version than the browser version installed on the client, the browser control will choose the highest document mode available.

The simplest thing is to put a very high decimal number ...

How to avoid Python/Pandas creating an index in a saved csv?

Use index=False.

df.to_csv('your.csv', index=False)

How to refresh the data in a jqGrid?

Try this to reload jqGrid with new data

jQuery("#grid").jqGrid('setGridParam',{datatype:'json'}).trigger('reloadGrid');

Why doesn't Java support unsigned ints?

This is from an interview with Gosling and others, about simplicity:

Gosling: For me as a language designer, which I don't really count myself as these days, what "simple" really ended up meaning was could I expect J. Random Developer to hold the spec in his head. That definition says that, for instance, Java isn't -- and in fact a lot of these languages end up with a lot of corner cases, things that nobody really understands. Quiz any C developer about unsigned, and pretty soon you discover that almost no C developers actually understand what goes on with unsigned, what unsigned arithmetic is. Things like that made C complex. The language part of Java is, I think, pretty simple. The libraries you have to look up.

How to run a javascript function during a mouseover on a div

Here is how I show hover text using JavaScript tooltip:

<script language="JavaScript" type="text/javascript" src="javascript/wz_tooltip.js"></script>

<div class="curhand" onmouseover="this.T_WIDTH=125; return escape('Welcome')">Are you New Here?</div>

JavaScript check if value is only undefined, null or false

Using ? is much cleaner.

var ? function_if_exists() : function_if_doesnt_exist();

Execute CMD command from code

Argh :D not the fastest

Process.Start("notepad C:\test.txt");

Is there Java HashMap equivalent in PHP?

Arrays in PHP can have Key Value structure.

Adding headers when using httpClient.GetAsync

When using GetAsync with the HttpClient you can add the authorization headers like so:

httpClient.DefaultRequestHeaders.Authorization 
                         = new AuthenticationHeaderValue("Bearer", "Your Oauth token");

This does add the authorization header for the lifetime of the HttpClient so is useful if you are hitting one site where the authorization header doesn't change.

Here is an detailed SO answer

refresh leaflet map: map container is already initialized

Before initializing map check for is the map is already initiated or not

var container = L.DomUtil.get('map');

if(container != null){

container._leaflet_id = null;

}

It works for me

How can I keep Bootstrap popovers alive while being hovered?

I agree that the best way is to use the one given by: David Chase, Cu Ly, and others that the simplest way to do this is to use the container: $(this) property as follows:

$(selectorString).each(function () {
  var $this = $(this);
  $this.popover({
    html: true,
    placement: "top",
    container: $this,
    trigger: "hover",
    title: "Popover",
    content: "Hey, you hovered on element"
  });
});

I want to point out here that the popover in this case will inherit all properties of the current element. So, for example, if you do this for a .btn element(bootstrap), you won't be able to select text inside the popover. Just wanted to record that since I spent quite some time banging my head on this.

Should __init__() call the parent class's __init__()?

In Anon's answer:
"If you need something from super's __init__ to be done in addition to what is being done in the current class's __init__ , you must call it yourself, since that will not happen automatically"

It's incredible: he is wording exactly the contrary of the principle of inheritance.


It is not that "something from super's __init__ (...) will not happen automatically" , it is that it WOULD happen automatically, but it doesn't happen because the base-class' __init__ is overriden by the definition of the derived-clas __init__

So then, WHY defining a derived_class' __init__ , since it overrides what is aimed at when someone resorts to inheritance ??

It's because one needs to define something that is NOT done in the base-class' __init__ , and the only possibility to obtain that is to put its execution in a derived-class' __init__ function.
In other words, one needs something in base-class' __init__ in addition to what would be automatically done in the base-classe' __init__ if this latter wasn't overriden.
NOT the contrary.


Then, the problem is that the desired instructions present in the base-class' __init__ are no more activated at the moment of instantiation. In order to offset this inactivation, something special is required: calling explicitly the base-class' __init__ , in order to KEEP , NOT TO ADD, the initialization performed by the base-class' __init__ . That's exactly what is said in the official doc:

An overriding method in a derived class may in fact want to extend rather than simply replace the base class method of the same name. There is a simple way to call the base class method directly: just call BaseClassName.methodname(self, arguments).
http://docs.python.org/tutorial/classes.html#inheritance

That's all the story:

  • when the aim is to KEEP the initialization performed by the base-class, that is pure inheritance, nothing special is needed, one must just avoid to define an __init__ function in the derived class

  • when the aim is to REPLACE the initialization performed by the base-class, __init__ must be defined in the derived-class

  • when the aim is to ADD processes to the initialization performed by the base-class, a derived-class' __init__ must be defined , comprising an explicit call to the base-class __init__


What I feel astonishing in the post of Anon is not only that he expresses the contrary of the inheritance theory, but that there have been 5 guys passing by that upvoted without turning a hair, and moreover there have been nobody to react in 2 years in a thread whose interesting subject must be read relatively often.

Get nth character of a string in Swift programming language

There's an alternative, explained in String manifesto

extension String : BidirectionalCollection {
    subscript(i: Index) -> Character { return characters[i] }
}

Text in a flex container doesn't wrap in IE11

Somehow all these solutions didn't work for me. There is clearly an IE bug in flex-direction:column.

I only got it working after removing flex-direction:

flex-wrap: wrap;
align-items: center;
align-content: center;

jQuery Force set src attribute for iframe

Setting src attribute didn't work for me. The iframe didn't display the url.

What worked for me was:

window.open(url, "nameof_iframe");

Hope it helps someone.

ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

When you use routerLink like this, then you need to pass the value of the route it should go to. But when you use routerLink with the property binding syntax, like this: [routerLink], then it should be assigned a name of the property the value of which will be the route it should navigate the user to.

So to fix your issue, replace this routerLink="['/about']" with routerLink="/about" in your HTML.

There were other places where you used property binding syntax when it wasn't really required. I've fixed it and you can simply use the template syntax below:

<nav class="main-nav>
  <ul 
    class="main-nav__list" 
    ng-sticky 
    addClass="main-sticky-link" 
    [ngClass]="ref.click ? 'Navbar__ToggleShow' : ''">
    <li class="main-nav__item" routerLinkActive="active">
      <a class="main-nav__link" routerLink="/">Home</a>
    </li>
    <li class="main-nav__item" routerLinkActive="active"> 
      <a class="main-nav__link" routerLink="/about">About us</a>
    </li>
  </ul>
</nav>

It also needs to know where exactly should it load the template for the Component corresponding to the route it has reached. So for that, don't forget to add a <router-outlet></router-outlet>, either in your template provided above or in a parent component.

There's another issue with your AppRoutingModule. You need to export the RouterModule from there so that it is available to your AppModule when it imports it. To fix that, export it from your AppRoutingModule by adding it to the exports array.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { MainLayoutComponent } from './layout/main-layout/main-layout.component';
import { AboutComponent } from './components/about/about.component';
import { WhatwedoComponent } from './components/whatwedo/whatwedo.component';
import { FooterComponent } from './components/footer/footer.component';
import { ProjectsComponent } from './components/projects/projects.component';
const routes: Routes = [
  { path: 'about', component: AboutComponent },
  { path: 'what', component: WhatwedoComponent },
  { path: 'contacts', component: FooterComponent },
  { path: 'projects', component: ProjectsComponent},
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forRoot(routes),
  ],
  exports: [RouterModule],
  declarations: []
})
export class AppRoutingModule { }

Finish all previous activities

When the user wishes to exit all open activities, they should press a button which loads the first Activity that runs when your application starts, clear all the other activities, then have the last remaining activity finish. Have the following code run when the user presses the exit button. In my case, LoginActivity is the first activity in my program to run.

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);

The above code clears all the activities except for LoginActivity. Then put the following code inside the LoginActivity's onCreate(...), to listen for when LoginActivity is recreated and the 'EXIT' signal was passed:

if (getIntent().getBooleanExtra("EXIT", false)) {
    finish();  
}

Why is making an exit button in Android so hard?

Android tries hard to discourage you from having an "exit" button in your application, because they want the user to never care about whether or not the programs they use are running in the background or not.

The Android OS developers want your program to be able to survive an unexpected shutdown and power off of the phone, and when the user restarts the program, they pick up right where they left off. So the user can receive a phone call while they use your application, and open maps which requires your application to be freed for more resources.

When the user resumes your application, they pick up right where they left off with no interruption. This exit button is usurping power from the activity manager, potentially causing problems with the automatically managed android program life cycle.

Cannot push to Git repository on Bitbucket

I had this issue and I thought I was crazy. I have been using SSH for 20 years. and git over SSH since 2012... but why couldn't I fetch my bitbucket repository on my home computer?

well, I have two bitbucket accounts and had 4 SSH keys loaded inside my agent. even if my .ssh/config was configured to use the right key. when ssh was initializing the connection, it was using them in order loaded into the agent. so I was getting logged into my personal bitbucket account.

then getting a Forbidden error trying to fetch the repo. makes sense.

I unloaded the key from the agent

ssh-add -d ~/.ssh/personal_rsa

then I could fetch the repos.

... Later I found out I can force it to use the specified identity only

 Host bitbucket.org-user2
     HostName bitbucket.org
     User git
     IdentityFile ~/.ssh/user2
     IdentitiesOnly yes

I didn't know about that last option IdentitiesOnly

from the bitbucket documentation itself

https://blog.developer.atlassian.com/different-ssh-keys-multiple-bitbucket-accounts/

Numeric for loop in Django templates

Unfortunately, that's not supported in the Django template language. There are a couple of suggestions, but they seem a little complex. I would just put a variable in the context:

...
render_to_response('foo.html', {..., 'range': range(10), ...}, ...)
...

and in the template:

{% for i in range %}
     ...
{% endfor %}

Iterating over all the keys of a map

A Type agnostic solution:

for _, key := range reflect.ValueOf(yourMap).MapKeys() {
    value := s.MapIndex(key).Interface()
    fmt.Println("Key:", key, "Value:", value)
}  

How to add new item to hash

Create hash as:

h = Hash.new
=> {}

Now insert into hash as:

h = Hash["one" => 1]

How to utilize date add function in Google spreadsheet?

Using pretty much the same approach as used by Burnash, for the final result you can use ...

=regexextract(A1,"[0-9]+")+A2

where A1 houses the string with text and number and A2 houses the date of interest

How to write data with FileOutputStream without losing old data?

Use the constructor that takes a File and a boolean

FileOutputStream(File file, boolean append) 

and set the boolean to true. That way, the data you write will be appended to the end of the file, rather than overwriting what was already there.

How do I set bold and italic on UILabel of iPhone/iPad?

Good answers here, but if you want the label respects the user's preferred size category, use preferredFont.

UIFont.systemFont(ofSize: UIFont.preferredFont(forTextStyle: .body).pointSize, weight: .bold)

Query to list number of records in each table in a database

select T.object_id, T.name, I.indid, I.rows 
  from Sys.tables T 
  left join Sys.sysindexes I 
    on (I.id = T.object_id and (indid =1 or indid =0 ))
 where T.type='U'

Here indid=1 means a CLUSTERED index and indid=0 is a HEAP

How to get first two characters of a string in oracle query?

Just use SUBSTR function. It takes 3 parameters: String column name, starting index and length of substring:

select SUBSTR(OrderNo, 1, 2) FROM shipment;

Sound effects in JavaScript / HTML5

HTML5 Audio objects

You don't need to bother with <audio> elements. HTML 5 lets you access Audio objects directly:

var snd = new Audio("file.wav"); // buffers automatically when created
snd.play();

There's no support for mixing in current version of the spec.

To play same sound multiple times, create multiple instances of the Audio object. You could also set snd.currentTime=0 on the object after it finishes playing.


Since the JS constructor doesn't support fallback <source> elements, you should use

(new Audio()).canPlayType("audio/ogg; codecs=vorbis")

to test whether the browser supports Ogg Vorbis.


If you're writing a game or a music app (more than just a player), you'll want to use more advanced Web Audio API, which is now supported by most browsers.

How do I get row id of a row in sql server

SQL does not do that. The order of the tuples in the table are not ordered by insertion date. A lot of people include a column that stores that date of insertion in order to get around this issue.

How to export DataTable to Excel

One way of doing it would be also with ACE OLEDB Provider (see also connection strings for Excel). Of course you'd have to have the provider installed and registered. You should have it, if you have Excel installed, but this is something you have to consider when deploying the app.

This is the example of calling the helper method from ExportHelper: ExportHelper.CreateXlsFromDataTable(myDataTable, @"C:\tmp\export.xls");

The helper for exporting to Excel file using ACE OLEDB:

public class ExportHelper
{
    private const string ExcelOleDbConnectionStringTemplate = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=YES\";";

    /// <summary>
    /// Creates the Excel file from items in DataTable and writes them to specified output file.
    /// </summary>
    public static void CreateXlsFromDataTable(DataTable dataTable, string fullFilePath)
    {
        string createTableWithHeaderScript = GenerateCreateTableCommand(dataTable);

        using (var conn = new OleDbConnection(String.Format(ExcelOleDbConnectionStringTemplate, fullFilePath)))
        {
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }

            OleDbCommand cmd = new OleDbCommand(createTableWithHeaderScript, conn);
            cmd.ExecuteNonQuery();

            foreach (DataRow dataExportRow in dataTable.Rows)
            {
                AddNewRow(conn, dataExportRow);
            }
        }
    }

    private static void AddNewRow(OleDbConnection conn, DataRow dataRow)
    {
        string insertCmd = GenerateInsertRowCommand(dataRow);

        using (OleDbCommand cmd = new OleDbCommand(insertCmd, conn))
        {
            AddParametersWithValue(cmd, dataRow);
            cmd.ExecuteNonQuery();
        }
    }

    /// <summary>
    /// Generates the insert row command.
    /// </summary>
    private static string GenerateInsertRowCommand(DataRow dataRow)
    {
        var stringBuilder = new StringBuilder();
        var columns = dataRow.Table.Columns.Cast<DataColumn>().ToList();
        var columnNamesCommaSeparated = string.Join(",", columns.Select(x => x.Caption));
        var questionmarkCommaSeparated = string.Join(",", columns.Select(x => "?"));

        stringBuilder.AppendFormat("INSERT INTO [{0}] (", dataRow.Table.TableName);
        stringBuilder.Append(columnNamesCommaSeparated);
        stringBuilder.Append(") VALUES(");
        stringBuilder.Append(questionmarkCommaSeparated);
        stringBuilder.Append(")");
        return stringBuilder.ToString();
    }

    /// <summary>
    /// Adds the parameters with value.
    /// </summary>
    private static void AddParametersWithValue(OleDbCommand cmd, DataRow dataRow)
    {
        var paramNumber = 1;

        for (int i = 0; i <= dataRow.Table.Columns.Count - 1; i++)
        {
            if (!ReferenceEquals(dataRow.Table.Columns[i].DataType, typeof(int)) && !ReferenceEquals(dataRow.Table.Columns[i].DataType, typeof(decimal)))
            {
                cmd.Parameters.AddWithValue("@p" + paramNumber, dataRow[i].ToString().Replace("'", "''"));
            }
            else
            {
                object value = GetParameterValue(dataRow[i]);
                OleDbParameter parameter = cmd.Parameters.AddWithValue("@p" + paramNumber, value);
                if (value is decimal)
                {
                    parameter.OleDbType = OleDbType.Currency;
                }
            }

            paramNumber = paramNumber + 1;
        }
    }

    /// <summary>
    /// Gets the formatted value for the OleDbParameter.
    /// </summary>
    private static object GetParameterValue(object value)
    {
        if (value is string)
        {
            return value.ToString().Replace("'", "''");
        }
        return value;
    }

    private static string GenerateCreateTableCommand(DataTable tableDefination)
    {
        StringBuilder stringBuilder = new StringBuilder();
        bool firstcol = true;

        stringBuilder.AppendFormat("CREATE TABLE [{0}] (", tableDefination.TableName);

        foreach (DataColumn tableColumn in tableDefination.Columns)
        {
            if (!firstcol)
            {
                stringBuilder.Append(", ");
            }
            firstcol = false;

            string columnDataType = "CHAR(255)";

            switch (tableColumn.DataType.Name)
            {
                case "String":
                    columnDataType = "CHAR(255)";
                    break;
                case "Int32":
                    columnDataType = "INTEGER";
                    break;
                case "Decimal":
                    // Use currency instead of decimal because of bug described at 
                    // http://social.msdn.microsoft.com/Forums/vstudio/en-US/5d6248a5-ef00-4f46-be9d-853207656bcc/localization-trouble-with-oledbparameter-and-decimal?forum=csharpgeneral
                    columnDataType = "CURRENCY";
                    break;
            }

            stringBuilder.AppendFormat("{0} {1}", tableColumn.ColumnName, columnDataType);
        }
        stringBuilder.Append(")");

        return stringBuilder.ToString();
    }
}

Row names & column names in R

Just to expand a little on Dirk's example:

It helps to think of a data frame as a list with equal length vectors. That's probably why names works with a data frame but not a matrix.

The other useful function is dimnames which returns the names for every dimension. You will notice that the rownames function actually just returns the first element from dimnames.

Regarding rownames and row.names: I can't tell the difference, although rownames uses dimnames while row.names was written outside of R. They both also seem to work with higher dimensional arrays:

>a <- array(1:5, 1:4)
> a[1,,,]
> rownames(a) <- "a"
> row.names(a)
[1] "a"
> a
, , 1, 1    
  [,1] [,2]
a    1    2

> dimnames(a)
[[1]]
[1] "a"

[[2]]
NULL

[[3]]
NULL

[[4]]
NULL

Division of integers in Java

Convert both completed and total to double or at least cast them to double when doing the devision. I.e. cast the varaibles to double not just the result.

Fair warning, there is a floating point precision problem when working with float and double.

Best Practices for securing a REST API / web service

One of the best posts I've ever come across regarding Security as it relates to REST is over at 1 RainDrop. The MySpace API's use OAuth also for security and you have full access to their custom channels in the RestChess code, which I did a lot of exploration with. This was demo'd at Mix and you can find the posting here.

Find all stored procedures that reference a specific column in some table

You can use the system views contained in information_schema to search in tables, views and (unencrypted) stored procedures with one script. I developed such a script some time ago because I needed to search for field names everywhere in the database.

The script below first lists the tables/views containing the column name you're searching for, and then the stored procedures source code where the column is found. It displays the result in one table distinguishing "BASE TABLE", "VIEW" and "PROCEDURE", and (optionally) the source code in a second table:

DECLARE @SearchFor nvarchar(max)='%CustomerID%' -- search for this string
DECLARE @SearchSP bit = 1 -- 1=search in SPs as well
DECLARE @DisplaySPSource bit = 1 -- 1=display SP source code

-- tables
if (@SearchSP=1) begin  
  (
  select '['+c.table_Schema+'].['+c.table_Name+'].['+c.column_name+']' [schema_object], 
            t.table_type 
  from information_schema.columns c
  left join information_schema.Tables t on c.table_name=t.table_name
  where column_name like @SearchFor 
  union
  select '['+routine_Schema+'].['+routine_Name+']' [schema_object], 
         'PROCEDURE' as table_type from information_schema.routines
  where routine_definition like @SearchFor
        and routine_type='procedure'
  )
  order by table_type, schema_object
end else begin
  select '['+c.table_Schema+'].['+c.table_Name+'].['+c.column_name+']' [schema_object], 
         t.table_type 
  from information_schema.columns c
  left join information_schema.Tables t on c.table_name=t.table_name
  where column_name like @SearchFor 
  order by c.table_Name, c.column_name
end     
-- stored procedure (source listing)
if (@SearchSP=1) begin      
    if (@DisplaySPSource=1) begin
      select '['+routine_Schema+'].['+routine_Name+']' [schema.sp], routine_definition 
      from information_schema.routines
      where routine_definition like @SearchFor
      and routine_type='procedure'
      order by routine_name
    end
end

If you run the query, use the "result as text" option - then you can use "find" to locate the search text in the result set (useful for long source code).

Note that you can set @DisplaySPSource to 0 if you just want to display the SP names, and if you're just looking for tables/views, but not for SPs, you can set @SearchSP to 0.

Example result (find CustomerID in the Northwind database, results displayed via LinqPad):

Sample Result

Note that I've verfied this script with a test view dbo.TestOrders and it found the CustomerID in this view even though c.* was used in the SELECT statement (referenced table Customers contains the CustomerIDand hence the view is showing this column).


Note for LinqPad users: In C#, you can use dc.ExecuteQueryDynamic(sqlQueryStr, new object[] {... parameters ...} ).Dump(); and have the parameters as @p0 ... @pn inside the query string. Then you can write a static extension class and save it under My Extensions to be used in your LinqPad queries. The data context can be passed from the query window as DataContextBase dc via parameter, i.e. public static void SearchDialog(this DataContextBase dc, string searchString = "%") inside a public static extension class (in LinqPad 6, it is DataContext). Then you can rewrite the SQL query above as a string with parameters and invoke it from the C# context.

how to pass parameter from @Url.Action to controller function

Need To Two Or More Parameters Passing Throw view To Controller Use This Syntax... Try.. It.

var id=0,Num=254;var str='Sample';    
var Url = '@Url.Action("ViewNameAtController", "Controller", new RouteValueDictionary(new { id= "id", Num= "Num", Str= "str" }))'.replace("id", encodeURIComponent(id));
    Url = Url.replace("Num", encodeURIComponent(Num));
    Url = Url.replace("Str", encodeURIComponent(str));
    Url = Url.replace(/&amp;/g, "&");
window.location.href = Url;

How to list containers in Docker

I got the error message Cannot connect to the Docker daemon. I forgot I am running the daemon as root and needed sudo:

$ sudo docker ps

getting the difference between date in days in java

Like this.

import java.util.Date;
import java.util.GregorianCalendar;

/**
 * DateDiff -- compute the difference between two dates.
 */
public class DateDiff {
  public static void main(String[] av) {
    /** The date at the end of the last century */
    Date d1 = new GregorianCalendar(2000, 11, 31, 23, 59).getTime();

    /** Today's date */
    Date today = new Date();

    // Get msec from each, and subtract.
    long diff = today.getTime() - d1.getTime();

    System.out.println("The 21st century (up to " + today + ") is "
        + (diff / (1000 * 60 * 60 * 24)) + " days old.");
  }

}

Here is an article on Java date arithmetic.

how to align all my li on one line?

Using Display: table

HTML:

<ul class="my-row">
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>

CSS:

ul.my-row {
  display: table;
  width: 100%;
  text-align: center;
}

ul.my-row > li {
  display: table-cell;
}

SCSS:

ul {
  &.my-row {
    display: table;
    width: 100%;
    text-align: center;

    > li {
      display: table-cell;
    }
  } 
}

Work great for me

What is the most effective way for float and double comparison?

The comparison with an epsilon value is what most people do (even in game programming).

You should change your implementation a little though:

bool AreSame(double a, double b)
{
    return fabs(a - b) < EPSILON;
}

Edit: Christer has added a stack of great info on this topic on a recent blog post. Enjoy.

Declaring a boolean in JavaScript using just var

As this very useful tutorial says:

var age = 0;

// bad
var hasAge = new Boolean(age);

// good
var hasAge = Boolean(age);

// good
var hasAge = !!age;

convert php date to mysql format

This site has two pretty simple solutions - just check the code, I provided the descriptions in case you wanted them - saves you some clicks.

http://www.richardlord.net/blog/dates-in-php-and-mysql

1.One common solution is to store the dates in DATETIME fields and use PHPs date() and strtotime() functions to convert between PHP timestamps and MySQL DATETIMEs. The methods would be used as follows -

$mysqldate = date( 'Y-m-d H:i:s', $phpdate );
$phpdate = strtotime( $mysqldate );

2.Our second option is to let MySQL do the work. MySQL has functions we can use to convert the data at the point where we access the database. UNIX_TIMESTAMP will convert from DATETIME to PHP timestamp and FROM_UNIXTIME will convert from PHP timestamp to DATETIME. The methods are used within the SQL query. So we insert and update dates using queries like this -

$query = "UPDATE table SET
    datetimefield = FROM_UNIXTIME($phpdate)
    WHERE...";
$query = "SELECT UNIX_TIMESTAMP(datetimefield)
    FROM table WHERE...";

Getting value from appsettings.json in .net core

In the constructor of Startup class, you can access appsettings.json and many other settings using the injected IConfiguration object:

Startup.cs Constructor

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;

        //here you go
        var myvalue = Configuration["Grandfather:Father:Child"];

    }

public IConfiguration Configuration { get; }

Contents of appsettings.json

  {
  "Grandfather": {
    "Father": {
      "Child": "myvalue"
    }
  }

Grep and Python

You can use python-textops3 :

from textops import *

print('\n'.join(cat(f) | grep(search_term)))

with python-textops3 you can use unix-like commands with pipes

Moment Js UTC to Local Time

Note: please update the date format accordingly.

Format Date

   __formatDate: function(myDate){
      var ts = moment.utc(myDate);
      return ts.local().format('D-MMM-Y');
   }

Format Time

  __formatTime: function(myDate){
      var ts = moment.utc(myDate);
      return ts.local().format('HH:mm');
  },

Improve subplot size/spacing with many subplots in matplotlib

You can use plt.subplots_adjust to change the spacing between the subplots (source)

call signature:

subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)

The parameter meanings (and suggested defaults) are:

left  = 0.125  # the left side of the subplots of the figure
right = 0.9    # the right side of the subplots of the figure
bottom = 0.1   # the bottom of the subplots of the figure
top = 0.9      # the top of the subplots of the figure
wspace = 0.2   # the amount of width reserved for blank space between subplots
hspace = 0.2   # the amount of height reserved for white space between subplots

The actual defaults are controlled by the rc file

String was not recognized as a valid DateTime " format dd/MM/yyyy"

Change Manually :

string s = date.Substring(3, 2) +"/" + date.Substring(0, 2) + "/" + date.Substring(6, 4);

From 11/22/2015 it will be converted in 22/11/2015

from unix timestamp to datetime

Looks like you might want the ISO format so that you can retain the timezone.

var dateTime = new Date(1370001284000);
dateTime.toISOString(); // Returns "2013-05-31T11:54:44.000Z"

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString

Should we @Override an interface's method implementation?

If the class that is implementing the interface is an abstract class, @Override is useful to ensure that the implementation is for an interface method; without the @Override an abstract class would just compile fine even if the implementation method signature does not match the method declared in the interface; the mismatched interface method would remain as unimplemented. The Java doc cited by @Zhao

The method does override or implement a method declared in a supertype

is clearly referring to an abstract super class; an interface can not be called the supertype. So, @Override is redundant and not sensible for interface method implementations in concrete classes.

What is the meaning of <> in mysql query?

<> is equal to != i.e, both are used to represent the NOT EQUAL operation. For instance, email <> '' and email != '' are same.

Convert Text to Date?

To the OP... I also got a type mismatch error the first time I tried running your subroutine. In my case it was cause by non-date-like data in the first cell (i.e. a header). When I changed the contents of the header cell to date-style txt for testing, it ran just fine...

Hope this helps as well.

Login failed for user 'DOMAIN\MACHINENAME$'

The trick that worked for me was to remove Integrated Security from my connection string and add a regular User ID=userName; Password=password your connection string in the App.config of your libruary might not be using integrated security but the one created in Web.config is!

How to present a modal atop the current view in Swift

First, remove all explicit setting of modal presentation style in code and do the following:

  1. In the storyboard set the ModalViewController's modalPresentation style to Over Current context

img1

  1. Check the checkboxes in the Root/Presenting ViewController - Provide Context and Define Context. They seem to be working even unchecked.

Show Error on the tip of the Edit Text Android

Using Kotlin Language,

EXAMPLE CODE

 login_ID.setOnClickListener {
            if(email_address_Id.text.isEmpty()){
                email_address_Id.error = "Please Enter Email Address"
            }
            if(Password_ID.text.isEmpty()){
                Password_ID.error = "Please Enter Password"
            }
        }

Can't load AMD 64-bit .dll on a IA 32-bit platform

If you are still getting that error after installing the 64 bit JRE, it means that the JVM running Gurobi package is still using the 32 bit JRE.

Check that you have updated the PATH and JAVA_HOME globally and in the command shell that you are using. (Maybe you just need to exit and restart it.)

Check that your command shell runs the right version of Java by running "java -version" and checking that it says it is a 64bit JRE.

If you are launching the example via a wrapper script / batch file, make sure that the script is using the right JRE. Modify as required ...

How do you fix a MySQL "Incorrect key file" error when you can't repair the table?

You must change the location of MySQL's temporary folder which is '/tmp' in most cases to a location with a bigger disk space. Change it in MySQL's config file.

Basically your server is running out of disk space where /tmp is located.

Escape double quote character in XML

New, improved answer to an old, frequently asked question...

When to escape double quote in XML

Double quote (") may appear without escaping:

  • In XML textual content:

    <NoEscapeNeeded>He said, "Don't quote me."</NoEscapeNeeded>
    
  • In XML attributes delimited by single quotes ('):

    <NoEscapeNeeded name='Pete "Maverick" Mitchell'/>
    

    Note: switching to single quotes (') also requires no escaping:

    <NoEscapeNeeded name="Pete 'Maverick' Mitchell"/>
    

Double quote (") must be escaped:

  • In XML attributes delimited by double quotes:

    <EscapeNeeded name="Pete &quot;Maverick&quot; Mitchell"/>
    

Bottom line

Double quote (") must be escaped as &quot; in XML only in very limited contexts.

Can I embed a custom font in an iPhone application?

I've combined some of the advice on this page into something that works for me on iOS 5.

First, you have to add the custom font to your project. Then, you need to follow the advice of @iPhoneDev and add the font to your info.plist file.

After you do that, this works:

UIFont *yourCustomFont = [UIFont fontWithName:@"YOUR-CUSTOM-FONT-POSTSCRIPT-NAME" size:14.0];
[yourUILabel setFont:yourCustomFont];

However, you need to know the Postscript name of your font. Just follow @Daniel Wood's advice and press command-i while you're in FontBook.

Then, enjoy your custom font.

How to list all methods for an object in Ruby?

What about one of these?

object.methods.sort
Class.methods.sort

How to remove old and unused Docker images

If you build these pruned images yourself (from some other, older base images) please be careful with the accepted solutions above based on docker image prune, as the command is blunt and will try to remove also all dependencies required by your latest images (the command should be probably renamed to docker image*s* prune).

The solution I came up for my docker image build pipelines (where there are daily builds and tags=dates are in the YYYYMMDD format) is this:

# carefully narrow down the image to be deleted (to avoid removing useful static stuff like base images)
my_deleted_image=mirekphd/ml-cpu-py37-vsc-cust

# define the monitored image (tested for obsolescence), which will be usually the same as deleted one, unless deleting some very infrequently built image which requires a separate "clock"
monitored_image=mirekphd/ml-cache

# calculate the oldest acceptable tag (date)
date_week_ago=$(date -d "last week" '+%Y%m%d')

# get the IDs of obsolete tags of our deleted image
# note we use monitored_image to test for obsolescence
my_deleted_image_obsolete_tag_ids=$(docker images --filter="before=$monitored_image:$date_week_ago" | grep $my_deleted_image | awk '{print $3}')

# remove the obsolete tags of the deleted image
# (note it typically has to be forced using -f switch)
docker rmi -f $my_deleted_image_obsolete_tag_ids

python plot normal distribution

import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
import math

mu = 0
variance = 1
sigma = math.sqrt(variance)
x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
plt.plot(x, stats.norm.pdf(x, mu, sigma))
plt.show()

gass distro, mean is 0 variance 1

Remove a CLASS for all child elements

This should work:

$("#table-filters>ul>li.active").removeClass("active");
//Find all `li`s with class `active`, children of `ul`s, children of `table-filters`

how to destroy bootstrap modal window completely?

This completely removes the modal from the DOM , is working for the "appended" modals as well .

#pickoptionmodal is the id of my modal window.

$(document).on('hidden.bs.modal','#pickoptionmodal',function(e){

e.preventDefault();

$("#pickoptionmodal").remove();

});

Python copy files to a new directory and rename if file name already exists

I would say you have an indentation problem, at least as you wrote it here:

while not os.path.exists(file + "_" + str(i) + extension):
   i+=1
   print "Already 2x exists..."
   print "Renaming"
   shutil.copy(path, file + "_" + str(i) + extension)

should be:

while os.path.exists(file + "_" + str(i) + extension):
    i+=1
print "Already 2x exists..."
print "Renaming"
shutil.copy(path, file + "_" + str(i) + extension)

Check this out, please!

How can I display a pdf document into a Webview?

String webviewurl = "http://test.com/testing.pdf";
webView.getSettings().setJavaScriptEnabled(true); 
if(webviewurl.contains(".pdf")){
    webviewurl = "http://docs.google.com/gview?embedded=true&url=" + webviewurl;        }
webview.loadUrl(webviewurl);

How to select a single child element using jQuery?

Maybe in this way?

$('img', this)[0]

Get GPS location via a service in Android

Take a look at Google Play Location Samples

Location Updates using a Foreground Service: Get updates about a device's location using a bound and started foreground service.

Location Updates using a PendingIntent: Get updates about a device's location using a PendingIntent. Sample shows implementation using an IntentService as well as a BroadcastReceiver.

What is the default maximum heap size for Sun's JVM from Java SE 6?

One can ask with some Java code:

long maxBytes = Runtime.getRuntime().maxMemory();
System.out.println("Max memory: " + maxBytes / 1024 / 1024 + "M");

See javadoc.

How can I color Python logging output?

The bit I had trouble with was setting up the formatter properly:

class ColouredFormatter(logging.Formatter):    
    def __init__(self, msg):
        logging.Formatter.__init__(self, msg)
        self._init_colour = _get_colour()

    def close(self):
        # restore the colour information to what it was
        _set_colour(self._init_colour)

    def format(self, record):        
        # Add your own colourer based on the other examples
        _set_colour( LOG_LEVEL_COLOUR[record.levelno] )
        return logging.Formatter.format(self, record)         

def init():
    # Set up the formatter. Needs to be first thing done.
    rootLogger = logging.getLogger()
    hdlr = logging.StreamHandler()
    fmt = ColouredFormatter('%(message)s')
    hdlr.setFormatter(fmt)
    rootLogger.addHandler(hdlr)

And then to use:

import coloured_log
import logging

coloured_log.init()
logging.info("info")    
logging.debug("debug")    

coloured_log.close()    # restore colours

How to update cursor limit for ORA-01000: maximum open cursors exceed

you can update the setting under init.ora in oraclexe\app\oracle\product\11.2.0\server\config\scripts

Bootstrap 3 .img-responsive images are not responsive inside fieldset in FireFox

just add .col-xs-12 to your responsive image. It's should work.

MVC which submit button has been pressed

Here's a really nice and simple way of doing it with really easy to follow instructions using a custom MultiButtonAttribute:

http://blog.maartenballiauw.be/post/2009/11/26/Supporting-multiple-submit-buttons-on-an-ASPNET-MVC-view.aspx

To summarise, make your submit buttons like this:

<input type="submit" value="Cancel" name="action" />
<input type="submit" value="Create" name="action" /> 

Your actions like this:

[HttpPost]
[MultiButton(MatchFormKey="action", MatchFormValue="Cancel")]
public ActionResult Cancel()
{
    return Content("Cancel clicked");
}

[HttpPost]
[MultiButton(MatchFormKey = "action", MatchFormValue = "Create")]
public ActionResult Create(Person person)
{
    return Content("Create clicked");
} 

And create this class:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultiButtonAttribute : ActionNameSelectorAttribute
{
    public string MatchFormKey { get; set; }
    public string MatchFormValue { get; set; }

    public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
    {
        return controllerContext.HttpContext.Request[MatchFormKey] != null &&
            controllerContext.HttpContext.Request[MatchFormKey] == MatchFormValue;
    }
}

How to discard uncommitted changes in SourceTree?

Its Ctrl + Shift + r

For me, there was only one option to discard all.

enter image description here

How to set radio button selected value using jquery

  <asp:RadioButtonList ID="rblRequestType">
        <asp:ListItem Selected="True" Value="value1">Value1</asp:ListItem>
        <asp:ListItem Value="Value2">Value2</asp:ListItem>
  </asp:RadioButtonList>

You can set checked like this.

var radio0 = $("#rblRequestType_0");
var radio1 = $("#rblRequestType_1");

radio0.checked = true;
radio1.checked = true;

Converting <br /> into a new line for use in a text area

The answer by @Mobilpadde is nice. But this is my solution with regex using preg_replace which might be faster according to my tests.

echo preg_replace('/<br\s?\/?>/i', "\r\n", "testing<br/><br /><BR><br>");

function function_one() {
    preg_replace('/<br\s?\/?>/i', "\r\n", "testing<br/><br /><BR><br>");
}

function function_two() {
    str_ireplace(['<br />','<br>','<br/>'], "\r\n", "testing<br/><br /><BR><br>");
}

function benchmark() {
    $count = 10000000;
    $before = microtime(true);

    for ($i=0 ; $i<$count; $i++) {
        function_one();
    }

    $after = microtime(true);
    echo ($after-$before)/$i . " sec/function one\n";



    $before = microtime(true);

    for ($i=0 ; $i<$count; $i++) {
        function_two();
    }

    $after = microtime(true);
    echo ($after-$before)/$i . " sec/function two\n";
}
benchmark();

Results:

1.1471637010574E-6 sec/function one (preg_replace)
1.6027762889862E-6 sec/function two (str_ireplace)

Using PowerShell to write a file in UTF-8 without the BOM

I figured this wouldn't be UTF, but I just found a pretty simple solution that seems to work...

Get-Content path/to/file.ext | out-file -encoding ASCII targetFile.ext

For me this results in a utf-8 without bom file regardless of the source format.

What's the best way to determine the location of the current PowerShell script?

For PowerShell 3.0

$PSCommandPath
    Contains the full path and file name of the script that is being run. 
    This variable is valid in all scripts.

The function is then:

function Get-ScriptDirectory {
    Split-Path -Parent $PSCommandPath
}

Replace tabs with spaces in vim

Try

set expandtab

for soft tabs.

To fix pre-existing tabs:

:%s/\t/  /g

I used two spaces since you already set your tabstop to 2 spaces.

How to get single value of List<object>

Define a class like this :

public class myclass {
       string id ;
       string title ;
       string content;
 }

 public class program {
        public void Main () {
               List<myclass> objlist = new List<myclass> () ;
               foreach (var value in objlist)  {
                       TextBox1.Text = value.id ;
                       TextBox2.Text= value.title;
                       TextBox3.Text= value.content ;
                }
         }
  }

I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.

JQuery ajax call default timeout value

There doesn't seem to be a standardized default value. I have the feeling the default is 0, and the timeout event left totally dependent on browser and network settings.

For IE, there is a timeout property for XMLHTTPRequests here. It defaults to null, and it says the network stack is likely to be the first to time out (which will not generate an ontimeout event by the way).

Ruby Hash to array of values

I would use:

hash.map { |key, value| value }

Xcode - How to fix 'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X" error?

You may have outlets to UI Element but not IBOutlet property in .h File

For all UI element in Connection Attribute check outlets and it corresponding property in .h header file.

May be missing one or more property entry in .h file.

error: No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml

As you specify in your attrs.xml your adSize attribute belongs to the namespace com.google.ads.AdView. Try to change:

android:adUnitId="a14bd6d2c63e055"         android:adSize="BANNER"

to

ads:adUnitId="a14bd6d2c63e055"         ads:adSize="BANNER"

and it should work.

Create an empty object in JavaScript with {} or new Object()?

This is essentially the same thing. Use whatever you find more convenient.

Iterating through a JSON object

After deserializing the JSON, you have a python object. Use the regular object methods.

In this case you have a list made of dictionaries:

json_object[0].items()

json_object[0]["title"]

etc.

How do I pass JavaScript variables to PHP?

Is your function, which sets the hidden form value, being called? It is not in this example. You should have no problem modifying a hidden value before posting the form back to the server.

What does operator "dot" (.) mean?

There is a whole page in the MATLAB documentation dedicated to this topic: Array vs. Matrix Operations. The gist of it is below:

MATLAB® has two different types of arithmetic operations: array operations and matrix operations. You can use these arithmetic operations to perform numeric computations, for example, adding two numbers, raising the elements of an array to a given power, or multiplying two matrices.

Matrix operations follow the rules of linear algebra. By contrast, array operations execute element by element operations and support multidimensional arrays. The period character (.) distinguishes the array operations from the matrix operations. However, since the matrix and array operations are the same for addition and subtraction, the character pairs .+ and .- are unnecessary.

Regular expression [Any number]

if("123".search(/^\d+$/) >= 0){
   // its a number
}

Android Studio Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

  1. Go to \android\gradle\wrapper\gradle-wrapper.properties.
  2. Update the installing distribution version (all.zip) of Gradle in distributionUrl. As an example for Gradle version 6.8:

distributionUrl=https://services.gradle.org/distributions/gradle-6.8-all.zip

What are my options for storing data when using React Native? (iOS and Android)

We dont need redux-persist we can simply use redux for persistance.

react-redux + AsyncStorage = redux-persist

so inside createsotre file simply add these lines

store.subscribe(async()=> await AsyncStorage.setItem("store", JSON.stringify(store.getState())))

this will update the AsyncStorage whenever there are some changes in the redux store.

Then load the json converted store. when ever the app loads. and set the store again.

Because redux-persist creates issues when using wix react-native-navigation. If that's the case then I prefer to use simple redux with above subscriber function

php Replacing multiple spaces with a single space

Use preg_replace() and instead of [ \t\n\r] use \s:

$output = preg_replace('!\s+!', ' ', $input);

From Regular Expression Basic Syntax Reference:

\d, \w and \s

Shorthand character classes matching digits, word characters (letters, digits, and underscores), and whitespace (spaces, tabs, and line breaks). Can be used inside and outside character classes.

"Non-resolvable parent POM: Could not transfer artifact" when trying to refer to a parent pom from a child pom with ${parent.groupid}

As Nayan said the Path has to updated properly in my case the apache-maven was installed in C:\apache-maven and settings.xml was found inside C:\apache-maven\conf\settings.xml

if this doesn't work go to your local repos
in my case C:\Users\<<"name">>.m2\
and search for .lastUpdated and delete them
then build the maven

How to load data to hive from HDFS without removing the source file?

An alternative to 'LOAD DATA' is available in which the data will not be moved from your existing source location to hive data warehouse location.

You can use ALTER TABLE command with 'LOCATION' option. Here is below required command

ALTER TABLE table_name ADD PARTITION (date_col='2017-02-07') LOCATION 'hdfs/path/to/location/'

The only condition here is, the location should be a directory instead of file.

Hope this will solve the problem.

How do I check whether an array contains a string in TypeScript?

You can use the some method:

console.log(channelArray.some(x => x === "three")); // true

You can use the find method:

console.log(channelArray.find(x => x === "three")); // three

Or you can use the indexOf method:

console.log(channelArray.indexOf("three")); // 2

Can we pass model as a parameter in RedirectToAction?

Yes you can pass the model that you have shown using

return RedirectToAction("GetStudent", "Student", student1 );

assuming student1 is an instance of Student

which will generate the following url (assuming your using the default routes and the value of student1 are ID=4 and Name="Amit")

.../Student/GetStudent/4?Name=Amit

Internally the RedirectToAction() method builds a RouteValueDictionary by using the .ToString() value of each property in the model. However, binding will only work if all the properties in the model are simple properties and it fails if any properties are complex objects or collections because the method does not use recursion. If for example, Student contained a property List<string> Subjects, then that property would result in a query string value of

....&Subjects=System.Collections.Generic.List'1[System.String]

and binding would fail and that property would be null

How do I remove the old history from a git repository?

When rebase or push to head/master this error may occurred

remote: GitLab: You are not allowed to access some of the refs!
To git@giturl:main/xyz.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@giturl:main/xyz.git'

To resolve this issue in git dashboard should remove master branch from "Protected branches"

enter image description here

then you can run this command

git push -f origin master

or

git rebase --onto temp $1 master

Cookies on localhost with explicit domain

localhost: You can use: domain: ".app.localhost" and it will work. The 'domain' parameter needs 1 or more dots in the domain name for setting cookies. Then you can have sessions working across localhost subdomains such as: api.app.localhost:3000.

HTML/Javascript Button Click Counter

After looking at the code you're having typos, here is the updated code

var clicks = 0; // should be var not int
    function clickME() {
        clicks += 1;
        document.getElementById("clicks").innerHTML = clicks; //getElementById() not getElementByID() Which you corrected in edit
 }

Demo

Note: Don't use in-built handlers, as .click() is javascript function try giving different name like clickME()

React - how to pass state to another component

Move all of your state and your handleClick function from Header to your MainWrapper component.

Then pass values as props to all components that need to share this functionality.

class MainWrapper extends React.Component {
    constructor() {
        super();
        this.state = {
            sidbarPushCollapsed: false,
            profileCollapsed: false
        };
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState({
            sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
            profileCollapsed: !this.state.profileCollapsed

        });
    }
    render() {
        return (
           //...
           <Header 
               handleClick={this.handleClick} 
               sidbarPushCollapsed={this.state.sidbarPushCollapsed}
               profileCollapsed={this.state.profileCollapsed} />
        );

Then in your Header's render() method, you'd use this.props:

<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>

Java String to JSON conversion

Instead of JSONObject , you can use ObjectMapper to convert java object to json string

ObjectMapper mapper = new ObjectMapper();
String requestBean = mapper.writeValueAsString(yourObject);

Get pixel color from canvas, on mousemove

calling getImageData every time will slow the process ... to speed up things i recommend store image data and then you can get pix value easily and quickly, so do something like this for better performance

// keep it global
let imgData = false;  // initially no image data we have

// create some function block 
if(imgData === false){   
  // fetch once canvas data     
  var ctx = canvas.getContext("2d");
  imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
}
    // Prepare your X Y coordinates which you will be fetching from your mouse loc
    let x = 100;   // 
    let y = 100;
    // locate index of current pixel
    let index = (y * imgData.width + x) * 4;

        let red = imgData.data[index];
        let green = imgData.data[index+1];
        let blue = imgData.data[index+2];
        let alpha = imgData.data[index+3];
   // Output
   console.log('pix x ' + x +' y '+y+ ' index '+index +' COLOR '+red+','+green+','+blue+','+alpha);

ModalPopupExtender OK Button click event not firing?

Aspx

<ajax:ModalPopupExtender runat="server" ID="modalPop" 
            PopupControlID="pnlpopup" 
            TargetControlID="btnGo"
              BackgroundCssClass="modalBackground"
             DropShadow="true"
             CancelControlID="btnCancel" X="470" Y="300"   />


//Codebehind    
protected void OkButton_Clicked(object sender, EventArgs e)
    {

        modalPop.Hide();
        //Do something in codebehind
    }

And don't set the OK button as OkControlID.

How to tell if a string contains a certain character in JavaScript?

Use a regular expression to accomplish this.

function isAlphanumeric( str ) {
 return /^[0-9a-zA-Z]+$/.test(str);
}

Concatenating string and integer in python

String formatting, using the new-style .format() method (with the defaults .format() provides):

 '{}{}'.format(s, i)

Or the older, but "still sticking around", %-formatting:

 '%s%d' %(s, i)

In both examples above there's no space between the two items concatenated. If space is needed, it can simply be added in the format strings.

These provide a lot of control and flexibility about how to concatenate items, the space between them etc. For details about format specifications see this.

Single quotes vs. double quotes in C or C++

Single quotes are characters (char), double quotes are null-terminated strings (char *).

char c = 'x';
char *s = "Hello World";

How do I make a PHP form that submits to self?

Your submit button doesn't have a name. Add name="submit" to your submit button.

If you view source on the form in the browser, you'll see how it submits to self - the form's action attribute will contain the name of the current script - therefore when the form submits, it submits to itself. Edit for vanity sake!

Delete item from state array in react

I also had a same requirement to delete an element from array which is in state.

const array= [...this.state.selectedOption]
const found= array.findIndex(x=>x.index===k)
if(found !== -1){
   this.setState({
   selectedOption:array.filter(x => x.index !== k)
    })
 }

First I copied the elements into an array. Then checked whether the element exist in the array or not. Then only I have deleted the element from the state using the filter option.

How do you right-justify text in an HTML textbox?

Apply style="text-align: right" to the input tag. This will allow entry to be right-justified, and (at least in Firefox 3, IE 7 and Safari) will even appear to flow from the right.

How to round a floating point number up to a certain decimal place?

8.833333333339 (or 8.833333333333334, the result of 106.00/12) properly rounded to two decimal places is 8.83. Mathematically it sounds like what you want is a ceiling function. The one in Python's math module is named ceil:

import math

v = 8.8333333333333339
print(math.ceil(v*100)/100)  # -> 8.84

Respectively, the floor and ceiling functions generally map a real number to the largest previous or smallest following integer which has zero decimal places — so to use them for 2 decimal places the number is first multiplied by 102 (or 100) to shift the decimal point and is then divided by it afterwards to compensate.

If you don't want to use the math module for some reason, you can use this (minimally tested) implementation I just wrote:

def ceiling(x):
    n = int(x)
    return n if n-1 < x <= n else n+1

How all this relates to the linked Loan and payment calculator problem:

screenshot of loan calculator output

From the sample output it appears that they rounded up the monthly payment, which is what many call the effect of the ceiling function. This means that each month a little more than 1/12 of the total amount is being paid. That made the final payment a little smaller than usual — leaving a remaining unpaid balance of only 8.76.

It would have been equally valid to use normal rounding producing a monthly payment of 8.83 and a slightly higher final payment of 8.87. However, in the real world people generally don't like to have their payments go up, so rounding up each payment is the common practice — it also returns the money to the lender more quickly.

Console app arguments, how arguments are passed to Main method

All answers are awesome and explained everything very well

but I just want to point out different way for passing args to main method

in visual studio

  1. right click on Project then choose Properties
  2. go to Debug tab then on the Start Options section provide the app with your args

like this image

Properties window

and happy knowing secrets

move_uploaded_file gives "failed to open stream: Permission denied" error

This worked for me.

sudo adduser <username> www-data
sudo chown -R www-data:www-data /var/www
sudo chmod -R g+rwX /var/www

Then logout or reboot.

If SELinux complains, try the following

sudo semanage fcontext -a -t httpd_sys_rw_content_t '/var/www(/.*)?'
sudo restorecon -Rv '/var/www(/.*)?'

jQuery class within class selector

For this html:

<div class="outer">
     <div class="inner"></div>
</div>

This selector should work:

$('.outer > .inner')

How to insert default values in SQL table?

You can write in this way

GO
ALTER TABLE Table_name  ADD
column_name decimal(18, 2) NOT NULL CONSTRAINT Constant_name DEFAULT 0
GO
ALTER TABLE Table_name SET (LOCK_ESCALATION = TABLE)
GO
COMMIT

Modify XML existing content in C#

The XmlTextWriter is usually used for generating (not updating) XML content. When you load the xml file into an XmlDocument, you don't need a separate writer.

Just update the node you have selected and .Save() that XmlDocument.

Adding Apostrophe in every field in particular column for excel

More universal can be: for each v Selection : v.value = "'" & v.value : next and selecting range of cells before execution

Check string length in PHP

Because $xml->xpath always return an array, and strlen expects a string.

Delete files older than 3 months old in a directory using .NET

For example: To go My folder project on source, i need to up two folder. I make this algorim to 2 days week and into four hour

public static void LimpiarArchivosViejos()
    {
        DayOfWeek today = DateTime.Today.DayOfWeek;
        int hora = DateTime.Now.Hour;
        if(today == DayOfWeek.Monday || today == DayOfWeek.Tuesday && hora < 12 && hora > 8)
        {
            CleanPdfOlds();
            CleanExcelsOlds();
        }

    }
    private static void CleanPdfOlds(){
        string[] files = Directory.GetFiles("../../Users/Maxi/Source/Repos/13-12-2017_config_pdfListados/ApplicaAccWeb/Uploads/Reports");
        foreach (string file in files)
        {
            FileInfo fi = new FileInfo(file);
            if (fi.CreationTime < DateTime.Now.AddDays(-7))
                fi.Delete();
        }
    }
    private static void CleanExcelsOlds()
    {
        string[] files2 = Directory.GetFiles("../../Users/Maxi/Source/Repos/13-12-2017_config_pdfListados/ApplicaAccWeb/Uploads/Excels");
        foreach (string file in files2)
        {
            FileInfo fi = new FileInfo(file);
            if (fi.CreationTime < DateTime.Now.AddDays(-7))
                fi.Delete();
        }
    }

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

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

text/javascript is mentioned obsolete. See reference docs.

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

Also see this question on SO.

UPDATE:

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

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

This is what worked for me.

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

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

HttpURLConnection timeout settings

You can set timeout like this,

con.setConnectTimeout(connectTimeout);
con.setReadTimeout(socketTimeout);

How to call Oracle MD5 hash function?

To calculate MD5 hash of CLOB content field with my desired encoding without implicitly recoding content to AL32UTF8, I've used this code:

create or replace function clob2blob(AClob CLOB) return BLOB is
  Result BLOB;
  o1 integer;
  o2 integer;
  c integer;
  w integer;
begin
  o1 := 1;
  o2 := 1;
  c := 0;
  w := 0;
  DBMS_LOB.CreateTemporary(Result, true);
  DBMS_LOB.ConvertToBlob(Result, AClob, length(AClob), o1, o2, 0, c, w);
  return(Result);
end clob2blob;
/

update my_table t set t.hash = (rawtohex(DBMS_CRYPTO.Hash(clob2blob(t.content),2)));

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

"project property - CUDA Runtime API - GPU - NVCC Compilation Type"

Set the 64 bit compile option -m64 -cubin

The hint is at compile log. Like this:

nvcc.exe ~~~~~~ -machine 32 -ccbin ~~~~~

That "-machine 32" is problem.

First set 64bit compile option, next re setting hybrid compile option. Then u can see the succeed.

Import Certificate to Trusted Root but not to Personal [Command Line]

If there are multiple certificates in a pfx file (key + corresponding certificate and a CA certificate) then this command worked well for me:

certutil -importpfx c:\somepfx.pfx this works but still a password is needed to be typed in manually for private key. Including -p and "password" cause error too many arguments for certutil on XP

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

You can use the os/signal package to handle incoming signals. Ctrl+C is SIGINT, so you can use this to trap os.Interrupt.

c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func(){
    for sig := range c {
        // sig is a ^C, handle it
    }
}()

The manner in which you cause your program to terminate and print information is entirely up to you.

How to hide app title in android?

You can do it programatically: Or without action bar

//It's enough to remove the line
     requestWindowFeature(Window.FEATURE_NO_TITLE);

//But if you want to display  full screen (without action bar) write too

     getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
     WindowManager.LayoutParams.FLAG_FULLSCREEN);

     setContentView(R.layout.your_activity);

How to print a two dimensional array?

you can use the Utility mettod. Arrays.deeptoString();

 public static void main(String[] args) {
    int twoD[][] = new int[4][]; 
    twoD[0] = new int[1]; 
    twoD[1] = new int[2]; 
    twoD[2] = new int[3]; 
    twoD[3] = new int[4]; 

    System.out.println(Arrays.deepToString(twoD));

}

C++ String Declaring

C++ supplies a string class that can be used like this:

#include <string>
#include <iostream>

int main() {
    std::string Something = "Some text";
    std::cout << Something << std::endl;
}

How to write a cron that will run a script every day at midnight?

Quick guide to setup a cron job

Create a new text file, example: mycronjobs.txt

For each daily job (00:00, 03:45), save the schedule lines in mycronjobs.txt

00 00 * * * ruby path/to/your/script.rb
45 03 * * * path/to/your/script2.sh

Send the jobs to cron (everytime you run this, cron deletes what has been stored and updates with the new information in mycronjobs.txt)

crontab mycronjobs.txt

Extra Useful Information

See current cron jobs

crontab -l

Remove all cron jobs

crontab -r

package javax.mail and javax.mail.internet do not exist

Download javax.mail.jar and add it to your project using the following steps:

  1. Extract the mail.jar file
  2. Right click the project node (JavaMail), click Properties to change properties of the project
  3. Now go to Libraries Tab
  4. Click on Add JAR/Folder Button. A window opens up.
  5. Browse to the location where you have unzipped your Mail.jar
  6. Press ok
  7. Compile your program to check whether the JAR files have been successfully included

Phone number validation Android

Given the rules you specified:

upto length 13 and including character + infront.

(and also incorporating the min length of 10 in your code)

You're going to want a regex that looks like this:

^\+[0-9]{10,13}$

With the min and max lengths encoded in the regex, you can drop those conditions from your if() block.

Off topic: I'd suggest that a range of 10 - 13 is too limiting for an international phone number field; you're almost certain to find valid numbers that are both longer and shorter than this. I'd suggest a range of 8 - 20 to be safe.

[EDIT] OP states the above regex doesn't work due to the escape sequence. Not sure why, but an alternative would be:

^[+][0-9]{10,13}$

[EDIT 2] OP now adds that the + sign should be optional. In this case, the regex needs a question mark after the +, so the example above would now look like this:

^[+]?[0-9]{10,13}$

Google Chrome Printing Page Breaks

Actually one detail is missing from the answer that is selected as accepted (from Phil Ross)....

it DOES work in Chrome, and the solution is really silly!!

Both the parent and the element onto which you want to control page-breaking must be declared as:

position: relative

check out this fiddle: http://jsfiddle.net/petersphilo/QCvA5/5/show/

This is true for:

page-break-before
page-break-after
page-break-inside

However, controlling page-break-inside in Safari does not work (in 5.1.7, at least)

i hope this helps!!!

PS: The question below brought up that fact that recent versions of Chrome no longer respect this, even with the position: relative; trick. However, they do seem to respect:

-webkit-region-break-inside: avoid;

see this fiddle: http://jsfiddle.net/petersphilo/QCvA5/23/show

so i guess we have to add that now...

Hope this helps!

Clear back stack using fragments

It is working for me,try this one:

public void clearFragmentBackStack() {
        FragmentManager fm = getSupportFragmentManager();
        for (int i = 0; i < fm.getBackStackEntryCount() - 1; i++) {
            fm.popBackStack();
        }
    }

How to configure Docker port mapping to use Nginx as an upstream proxy?

@T0xicCode's answer is correct, but I thought I would expand on the details since it actually took me about 20 hours to finally get a working solution implemented.

If you're looking to run Nginx in its own container and use it as a reverse proxy to load balance multiple applications on the same server instance then the steps you need to follow are as such:

Link Your Containers

When you docker run your containers, typically by inputting a shell script into User Data, you can declare links to any other running containers. This means that you need to start your containers up in order and only the latter containers can link to the former ones. Like so:

#!/bin/bash
sudo docker run -p 3000:3000 --name API mydockerhub/api
sudo docker run -p 3001:3001 --link API:API --name App mydockerhub/app
sudo docker run -p 80:80 -p 443:443 --link API:API --link App:App --name Nginx mydockerhub/nginx

So in this example, the API container isn't linked to any others, but the App container is linked to API and Nginx is linked to both API and App.

The result of this is changes to the env vars and the /etc/hosts files that reside within the API and App containers. The results look like so:

/etc/hosts

Running cat /etc/hosts within your Nginx container will produce the following:

172.17.0.5  0fd9a40ab5ec
127.0.0.1   localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.3  App
172.17.0.2  API



ENV Vars

Running env within your Nginx container will produce the following:

API_PORT=tcp://172.17.0.2:3000
API_PORT_3000_TCP_PROTO=tcp
API_PORT_3000_TCP_PORT=3000
API_PORT_3000_TCP_ADDR=172.17.0.2

APP_PORT=tcp://172.17.0.3:3001
APP_PORT_3001_TCP_PROTO=tcp
APP_PORT_3001_TCP_PORT=3001
APP_PORT_3001_TCP_ADDR=172.17.0.3

I've truncated many of the actual vars, but the above are the key values you need to proxy traffic to your containers.

To obtain a shell to run the above commands within a running container, use the following:

sudo docker exec -i -t Nginx bash

You can see that you now have both /etc/hosts file entries and env vars that contain the local IP address for any of the containers that were linked. So far as I can tell, this is all that happens when you run containers with link options declared. But you can now use this information to configure nginx within your Nginx container.



Configuring Nginx

This is where it gets a little tricky, and there's a couple of options. You can choose to configure your sites to point to an entry in the /etc/hosts file that docker created, or you can utilize the ENV vars and run a string replacement (I used sed) on your nginx.conf and any other conf files that may be in your /etc/nginx/sites-enabled folder to insert the IP values.



OPTION A: Configure Nginx Using ENV Vars

This is the option that I went with because I couldn't get the /etc/hosts file option to work. I'll be trying Option B soon enough and update this post with any findings.

The key difference between this option and using the /etc/hosts file option is how you write your Dockerfile to use a shell script as the CMD argument, which in turn handles the string replacement to copy the IP values from ENV to your conf file(s).

Here's the set of configuration files I ended up with:

Dockerfile

FROM ubuntu:14.04
MAINTAINER Your Name <[email protected]>

RUN apt-get update && apt-get install -y nano htop git nginx

ADD nginx.conf /etc/nginx/nginx.conf
ADD api.myapp.conf /etc/nginx/sites-enabled/api.myapp.conf
ADD app.myapp.conf /etc/nginx/sites-enabled/app.myapp.conf
ADD Nginx-Startup.sh /etc/nginx/Nginx-Startup.sh

EXPOSE 80 443

CMD ["/bin/bash","/etc/nginx/Nginx-Startup.sh"]

nginx.conf

daemon off;
user www-data;
pid /var/run/nginx.pid;
worker_processes 1;


events {
    worker_connections 1024;
}


http {

    # Basic Settings

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 33;
    types_hash_max_size 2048;

    server_tokens off;
    server_names_hash_bucket_size 64;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;


    # Logging Settings
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;


    # Gzip Settings

gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 3;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/xml text/css application/x-javascript application/json;
    gzip_disable "MSIE [1-6]\.(?!.*SV1)";

    # Virtual Host Configs  
    include /etc/nginx/sites-enabled/*;

    # Error Page Config
    #error_page 403 404 500 502 /srv/Splash;


}

NOTE: It's important to include daemon off; in your nginx.conf file to ensure that your container doesn't exit immediately after launching.

api.myapp.conf

upstream api_upstream{
    server APP_IP:3000;
}

server {
    listen 80;
    server_name api.myapp.com;
    return 301 https://api.myapp.com/$request_uri;
}

server {
    listen 443;
    server_name api.myapp.com;

    location / {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
        proxy_pass http://api_upstream;
    }

}

Nginx-Startup.sh

#!/bin/bash
sed -i 's/APP_IP/'"$API_PORT_3000_TCP_ADDR"'/g' /etc/nginx/sites-enabled/api.myapp.com
sed -i 's/APP_IP/'"$APP_PORT_3001_TCP_ADDR"'/g' /etc/nginx/sites-enabled/app.myapp.com

service nginx start

I'll leave it up to you to do your homework about most of the contents of nginx.conf and api.myapp.conf.

The magic happens in Nginx-Startup.sh where we use sed to do string replacement on the APP_IP placeholder that we've written into the upstream block of our api.myapp.conf and app.myapp.conf files.

This ask.ubuntu.com question explains it very nicely: Find and replace text within a file using commands

GOTCHA On OSX, sed handles options differently, the -i flag specifically. On Ubuntu, the -i flag will handle the replacement 'in place'; it will open the file, change the text, and then 'save over' the same file. On OSX, the -i flag requires the file extension you'd like the resulting file to have. If you're working with a file that has no extension you must input '' as the value for the -i flag.

GOTCHA To use ENV vars within the regex that sed uses to find the string you want to replace you need to wrap the var within double-quotes. So the correct, albeit wonky-looking, syntax is as above.

So docker has launched our container and triggered the Nginx-Startup.sh script to run, which has used sed to change the value APP_IP to the corresponding ENV variable we provided in the sed command. We now have conf files within our /etc/nginx/sites-enabled directory that have the IP addresses from the ENV vars that docker set when starting up the container. Within your api.myapp.conf file you'll see the upstream block has changed to this:

upstream api_upstream{
    server 172.0.0.2:3000;
}

The IP address you see may be different, but I've noticed that it's usually 172.0.0.x.

You should now have everything routing appropriately.

GOTCHA You cannot restart/rerun any containers once you've run the initial instance launch. Docker provides each container with a new IP upon launch and does not seem to re-use any that its used before. So api.myapp.com will get 172.0.0.2 the first time, but then get 172.0.0.4 the next time. But Nginx will have already set the first IP into its conf files, or in its /etc/hosts file, so it won't be able to determine the new IP for api.myapp.com. The solution to this is likely to use CoreOS and its etcd service which, in my limited understanding, acts like a shared ENV for all machines registered into the same CoreOS cluster. This is the next toy I'm going to play with setting up.



OPTION B: Use /etc/hosts File Entries

This should be the quicker, easier way of doing this, but I couldn't get it to work. Ostensibly you just input the value of the /etc/hosts entry into your api.myapp.conf and app.myapp.conf files, but I couldn't get this method to work.

UPDATE: See @Wes Tod's answer for instructions on how to make this method work.

Here's the attempt that I made in api.myapp.conf:

upstream api_upstream{
    server API:3000;
}

Considering that there's an entry in my /etc/hosts file like so: 172.0.0.2 API I figured it would just pull in the value, but it doesn't seem to be.

I also had a couple of ancillary issues with my Elastic Load Balancer sourcing from all AZ's so that may have been the issue when I tried this route. Instead I had to learn how to handle replacing strings in Linux, so that was fun. I'll give this a try in a while and see how it goes.

Round double value to 2 decimal places

To remove the decimals from your double, take a look at this output

Obj C

double hellodouble = 10.025;
NSLog(@"Your value with 2 decimals: %.2f", hellodouble);
NSLog(@"Your value with no decimals: %.0f", hellodouble);

The output will be:

10.02 
10

Swift 2.1 and Xcode 7.2.1

let hellodouble:Double = 3.14159265358979
print(String(format:"Your value with 2 decimals: %.2f", hellodouble))
print(String(format:"Your value with no decimals: %.0f", hellodouble))

The output will be:

3.14 
3

Add IIS 7 AppPool Identities as SQL Server Logons

I figured it out through trial and error... the real chink in the armor was a little known setting in IIS in the Configuration Editor for the website in

Section: system.webServer/security/authentication/windowsAuthentication

From: ApplicationHost.config <locationpath='ServerName/SiteName' />

called useAppPoolCredentials (which is set to False by default. Set this to True and life becomes great again!!! Hope this saves pain for the next guy....

enter image description here

How to implement the --verbose or -v option into a script?

Building and simplifying @kindall's answer, here's what I typically use:

v_print = None
def main()
    parser = argparse.ArgumentParser()
    parser.add_argument('-v', '--verbosity', action="count", 
                        help="increase output verbosity (e.g., -vv is more than -v)")

    args = parser.parse_args()

    if args.verbosity:
        def _v_print(*verb_args):
            if verb_args[0] > (3 - args.verbosity):
                print verb_args[1]  
    else:
        _v_print = lambda *a: None  # do-nothing function

    global v_print
    v_print = _v_print

if __name__ == '__main__':
    main()

This then provides the following usage throughout your script:

v_print(1, "INFO message")
v_print(2, "WARN message")
v_print(3, "ERROR message")

And your script can be called like this:

% python verbose-tester.py -v
ERROR message

% python verbose=tester.py -vv
WARN message
ERROR message

% python verbose-tester.py -vvv
INFO message
WARN message
ERROR message

A couple notes:

  1. Your first argument is your error level, and the second is your message. It has the magic number of 3 that sets the upper bound for your logging, but I accept that as a compromise for simplicity.
  2. If you want v_print to work throughout your program, you have to do the junk with the global. It's no fun, but I challenge somebody to find a better way.

JavaScript: replace last occurrence of text in a string

I would suggest using the replace-last npm package.

_x000D_
_x000D_
var str = 'one two, one three, one four, one';_x000D_
var result = replaceLast(str, 'one', 'finish');_x000D_
console.log(result);
_x000D_
<script src="https://unpkg.com/replace-last@latest/replaceLast.js"></script>
_x000D_
_x000D_
_x000D_

This works for string and regex replacements.

Windows command to convert Unix line endings?

You can do this without additional tools in VBScript:

Do Until WScript.StdIn.AtEndOfStream
  WScript.StdOut.WriteLine WScript.StdIn.ReadLine
Loop

Put the above lines in a file unix2dos.vbs and run it like this:

cscript //NoLogo unix2dos.vbs <C:\path\to\input.txt >C:\path\to\output.txt

or like this:

type C:\path\to\input.txt | cscript //NoLogo unix2dos.vbs >C:\path\to\output.txt

You can also do it in PowerShell:

(Get-Content "C:\path\to\input.txt") -replace "`n", "`r`n" |
  Set-Content "C:\path\to\output.txt"

which could be further simplified to this:

(Get-Content "C:\path\to\input.txt") | Set-Content "C:\path\to\output.txt"

The above statement works without an explicit replacement, because Get-Content implicitly splits input files at any kind of linebreak (CR, LF, and CR-LF), and Set-Content joins the input array with Windows linebreaks (CR-LF) before writing it to a file.

NameError: name 'datetime' is not defined

It can also be used as below:

from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)

DataTrigger where value is NOT null?

Converter:

public class NullableToVisibilityConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value == null ? Visibility.Collapsed : Visibility.Visible;
    }
}

Binding:

Visibility="{Binding PropertyToBind, Converter={StaticResource nullableToVisibilityConverter}}"

Detecting user leaving page with react-router

For react-router v3.x

I had the same issue where I needed a confirmation message for any unsaved change on the page. In my case, I was using React Router v3, so I could not use <Prompt />, which was introduced from React Router v4.

I handled 'back button click' and 'accidental link click' with the combination of setRouteLeaveHook and history.pushState(), and handled 'reload button' with onbeforeunload event handler.

setRouteLeaveHook (doc) & history.pushState (doc)

  • Using only setRouteLeaveHook was not enough. For some reason, the URL was changed although the page remained the same when 'back button' was clicked.

      // setRouteLeaveHook returns the unregister method
      this.unregisterRouteHook = this.props.router.setRouteLeaveHook(
        this.props.route,
        this.routerWillLeave
      );
    
      ...
    
      routerWillLeave = nextLocation => {
        // Using native 'confirm' method to show confirmation message
        const result = confirm('Unsaved work will be lost');
        if (result) {
          // navigation confirmed
          return true;
        } else {
          // navigation canceled, pushing the previous path
          window.history.pushState(null, null, this.props.route.path);
          return false;
        }
      };
    

onbeforeunload (doc)

  • It is used to handle 'accidental reload' button

    window.onbeforeunload = this.handleOnBeforeUnload;
    
    ...
    
    handleOnBeforeUnload = e => {
      const message = 'Are you sure?';
      e.returnValue = message;
      return message;
    }
    

Below is the full component that I have written

  • note that withRouter is used to have this.props.router.
  • note that this.props.route is passed down from the calling component
  • note that currentState is passed as prop to have initial state and to check any change

    import React from 'react';
    import PropTypes from 'prop-types';
    import _ from 'lodash';
    import { withRouter } from 'react-router';
    import Component from '../Component';
    import styles from './PreventRouteChange.css';
    
    class PreventRouteChange extends Component {
      constructor(props) {
        super(props);
        this.state = {
          // initialize the initial state to check any change
          initialState: _.cloneDeep(props.currentState),
          hookMounted: false
        };
      }
    
      componentDidUpdate() {
    
       // I used the library called 'lodash'
       // but you can use your own way to check any unsaved changed
        const unsaved = !_.isEqual(
          this.state.initialState,
          this.props.currentState
        );
    
        if (!unsaved && this.state.hookMounted) {
          // unregister hooks
          this.setState({ hookMounted: false });
          this.unregisterRouteHook();
          window.onbeforeunload = null;
        } else if (unsaved && !this.state.hookMounted) {
          // register hooks
          this.setState({ hookMounted: true });
          this.unregisterRouteHook = this.props.router.setRouteLeaveHook(
            this.props.route,
            this.routerWillLeave
          );
          window.onbeforeunload = this.handleOnBeforeUnload;
        }
      }
    
      componentWillUnmount() {
        // unregister onbeforeunload event handler
        window.onbeforeunload = null;
      }
    
      handleOnBeforeUnload = e => {
        const message = 'Are you sure?';
        e.returnValue = message;
        return message;
      };
    
      routerWillLeave = nextLocation => {
        const result = confirm('Unsaved work will be lost');
        if (result) {
          return true;
        } else {
          window.history.pushState(null, null, this.props.route.path);
          if (this.formStartEle) {
            this.moveTo.move(this.formStartEle);
          }
          return false;
        }
      };
    
      render() {
        return (
          <div>
            {this.props.children}
          </div>
        );
      }
    }
    
    PreventRouteChange.propTypes = propTypes;
    
    export default withRouter(PreventRouteChange);
    

Please let me know if there is any question :)

How to return only 1 row if multiple duplicate rows and still return rows that are not duplicates?

select t.*
from (
    select RequestID, max(CreatedDate) as MaxCreatedDate
    from table1
    group by RequestID
) tm
inner join table1 t on tm.RequestID = t.RequestID and tm.MaxCreatedDate = t.CreatedDate

Make git automatically remove trailing whitespace before committing

Please try my pre-commit hooks, it can auto detect trailing-whitespace and remove it. Thank you!

it can work under GitBash(windows), Mac OS X and Linux!


Snapshot:

$ git commit -am "test"
auto remove trailing whitespace in foobar/main.m!
auto remove trailing whitespace in foobar/AppDelegate.m!
[master 80c11fe] test
1 file changed, 2 insertions(+), 2 deletions(-)

How to add parameters to a HTTP GET request in Android?

As of HttpComponents 4.2+ there is a new class URIBuilder, which provides convenient way for generating URIs.

You can use either create URI directly from String URL:

List<NameValuePair> listOfParameters = ...;

URI uri = new URIBuilder("http://example.com:8080/path/to/resource?mandatoryParam=someValue")
    .addParameter("firstParam", firstVal)
    .addParameter("secondParam", secondVal)
    .addParameters(listOfParameters)
    .build();

Otherwise, you can specify all parameters explicitly:

URI uri = new URIBuilder()
    .setScheme("http")
    .setHost("example.com")
    .setPort(8080)
    .setPath("/path/to/resource")
    .addParameter("mandatoryParam", "someValue")
    .addParameter("firstParam", firstVal)
    .addParameter("secondParam", secondVal)
    .addParameters(listOfParameters)
    .build();

Once you have created URI object, then you just simply need to create HttpGet object and perform it:

//create GET request
HttpGet httpGet = new HttpGet(uri);
//perform request
httpClient.execute(httpGet ...//additional parameters, handle response etc.

Spring 3.0: Unable to locate Spring NamespaceHandler for XML schema namespace

Did you try putting all your jars directly in the WEB-INF/lib dir instead of sub-dirs of that?

No WEB-INF/lib/spring/org.springframework.aop-3.0.0.RELEASE.jar, just WEB-INF/lib/org.springframework.aop-3.0.0.RELEASE.jar

Same with the rest of the jars.

How to set custom location for local installation of npm package?

If you want this in config, you can set npm config like so:

npm config set prefix "$(pwd)/vendor/node_modules"

or

npm config set prefix "$HOME/vendor/node_modules"

Check your config with

npm config ls -l

Or as @pje says and use the --prefix flag

"Could not run curl-config: [Errno 2] No such file or directory" when installing pycurl

I encountered the same problem whilst trying to get Shinken 2.0.3 to fire up on Ubuntu. Eventually I did a full uninstall then reinstalled Shinken with pip -v. As it cleaned up, it mentioned:

Warning: missing python-pycurl lib, you MUST install it before launch the shinken daemons

Installed that with apt-get, and all the brokers fired up as expected :-)

How to perform case-insensitive sorting in JavaScript?

In support of the accepted answer I would like to add that the function below seems to change the values in the original array to be sorted so that not only will it sort lower case but upper case values will also be changed to lower case. This is a problem for me because even though I wish to see Mary next to mary, I do not wish that the case of the first value Mary be changed to lower case.

myArray.sort(
  function(a, b) {
    if (a.toLowerCase() < b.toLowerCase()) return -1;
    if (a.toLowerCase() > b.toLowerCase()) return 1;
    return 0;
  }
);

In my experiments, the following function from the accepted answer sorts correctly but does not change the values.

["Foo", "bar"].sort(function (a, b) {
    return a.toLowerCase().localeCompare(b.toLowerCase());
});

How to obtain the start time and end time of a day?

I tried this code and it works well!

final ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
final ZonedDateTime startofDay =
    now.toLocalDate().atStartOfDay(ZoneOffset.UTC);
final ZonedDateTime endOfDay =
    now.toLocalDate().atTime(LocalTime.MAX).atZone(ZoneOffset.UTC);

How do I use tools:overrideLibrary in a build.gradle file?

<manifest xmlns:tools="http://schemas.android.com/tools" ... >
  <uses-sdk tools:overrideLibrary="nl.innovalor.ocr, nl.innovalor.corelib" />

I was facing the issue of conflict between different min sdk versions. So this solution worked for me.

How to stop line breaking in vim

If, like me, you're running gVim on Windows then your .vimrc file may be sourcing another 'example' Vimscript file that automatically sets textwidth (in my case to 78) for text files.

My answer to a similar question as this one – How to stop gVim wrapping text at column 80 – on the Vi and Vim Stack Exchange site:

In my case, Vitor's comment suggested I run the following:

:verbose set tw?

Doing so gave me the following output:

textwidth=78
      Last set from C:\Program Files (x86)\Vim\vim74\vimrc_example.vim

In vimrc_example.vim, I found the relevant lines:

" Only do this part when compiled with support for autocommands.
if has("autocmd")

  ...

  " For all text files set 'textwidth' to 78 characters.
  autocmd FileType text setlocal textwidth=78

  ...

And I found that my .vimrc is sourcing that file:

source $VIMRUNTIME/vimrc_example.vim

In my case, I don't want textwidth to be set for any files, so I just commented out the relevant line in vimrc_example.vim.

How do I increase the capacity of the Eclipse output console?

For C++ users, to increase the Build console output size see here

ie Windows > Preference > C/C++ > Build > Console

Reload an iframe with jQuery

//refresh all iframes on page

var f_list = document.getElementsByTagName('iframe');

 for (var i = 0, f; f = f_list[i]; i++) {
                            f.src = f.src;
                        }

How do I create a comma-separated list from an array in PHP?

If doing quoted answers, you can do

$commaList = '"'.implode( '" , " ', $fruit). '"';

the above assumes that fruit is non-null. If you don't want to make that assumption you can use an if-then-else statement or ternary (?:) operator.

Call Activity method from adapter

if (parent.getContext() instanceof yourActivity) {
  //execute code
}

this condition will enable you to execute something if the Activity which has the GroupView that requesting views from the getView() method of your adapter is yourActivity

NOTE : parent is that GroupView

Resizing an iframe based on content

get iframe content height then give it to this iframe

 var iframes = document.getElementsByTagName("iframe");
 for(var i = 0, len = iframes.length; i<len; i++){
      window.frames[i].onload = function(_i){
           return function(){
                     iframes[_i].style.height = window.frames[_i].document.body.scrollHeight + "px";
                     }
      }(i);
 }

Formatting code snippets for blogging on Blogger

This can be done fairly easily with SyntaxHighlighter. I have step-by-step instructions for setting up SyntaxHighlighter in Blogger on my blog. SyntaxHighlighter is very easy to use. It lets you post snippets in raw form and then wrap them in pre blocks like:

<pre name="code" class="brush: erlang"><![CDATA[
-module(trim).

-export([string_strip_right/1, reverse_tl_reverse/1, bench/0]).

bench() -> [nbench(N) || N <- [1,1000,1000000]].

nbench(N) -> {N, bench(["a" || _ <- lists:seq(1,N)])}.

bench(String) ->
    {{string_strip_right,
    lists:sum([
        element(1, timer:tc(trim, string_strip_right, [String]))
        || _ <- lists:seq(1,1000)])},
    {reverse_tl_reverse,
    lists:sum([
        element(1, timer:tc(trim, reverse_tl_reverse, [String]))
        || _ <- lists:seq(1,1000)])}}.

string_strip_right(String) -> string:strip(String, right, $\n).

reverse_tl_reverse(String) ->
    lists:reverse(tl(lists:reverse(String))).
]]></pre>

Just change the brush name to "python" or "java" or "javascript" and paste in the code of your choice. The CDATA tagging let's you put pretty much any code in there without worrying about entity escaping or other typical annoyances of code blogging.

EditText request focus

Yes, I got the answer.. just simply edit the manifest file as:

        <activity android:name=".MainActivity"
        android:label="@string/app_name"
        android:windowSoftInputMode="stateAlwaysVisible" />

and set EditText.requestFocus() in onCreate()..

Thanks..

Kubernetes how to make Deployment to update image

UPDATE 2019-06-24

Based on the @Jodiug comment if you have a 1.15 version you can use the command:

kubectl rollout restart deployment/demo

Read more on the issue:

https://github.com/kubernetes/kubernetes/issues/13488


Well there is an interesting discussion about this subject on the kubernetes GitHub project. See the issue: https://github.com/kubernetes/kubernetes/issues/33664

From the solutions described there, I would suggest one of two.

First

1.Prepare deployment

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: demo
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: demo
    spec:
      containers:
      - name: demo
        image: registry.example.com/apps/demo:master
        imagePullPolicy: Always
        env:
        - name: FOR_GODS_SAKE_PLEASE_REDEPLOY
          value: 'THIS_STRING_IS_REPLACED_DURING_BUILD'

2.Deploy

sed -ie "s/THIS_STRING_IS_REPLACED_DURING_BUILD/$(date)/g" deployment.yml
kubectl apply -f deployment.yml

Second (one liner):

kubectl patch deployment web -p \
  "{\"spec\":{\"template\":{\"metadata\":{\"labels\":{\"date\":\"`date +'%s'`\"}}}}}"

Of course the imagePullPolicy: Always is required on both cases.