Programs & Examples On #Nslock

An NSLock object is used to coordinate the operation of multiple threads of execution within the same application. An NSLock object can be used to mediate access to an application’s global data or to protect a critical section of code, allowing it to run atomically.

How does @synchronized lock/unlock in Objective-C?

Actually

{
  @synchronized(self) {
    return [[myString retain] autorelease];
  }
}

transforms directly into:

// needs #import <objc/objc-sync.h>
{
  objc_sync_enter(self)
    id retVal = [[myString retain] autorelease];
  objc_sync_exit(self);
  return retVal;
}

This API available since iOS 2.0 and imported using...

#import <objc/objc-sync.h>

How to send a JSON object using html form data

I found a way to pass a JSON message using only a HTML form.

This example is for GraphQL but it will work for any endpoint that is expecting a JSON message.

GrapqhQL by default expects a parameter called operations where you can add your query or mutation in JSON format. In this specific case I am invoking this query which is requesting to get allUsers and return the userId of each user.

{ 
 allUsers 
  { 
  userId 
  }
}

I am using a text input to demonstrate how to use it, but you can change it for a hidden input to hide the query from the user.

<html>
<body>
    <form method="post" action="http://localhost:8080/graphql">
        <input type="text" name="operations" value="{&quot;query&quot;: &quot;{ allUsers { userId } }&quot;, "variables":  {}}"/>
        <input type="submit" />
    </form>
</body>
</html>

In order to make this dynamic you will need JS to transport the values of the text fields to the query string before submitting your form. Anyway I found this approach very interesting. Hope it helps.

Convert alphabet letters to number in Python

This is very simple script to do what you are asking for ! try this:

#!/usr/bin/env python3

def remove(string): 
    return string.replace(" ", "")

dict = {'a': '1', 
    'b': '2',
    'c': '3',
    'd': '4',
    'e': '5',
    'f': '6',
    'g': '7',
    'h': '8',
    'i': '9',
    'j': '10',
    'k': '11',
    'l': '12',
    'm': '13',
    'n': '14',
    'o': '15',
    'p': '16',
    'q': '17',
    'r': '18',
    's': '19',
    't': '20',
    'u': '21',
    'v': '22',
    'w': '23',
    'x': '24',
    'y': '25',
    'z': '26',
}

word = remove(input(''))

for x in word:
    print(dict[x])

## or ##
#index = 0
#for x in word:
#   print(dict[word[index]])
#   index = index + 1

Get lengths of a list in a jinja2 template

Alex' comment looks good but I was still confused with using range. The following worked for me while working on a for condition using length within range.

{% for i in range(0,(nums['list_users_response']['list_users_result']['users'])| length) %}
<li>    {{ nums['list_users_response']['list_users_result']['users'][i]['user_name'] }} </li>
{% endfor %}

How can I get color-int from color resource?

Based on the new Android Support Library (and this update), now you should call:

ContextCompat.getColor(context, R.color.name.color);

According to the documentation:

public int getColor (int id)

This method was deprecated in API level 23. Use getColor(int, Theme) instead

It is the same solution for getResources().getColorStateList(id):

You have to change it like this:

ContextCompat.getColorStateList(getContext(),id);

EDIT 2019

Regarding ThemeOverlay use the context of the closest view:

val color = ContextCompat.getColor(
  closestView.context,
  R.color.name.color
)

So this way you get the right color based on your ThemeOverlay.

Specially needed when in same activity you use different themes, like dark/light theme. If you would like to understand more about Themes and Styles this talk is suggested: Developing Themes with Style

Nick Butcher - Droidcon Berlin - Developing Themes with Style

How to order a data frame by one descending and one ascending column?

In @dudusan's example, you could also reverse the order of I1, and then sort ascending:

> rum <- read.table(textConnection("P1  P2  P3  T1  T2  T3  I1  I2
+   2   3   5   52  43  61  6   b
+   6   4   3   72  NA  59  1   a
+   1   5   6   55  48  60  6   f
+   2   4   4   65  64  58  2   b
+   1   5   6   55  48  60  6   c"), header = TRUE)
> f=factor(rum$I1)   
> levels(f) <- sort(levels(f), decreasing = TRUE)
> rum[order(as.character(f), rum$I2), ]
  P1 P2 P3 T1 T2 T3 I1 I2
1  2  3  5 52 43 61  6  b
5  1  5  6 55 48 60  6  c
3  1  5  6 55 48 60  6  f
4  2  4  4 65 64 58  2  b
2  6  4  3 72 NA 59  1  a
> 

This seems a bit shorter, you don't reverse the order of I2 twice.

How can I sort a dictionary by key?

There is an easy way to sort a dictionary.

According to your question,

The solution is :

c={2:3, 1:89, 4:5, 3:0}
y=sorted(c.items())
print y

(Where c,is the name of your dictionary.)

This program gives the following output:

[(1, 89), (2, 3), (3, 0), (4, 5)]

like u wanted.

Another example is:

d={"John":36,"Lucy":24,"Albert":32,"Peter":18,"Bill":41}
x=sorted(d.keys())
print x

Gives the output:['Albert', 'Bill', 'John', 'Lucy', 'Peter']

y=sorted(d.values())
print y

Gives the output:[18, 24, 32, 36, 41]

z=sorted(d.items())
print z

Gives the output:

[('Albert', 32), ('Bill', 41), ('John', 36), ('Lucy', 24), ('Peter', 18)]

Hence by changing it into keys, values and items , you can print like what u wanted.Hope this helps!

Is <img> element block level or inline level?

<img> is a replaced element; it has a display value of inline by default, but its default dimensions are defined by the embedded image's intrinsic values, like it were inline-block. You can set properties like border/border-radius, padding/margin, width, height, etc. on an image.

Replaced elements : They're elements whose contents are not affected by the current document's styles. The position of the replaced element can be affected using CSS, but not the contents of the replaced element itself.

Referenece : https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img

What is the largest TCP/IP network port number allowable for IPv4?

Valid numbers for ports are: 0 to 2^16-1 = 0 to 65535
That is because a port number is 16 bit length.

However ports are divided into:
Well-known ports: 0 to 1023 (used for system services e.g. HTTP, FTP, SSH, DHCP ...)
Registered/user ports: 1024 to 49151 (you can use it for your server, but be careful some famous applications: like Microsoft SQL Server database management system (MSSQL) server or Apache Derby Network Server are already taking from this range i.e. it is not recommended to assign the port of MSSQL to your server otherwise if MSSQL is running then your server most probably will not run because of port conflict )
Dynamic/private ports: 49152 to 65535. (not used for the servers rather the clients e.g. in NATing service)

In programming you can use any numbers 0 to 65535 for your server, however you should stick to the ranges mentioned above, otherwise some system services or some applications will not run because of port conflict.
Check the list of most ports here: https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers

Query to get only numbers from a string

With the previous queries I get these results:

'AAAA1234BBBB3333' >>>> Output: 1234

'-çã+0!\aº1234' >>>> Output: 0

The code below returns All numeric chars:

1st output: 12343333

2nd output: 01234

declare @StringAlphaNum varchar(255)
declare @Character varchar
declare @SizeStringAlfaNumerica int
declare @CountCharacter int

set @StringAlphaNum = 'AAAA1234BBBB3333'
set @SizeStringAlfaNumerica = len(@StringAlphaNum)
set @CountCharacter = 1

while isnumeric(@StringAlphaNum) = 0
begin
    while @CountCharacter < @SizeStringAlfaNumerica
        begin
            if substring(@StringAlphaNum,@CountCharacter,1) not like '[0-9]%'
            begin
                set @Character = substring(@StringAlphaNum,@CountCharacter,1)
                set @StringAlphaNum = replace(@StringAlphaNum, @Character, '')
            end
    set @CountCharacter = @CountCharacter + 1
    end
    set @CountCharacter = 0
end
select @StringAlphaNum

How do I install a plugin for vim?

To expand on Karl's reply, Vim looks in a specific set of directories for its runtime files. You can see that set of directories via :set runtimepath?. In order to tell Vim to also look inside ~/.vim/vim-haml you'll want to add

set runtimepath+=$HOME/.vim/vim-haml

to your ~/.vimrc. You'll likely also want the following in your ~/.vimrc to enable all the functionality provided by vim-haml.

filetype plugin indent on
syntax on

You can refer to the 'runtimepath' and :filetype help topics in Vim for more information.

How to merge 2 List<T> and removing duplicate values from it in C#

why not simply eg

var newList = list1.Union(list2)/*.Distinct()*//*.ToList()*/;

oh ... according to the documentation you can leave out the .Distinct()

This method excludes duplicates from the return set

Get the correct week number of a given date

Good news! A pull request adding System.Globalization.ISOWeek to .NET Core was just merged and is currently slated for the 3.0 release. Hopefully it will propagate to the other .NET platforms in a not-too-distant future.

The type has the following signature, which should cover most ISO week needs:

namespace System.Globalization
{
    public static class ISOWeek
    {
        public static int GetWeekOfYear(DateTime date);
        public static int GetWeeksInYear(int year);
        public static int GetYear(DateTime date);
        public static DateTime GetYearEnd(int year);
        public static DateTime GetYearStart(int year);
        public static DateTime ToDateTime(int year, int week, DayOfWeek dayOfWeek);
    }
}

You can find the source code here.

UPDATE: These APIs have also been included in the 2.1 version of .NET Standard.

SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

You need to replace it as WHERE clockDate = { fn CURRENT_DATE() } AND userName = 'test'. Please remove extra ")" from { fn CURRENT_DATE() })

JavaScript Regular Expression Email Validation

this is the one i am using on my page.

http://www.zparacha.com/validate-email-address-using-javascript-regular-expression/

/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/

How do I install cygwin components from the command line?

Cygwin's setup accepts command-line arguments to install packages from the command-line.

e.g. setup-x86.exe -q -P packagename1,packagename2 to install packages without any GUI interaction ('unattended setup mode').

(Note that you need to use setup-x86.exe or setup-x86_64.exe as appropriate.)

See http://cygwin.com/packages/ for the package list.

How to get current user, and how to use User class in MVC5?

If you want the ApplicationUser object in one line of code (if you have the latest ASP.NET Identity installed), try:

ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

You'll need the following using statements:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

How to test if a DataSet is empty?

We can check total three ways.

  1. if(ds != null)
  2. if(ds.Tables.Count > 0 )
  3. if(ds.Tables[0].Rows.Count > 0)

Iterating over dictionaries using 'for' loops

I have a use case where I have to iterate through the dict to get the key, value pair, also the index indicating where I am. This is how I do it:

d = {'x': 1, 'y': 2, 'z': 3} 
for i, (key, value) in enumerate(d.items()):
   print(i, key, value)

Note that the parentheses around the key, value are important, without them, you'd get an ValueError "not enough values to unpack".

How do you simulate Mouse Click in C#?

they are some needs i can't see to dome thing like Keith or Marcos Placona did instead of just doing

using System;
using System.Windows.Forms;

namespace WFsimulateMouseClick
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            button1_Click(button1, new MouseEventArgs(System.Windows.Forms.MouseButtons.Left, 1, 1, 1, 1));

            //by the way
            //button1.PerformClick();
            // and
            //button1_Click(button1, new EventArgs());
            // are the same
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("clicked");
        }
    }
}

Where to place and how to read configuration resource files in servlet based application?

It's your choice. There are basically three ways in a Java web application archive (WAR):


1. Put it in classpath

So that you can load it by ClassLoader#getResourceAsStream() with a classpath-relative path:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("foo.properties");
// ...
Properties properties = new Properties();
properties.load(input);

Here foo.properties is supposed to be placed in one of the roots which are covered by the default classpath of a webapp, e.g. webapp's /WEB-INF/lib and /WEB-INF/classes, server's /lib, or JDK/JRE's /lib. If the propertiesfile is webapp-specific, best is to place it in /WEB-INF/classes. If you're developing a standard WAR project in an IDE, drop it in src folder (the project's source folder). If you're using a Maven project, drop it in /main/resources folder.

You can alternatively also put it somewhere outside the default classpath and add its path to the classpath of the appserver. In for example Tomcat you can configure it as shared.loader property of Tomcat/conf/catalina.properties.

If you have placed the foo.properties it in a Java package structure like com.example, then you need to load it as below

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("com/example/foo.properties");
// ...

Note that this path of a context class loader should not start with a /. Only when you're using a "relative" class loader such as SomeClass.class.getClassLoader(), then you indeed need to start it with a /.

ClassLoader classLoader = getClass().getClassLoader();
InputStream input = classLoader.getResourceAsStream("/com/example/foo.properties");
// ...

However, the visibility of the properties file depends then on the class loader in question. It's only visible to the same class loader as the one which loaded the class. So, if the class is loaded by e.g. server common classloader instead of webapp classloader, and the properties file is inside webapp itself, then it's invisible. The context class loader is your safest bet so you can place the properties file "everywhere" in the classpath and/or you intend to be able to override a server-provided one from the webapp on.


2. Put it in webcontent

So that you can load it by ServletContext#getResourceAsStream() with a webcontent-relative path:

InputStream input = getServletContext().getResourceAsStream("/WEB-INF/foo.properties");
// ...

Note that I have demonstrated to place the file in /WEB-INF folder, otherwise it would have been public accessible by any webbrowser. Also note that the ServletContext is in any HttpServlet class just accessible by the inherited GenericServlet#getServletContext() and in Filter by FilterConfig#getServletContext(). In case you're not in a servlet class, it's usually just injectable via @Inject.


3. Put it in local disk file system

So that you can load it the usual java.io way with an absolute local disk file system path:

InputStream input = new FileInputStream("/absolute/path/to/foo.properties");
// ...

Note the importance of using an absolute path. Relative local disk file system paths are an absolute no-go in a Java EE web application. See also the first "See also" link below.


Which to choose?

Just weigh the advantages/disadvantages in your own opinion of maintainability.

If the properties files are "static" and never needs to change during runtime, then you could keep them in the WAR.

If you prefer being able to edit properties files from outside the web application without the need to rebuild and redeploy the WAR every time, then put it in the classpath outside the project (if necessary add the directory to the classpath).

If you prefer being able to edit properties files programmatically from inside the web application using Properties#store() method, put it outside the web application. As the Properties#store() requires a Writer, you can't go around using a disk file system path. That path can in turn be passed to the web application as a VM argument or system property. As a precaution, never use getRealPath(). All changes in deploy folder will get lost on a redeploy for the simple reason that the changes are not reflected back in original WAR file.

See also:

Java: Calculating the angle between two points in degrees

Why is everyone complicating this?

The only problem is Math.atan2( x , y)

The corret answer is Math.atan2( y, x)

All they did was mix the variable order for Atan2 causing it to reverse the degree of rotation.

All you had to do was look up the syntax https://www.google.com/amp/s/www.geeksforgeeks.org/java-lang-math-atan2-java/amp/

I need an unordered list without any bullets

If you wanted to accomplish this with pure HTML alone, this solution will work across all major browsers:

Description Lists

Simply using the following HTML:

_x000D_
_x000D_
    <dl>
      <dt>List Item 1</dt>
        <dd>Sub-Item 1.1</dd>
      <dt>List Item 2</dt>
        <dd>Sub-Item 2.1</dd>
        <dd>Sub-Item 2.2</dd>
        <dd>Sub-Item 2.3</dd>
      <dt>List Item 3</dt>
        <dd>Sub-Item 3.1</dd>
    </dl>
_x000D_
_x000D_
_x000D_

Example here: https://jsfiddle.net/zumcmvma/2/

Reference here: https://www.w3schools.com/tags/tag_dl.asp

angularjs - ng-repeat: access key and value from JSON array object

Solution I have json object which has data

[{"name":"Ata","email":"[email protected]"}]

You can use following approach to iterate through ng-repeat and use table format instead of list.

<div class="container" ng-controller="fetchdataCtrl">    
  <ul ng-repeat="item in numbers">
    <li>            
      {{item.name}}: {{item.email}}
    </li>
  </ul>     
</div>

How do you uninstall a python package that was installed using distutils?

It varies based on the options that you pass to install and the contents of the distutils configuration files on the system/in the package. I don't believe that any files are modified outside of directories specified in these ways.

Notably, distutils does not have an uninstall command at this time.

It's also noteworthy that deleting a package/egg can cause dependency issues – utilities like easy_install attempt to alleviate such problems.

Find nginx version?

In my case, I try to add sudo

sudo nginx -v

enter image description here

Use find command but exclude files in two directories

Use

find \( -path "./tmp" -o -path "./scripts" \) -prune -o  -name "*_peaks.bed" -print

or

find \( -path "./tmp" -o -path "./scripts" \) -prune -false -o  -name "*_peaks.bed"

or

find \( -path "./tmp" -path "./scripts" \) ! -prune -o  -name "*_peaks.bed"

The order is important. It evaluates from left to right. Always begin with the path exclusion.

Explanation

Do not use -not (or !) to exclude whole directory. Use -prune. As explained in the manual:

-prune    The primary shall always evaluate as  true;  it
          shall  cause  find  not  to descend the current
          pathname if it is a directory.  If  the  -depth
          primary  is specified, the -prune primary shall
          have no effect.

and in the GNU find manual:

-path pattern
              [...]
              To ignore  a  whole
              directory  tree,  use  -prune rather than checking
              every file in the tree.

Indeed, if you use -not -path "./pathname", find will evaluate the expression for each node under "./pathname".

find expressions are just condition evaluation.

  • \( \) - groups operation (you can use -path "./tmp" -prune -o -path "./scripts" -prune -o, but it is more verbose).
  • -path "./script" -prune - if -path returns true and is a directory, return true for that directory and do not descend into it.
  • -path "./script" ! -prune - it evaluates as (-path "./script") AND (! -prune). It revert the "always true" of prune to always false. It avoids printing "./script" as a match.
  • -path "./script" -prune -false - since -prune always returns true, you can follow it with -false to do the same than !.
  • -o - OR operator. If no operator is specified between two expressions, it defaults to AND operator.

Hence, \( -path "./tmp" -o -path "./scripts" \) -prune -o -name "*_peaks.bed" -print is expanded to:

[ (-path "./tmp" OR -path "./script") AND -prune ] OR ( -name "*_peaks.bed" AND print )

The print is important here because without it is expanded to:

{ [ (-path "./tmp" OR -path "./script" )  AND -prune ]  OR (-name "*_peaks.bed" ) } AND print

-print is added by find - that is why most of the time, you do not need to add it in you expression. And since -prune returns true, it will print "./script" and "./tmp".

It is not necessary in the others because we switched -prune to always return false.

Hint: You can use find -D opt expr 2>&1 1>/dev/null to see how it is optimized and expanded,
find -D search expr 2>&1 1>/dev/null to see which path is checked.

web-api POST body object always null

If using Postman, make sure that:

  • You have set a "Content-Type" header to "application/json"
  • You are sending the body as "raw"
  • You don't need to specify the parameter name anywhere if you are using [FromBody]

I was stupidly trying to send my JSON as form data, duh...

How to extract a string using JavaScript Regex?

You need to use the m flag:

multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string)

Also put the * in the right place:

"DATE:20091201T220000\r\nSUMMARY:Dad's birthday".match(/^SUMMARY\:(.*)$/gm);
//------------------------------------------------------------------^    ^
//-----------------------------------------------------------------------|

What algorithms compute directions from point A to point B on a map?

This is pure speculation on my part, but I suppose that they may use an influence map data structure overlaying the directed map in order to narrow the search domain. This would allow the search algorithm to direct the path to major routes when the desired trip is long.

Given that this is a Google app, it's also reasonable to suppose that a lot of the magic is done via extensive caching. :) I wouldn't be surprised if caching the top 5% most common Google Map route requests allowed for a large chunk (20%? 50%?) of requests to be answered by a simple look-up.

How to select the last record of a table in SQL?

It is always a good practice in your table design to have an automatic row identifier, such as

 [RowID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL

, then you can identify your last row by

 select * from yourTable where rowID =  @@IDENTITY 

Global and local variables in R

Variables declared inside a function are local to that function. For instance:

foo <- function() {
    bar <- 1
}
foo()
bar

gives the following error: Error: object 'bar' not found.

If you want to make bar a global variable, you should do:

foo <- function() {
    bar <<- 1
}
foo()
bar

In this case bar is accessible from outside the function.

However, unlike C, C++ or many other languages, brackets do not determine the scope of variables. For instance, in the following code snippet:

if (x > 10) {
    y <- 0
}
else {
    y <- 1
}

y remains accessible after the if-else statement.

As you well say, you can also create nested environments. You can have a look at these two links for understanding how to use them:

  1. http://stat.ethz.ch/R-manual/R-devel/library/base/html/environment.html
  2. http://stat.ethz.ch/R-manual/R-devel/library/base/html/get.html

Here you have a small example:

test.env <- new.env()

assign('var', 100, envir=test.env)
# or simply
test.env$var <- 100

get('var') # var cannot be found since it is not defined in this environment
get('var', envir=test.env) # now it can be found

oracle SQL how to remove time from date

You can use TRUNC on DateTime to remove Time part of the DateTime. So your where clause can be:

AND TRUNC(p1.PA_VALUE) >= TO_DATE('25/10/2012', 'DD/MM/YYYY')

The TRUNCATE (datetime) function returns date with the time portion of the day truncated to the unit specified by the format model.

Embed youtube videos that play in fullscreen automatically

This was pretty well answered over here: How to make a YouTube embedded video a full page width one?

If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)

<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>

of the video it should play on load. Here's a demo over at jsfiddle.

PHP Session data not being saved

Check to make sure you are not mixing https:// with http://. Session variables do not flow between secure and insecure sessions.

Center text in div?

If you have text inside a <div>:

text-align: center;
vertical-align: middle;
display: table-cell;

Better way to check if a Path is a File or a Directory?

I needed this, the posts helped, this gets it down to one line, and if the path isn't a path at all, it just returns and exits the method. It addresses all of the above concerns, doesn't need the trailing slash either.

if (!Directory.Exists(@"C:\folderName")) return;

Updating MySQL primary key

Next time, use a single "alter table" statement to update the primary key.

alter table xx drop primary key, add primary key(k1, k2, k3);

To fix things:

create table fixit (user_2, user_1, type, timestamp, n, primary key( user_2, user_1, type) );
lock table fixit write, user_interactions u write, user_interactions write;

insert into fixit 
select user_2, user_1, type, max(timestamp), count(*) n from user_interactions u 
group by user_2, user_1, type
having n > 1;

delete u from user_interactions u, fixit 
where fixit.user_2 = u.user_2 
  and fixit.user_1 = u.user_1 
  and fixit.type = u.type 
  and fixit.timestamp != u.timestamp;

alter table user_interactions add primary key (user_2, user_1, type );

unlock tables;

The lock should stop further updates coming in while your are doing this. How long this takes obviously depends on the size of your table.

The main problem is if you have some duplicates with the same timestamp.

How to make a rest post call from ReactJS code?

Another recently popular packages is : axios

Install : npm install axios --save

Simple Promise based requests


axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Add rows to CSV File in powershell

Simple to me is like this:

$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"

"$Time,$Description"|Add-Content -Path $File # Keep no space between content variables

If you have a lot of columns, then create a variable like $NewRow like:

$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"
$NewRow = "$Time,$Description" # No space between variables, just use comma(,).

$NewRow | Add-Content -Path $File # Keep no space between content variables

Please note the difference between Set-Content (overwrites the existing contents) and Add-Content (appends to the existing contents) of the file.

Android - How to get application name? (Not package name)

In Kotlin its simple:

val appLabel = context.applicationInfo.nonLocalizedLabel

How do you create a remote Git branch?

If you want to create a branch from the current branch

git checkout -b {your_local_branch_name} 

you want a branch from a remote branch, you can try

git checkout -b {your_local_branch_name} origin/<remote_branch_name>

If you are done with changes you can add the file.

git add -A or git add <each_file_names>

Then do a commit locally

git commit -m 'your commit message'

When you want to push to remote repo

git push -u origin <your_local_branch_name>

All together will be

git checkout -b bug_fixes 

or If you want to create a branch from a remote branch say development

git checkout -b bug_fixes origin/development

You can push to the branch to remote repo by

git push -u origin bug_fixes

Anytime you want to update your branch from any other branch say master.

git pull origin master.

How do I import a sql data file into SQL Server?

There is no such thing as importing in MS SQL. I understand what you mean. It is so simple. Whenever you get/have a something.SQL file, you should just double click and it will directly open in your MS SQL Studio.

How to implement the Softmax function in Python

I would like to supplement a little bit more understanding of the problem. Here it is correct of subtracting max of the array. But if you run the code in the other post, you would find it is not giving you right answer when the array is 2D or higher dimensions.

Here I give you some suggestions:

  1. To get max, try to do it along x-axis, you will get an 1D array.
  2. Reshape your max array to original shape.
  3. Do np.exp get exponential value.
  4. Do np.sum along axis.
  5. Get the final results.

Follow the result you will get the correct answer by doing vectorization. Since it is related to the college homework, I cannot post the exact code here, but I would like to give more suggestions if you don't understand.

How to convert dataframe into time series?

With library fpp, you can easily create time series with date format: time_ser=ts(data,frequency=4,start=c(1954,2))

here we start at the 2nd quarter of 1954 with quarter fequency.

Search an array for matching attribute

you can use ES5 some. Its pretty first by using callback

function findRestaurent(foodType) {
    var restaurant;
    restaurants.some(function (r) {
        if (r.food === id) {
            restaurant = r;
            return true;
        }
   });
  return restaurant;
}

How to run multiple DOS commands in parallel?

You can execute commands in parallel with start like this:

start "" ping myserver
start "" nslookup myserver
start "" morecommands

They will each start in their own command prompt and allow you to run multiple commands at the same time from one batch file.

Hope this helps!

Node.js Best Practice Exception Handling

Update: Joyent now has their own guide. The following information is more of a summary:

Safely "throwing" errors

Ideally we'd like to avoid uncaught errors as much as possible, as such, instead of literally throwing the error, we can instead safely "throw" the error using one of the following methods depending on our code architecture:

  • For synchronous code, if an error happens, return the error:

    // Define divider as a syncrhonous function
    var divideSync = function(x,y) {
        // if error condition?
        if ( y === 0 ) {
            // "throw" the error safely by returning it
            return new Error("Can't divide by zero")
        }
        else {
            // no error occured, continue on
            return x/y
        }
    }
    
    // Divide 4/2
    var result = divideSync(4,2)
    // did an error occur?
    if ( result instanceof Error ) {
        // handle the error safely
        console.log('4/2=err', result)
    }
    else {
        // no error occured, continue on
        console.log('4/2='+result)
    }
    
    // Divide 4/0
    result = divideSync(4,0)
    // did an error occur?
    if ( result instanceof Error ) {
        // handle the error safely
        console.log('4/0=err', result)
    }
    else {
        // no error occured, continue on
        console.log('4/0='+result)
    }
    
  • For callback-based (ie. asynchronous) code, the first argument of the callback is err, if an error happens err is the error, if an error doesn't happen then err is null. Any other arguments follow the err argument:

    var divide = function(x,y,next) {
        // if error condition?
        if ( y === 0 ) {
            // "throw" the error safely by calling the completion callback
            // with the first argument being the error
            next(new Error("Can't divide by zero"))
        }
        else {
            // no error occured, continue on
            next(null, x/y)
        }
    }
    
    divide(4,2,function(err,result){
        // did an error occur?
        if ( err ) {
            // handle the error safely
            console.log('4/2=err', err)
        }
        else {
            // no error occured, continue on
            console.log('4/2='+result)
        }
    })
    
    divide(4,0,function(err,result){
        // did an error occur?
        if ( err ) {
            // handle the error safely
            console.log('4/0=err', err)
        }
        else {
            // no error occured, continue on
            console.log('4/0='+result)
        }
    })
    
  • For eventful code, where the error may happen anywhere, instead of throwing the error, fire the error event instead:

    // Definite our Divider Event Emitter
    var events = require('events')
    var Divider = function(){
        events.EventEmitter.call(this)
    }
    require('util').inherits(Divider, events.EventEmitter)
    
    // Add the divide function
    Divider.prototype.divide = function(x,y){
        // if error condition?
        if ( y === 0 ) {
            // "throw" the error safely by emitting it
            var err = new Error("Can't divide by zero")
            this.emit('error', err)
        }
        else {
            // no error occured, continue on
            this.emit('divided', x, y, x/y)
        }
    
        // Chain
        return this;
    }
    
    // Create our divider and listen for errors
    var divider = new Divider()
    divider.on('error', function(err){
        // handle the error safely
        console.log(err)
    })
    divider.on('divided', function(x,y,result){
        console.log(x+'/'+y+'='+result)
    })
    
    // Divide
    divider.divide(4,2).divide(4,0)
    

Safely "catching" errors

Sometimes though, there may still be code that throws an error somewhere which can lead to an uncaught exception and a potential crash of our application if we don't catch it safely. Depending on our code architecture we can use one of the following methods to catch it:

  • When we know where the error is occurring, we can wrap that section in a node.js domain

    var d = require('domain').create()
    d.on('error', function(err){
        // handle the error safely
        console.log(err)
    })
    
    // catch the uncaught errors in this asynchronous or synchronous code block
    d.run(function(){
        // the asynchronous or synchronous code that we want to catch thrown errors on
        var err = new Error('example')
        throw err
    })
    
  • If we know where the error is occurring is synchronous code, and for whatever reason can't use domains (perhaps old version of node), we can use the try catch statement:

    // catch the uncaught errors in this synchronous code block
    // try catch statements only work on synchronous code
    try {
        // the synchronous code that we want to catch thrown errors on
        var err = new Error('example')
        throw err
    } catch (err) {
        // handle the error safely
        console.log(err)
    }
    

    However, be careful not to use try...catch in asynchronous code, as an asynchronously thrown error will not be caught:

    try {
        setTimeout(function(){
            var err = new Error('example')
            throw err
        }, 1000)
    }
    catch (err) {
        // Example error won't be caught here... crashing our app
        // hence the need for domains
    }
    

    If you do want to work with try..catch in conjunction with asynchronous code, when running Node 7.4 or higher you can use async/await natively to write your asynchronous functions.

    Another thing to be careful about with try...catch is the risk of wrapping your completion callback inside the try statement like so:

    var divide = function(x,y,next) {
        // if error condition?
        if ( y === 0 ) {
            // "throw" the error safely by calling the completion callback
            // with the first argument being the error
            next(new Error("Can't divide by zero"))
        }
        else {
            // no error occured, continue on
            next(null, x/y)
        }
    }
    
    var continueElsewhere = function(err, result){
            throw new Error('elsewhere has failed')
    }
    
    try {
            divide(4, 2, continueElsewhere)
            // ^ the execution of divide, and the execution of 
            //   continueElsewhere will be inside the try statement
    }
    catch (err) {
            console.log(err.stack)
            // ^ will output the "unexpected" result of: elsewhere has failed
    }
    

    This gotcha is very easy to do as your code becomes more complex. As such, it is best to either use domains or to return errors to avoid (1) uncaught exceptions in asynchronous code (2) the try catch catching execution that you don't want it to. In languages that allow for proper threading instead of JavaScript's asynchronous event-machine style, this is less of an issue.

  • Finally, in the case where an uncaught error happens in a place that wasn't wrapped in a domain or a try catch statement, we can make our application not crash by using the uncaughtException listener (however doing so can put the application in an unknown state):

    // catch the uncaught errors that weren't wrapped in a domain or try catch statement
    // do not use this in modules, but only in applications, as otherwise we could have multiple of these bound
    process.on('uncaughtException', function(err) {
        // handle the error safely
        console.log(err)
    })
    
    // the asynchronous or synchronous code that emits the otherwise uncaught error
    var err = new Error('example')
    throw err
    

Decimal number regular expression, where digit after decimal is optional

/\d+\.?\d*/

One or more digits (\d+), optional period (\.?), zero or more digits (\d*).

Depending on your usage or regex engine you may need to add start/end line anchors:

/^\d+\.?\d*$/

Regular expression visualization

Debuggex Demo

How to execute raw SQL in Flask-SQLAlchemy app

Have you tried:

result = db.engine.execute("<sql here>")

or:

from sqlalchemy import text

sql = text('select name from penguins')
result = db.engine.execute(sql)
names = [row[0] for row in result]
print names

Get Category name from Post ID

here you go get_the_category( $post->ID ); will return the array of categories of that post you need to loop through the array

$category_detail=get_the_category('4');//$post->ID
foreach($category_detail as $cd){
echo $cd->cat_name;
}

get_the_category

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

You have a few typos in your select. It should be: input:not([disabled]):not([type="submit"]):focus

See this jsFiddle for a proof of concept. On a sidenote, if I removed the "background-color" property, then the box shadow no longer works. Not sure why.

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option>

Thank you all for this thread! My colleague and I just discovered that the default_value property is a Constant, not a Variable.

In other React forms I've built, the default value for a Select was preset in an associated Context. So the first time the Select was rendered, default_value was set to the correct value.

But in my latest React form (a small modal), I'm passing the values for the form as props and then using a useEffect to populate the associated Context. So the FIRST time the Select is rendered, default_value is set to null. Then when the Context is populated and the Select is supposed to be re-rendered, default_value cannot be changed and thus the initial default value is not set.

The solution was ultimately simple: Use the value property instead. But figuring out why default_value didn't work like it did with my other forms took some time.

I'm posting this to help others in the community.

Change icon-bar (?) color in bootstrap

In bootstrap 4.3.1 I can change the background color of the toggler icon to white via the css code.

.navbar-toggler{
  background-color:white;
  }

And in my opinion the so changed icon looks fine as well on light as on dark background.

Batch script to find and replace a string in text file within a minute for files up to 12 MB

Just download fart (find and replace text) from here

use it in CMD (for ease of use I add fart folder to my path variable)

here is an example:

fart -r "C:\myfolder\*.*" findSTR replaceSTR

this command will search in C:\myfolder and all sub-folders and replace findSTR with replaceSTR

-r means process sub-folders recursively.

fart is really fast and easy

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

 extension UITextField {  
  func setBottomBorder(color:String) {
    self.borderStyle = UITextBorderStyle.None
    let border = CALayer()
    let width = CGFloat(1.0)
    border.borderColor = UIColor(hexString: color)!.cgColor
    border.frame = CGRect(x: 0, y: self.frame.size.height - width,   width:  self.frame.size.width, height: self.frame.size.height)
    border.borderWidth = width
    self.layer.addSublayer(border)
    self.layer.masksToBounds = true
   }
}

and then just do this:

yourTextField.setBottomBorder(color: "#3EFE46")

C++ Loop through Map

As P0W has provided complete syntax for each C++ version, I would like to add couple of more points by looking at your code

  • Always take const & as argument as to avoid extra copies of the same object.
  • use unordered_map as its always faster to use. See this discussion

here is a sample code:

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

void output(const auto& table)
{
   for (auto const & [k, v] : table)
   {
        std::cout << "Key: " << k << " Value: " << v << std::endl;
   }
}

int main() {
    std::unordered_map<string, int> mydata = {
        {"one", 1},
        {"two", 2},
        {"three", 3}
    };
    output(mydata);
    return 0;
}

How to use ADB to send touch events to device using sendevent command?

You don't need to use

adb shell getevent -l

command, you just need to enable in Developer Options on the device [Show Touch data] to get X and Y.

Some more information can be found in my article here: https://mobileqablog.wordpress.com/2016/08/20/android-automatic-touchscreen-taps-adb-shell-input-touchscreen-tap/

How is AngularJS different from jQuery

I think this is a very good chart describing the differences in short. A quick glance at it shows most of the differences.

enter image description here

One thing I would like to add is that, AngularJS can be made to follow the MVVM design pattern while jQuery does not follow any of the standard Object Oriented patterns.

How do I use modulus for float/double?

You probably had a typo when you first ran it.

evaluating 0.5 % 0.3 returns '0.2' (A double) as expected.

Mindprod has a good overview of how modulus works in Java.

How to get all options in a drop-down list by Selenium WebDriver using C#?

 WebElement element = driver.findElement(By.id("inst_state"));
        Select s = new Select(element);
        List <WebElement> elementcount = s.getOptions();

        System.out.println(elementcount.size());
        for(int i=0 ;i<elementcount.size();i++)
        {
            String value = elementcount.get(i).getText();
            System.out.println(value);

        }

Is there any method to get the URL without query string?

Try this: window.location.href.split('?')[0]

Flutter - Layout a Grid

GridView is used for implementing material grid lists. If you know you have a fixed number of items and it's not very many (16 is fine), you can use GridView.count. However, you should note that a GridView is scrollable, and if that isn't what you want, you may be better off with just rows and columns.

screenshot

import 'dart:collection';
import 'package:flutter/scheduler.dart';
import 'package:flutter/material.dart';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/foundation.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.orange,
      ),
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget{
  @override
  Widget build(BuildContext context){
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Grid Demo'),
      ),
      body: new GridView.count(
        crossAxisCount: 4,
        children: new List<Widget>.generate(16, (index) {
          return new GridTile(
            child: new Card(
              color: Colors.blue.shade200,
              child: new Center(
                child: new Text('tile $index'),
              )
            ),
          );
        }),
      ),
    );
  }
}

What is the difference between dynamic programming and greedy approach?

Based on Wikipedia's articles.

Greedy Approach

A greedy algorithm is an algorithm that follows the problem solving heuristic of making the locally optimal choice at each stage with the hope of finding a global optimum. In many problems, a greedy strategy does not in general produce an optimal solution, but nonetheless a greedy heuristic may yield locally optimal solutions that approximate a global optimal solution in a reasonable time.

We can make whatever choice seems best at the moment and then solve the subproblems that arise later. The choice made by a greedy algorithm may depend on choices made so far but not on future choices or all the solutions to the subproblem. It iteratively makes one greedy choice after another, reducing each given problem into a smaller one.

Dynamic programming

The idea behind dynamic programming is quite simple. In general, to solve a given problem, we need to solve different parts of the problem (subproblems), then combine the solutions of the subproblems to reach an overall solution. Often when using a more naive method, many of the subproblems are generated and solved many times. The dynamic programming approach seeks to solve each subproblem only once, thus reducing the number of computations: once the solution to a given subproblem has been computed, it is stored or "memo-ized": the next time the same solution is needed, it is simply looked up. This approach is especially useful when the number of repeating subproblems grows exponentially as a function of the size of the input.

Difference

Greedy choice property

We can make whatever choice seems best at the moment and then solve the subproblems that arise later. The choice made by a greedy algorithm may depend on choices made so far but not on future choices or all the solutions to the subproblem. It iteratively makes one greedy choice after another, reducing each given problem into a smaller one. In other words, a greedy algorithm never reconsiders its choices.

This is the main difference from dynamic programming, which is exhaustive and is guaranteed to find the solution. After every stage, dynamic programming makes decisions based on all the decisions made in the previous stage, and may reconsider the previous stage's algorithmic path to solution.

For example, let's say that you have to get from point A to point B as fast as possible, in a given city, during rush hour. A dynamic programming algorithm will look into the entire traffic report, looking into all possible combinations of roads you might take, and will only then tell you which way is the fastest. Of course, you might have to wait for a while until the algorithm finishes, and only then can you start driving. The path you will take will be the fastest one (assuming that nothing changed in the external environment).

On the other hand, a greedy algorithm will start you driving immediately and will pick the road that looks the fastest at every intersection. As you can imagine, this strategy might not lead to the fastest arrival time, since you might take some "easy" streets and then find yourself hopelessly stuck in a traffic jam.

Some other details...

In mathematical optimization, greedy algorithms solve combinatorial problems having the properties of matroids.

Dynamic programming is applicable to problems exhibiting the properties of overlapping subproblems and optimal substructure.

Adding a SVN repository in Eclipse

This is a dead topic, but the solution is to install a client adapter along with Subclipse.

Take a look at this, and install SVN Client Adapter, SVNKit Adapter, and SVNKit Library.

Then check under Window -> Preference -> Team -> SVN and make sure there is an entry for SVN Interface.

And for future reference, if you can connect to the repository through the command line, then it must be a problem with the IDE.

FontAwesome icons not showing. Why?

I use:

<link rel="stylesheet" href="http://fontawesome.io/assets/font-awesome/css/font-awesome.css">
<a class="icon fa-car" aria-hidden="true" style="color:white;" href="http://viettelquangbinh.com"></a>

and style after:

.icon::before {
display: inline-block;
margin-right: .5em;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
transform: translate(0, 0);
}

JAVA_HOME is set to an invalid directory:

JAVA_HOME should be C:\Program Files\Java\jdk1.8.0_172 don't include semi-colon(;) or bin in path. Any jdk version above 7 will work. Also, you need to re-start the cmd

jQuery: how to scroll to certain anchor/div on page load?

    /* START --- scroll till anchor */
        (function($) {
             $.fn.goTo = function() {
                  var top_menu_height=$('#div_menu_header').height() + 5 ;
                  //alert ( 'top_menu_height is:' + top_menu_height );
                  $('html, body').animate({
                        scrollTop: (-1)*top_menu_height + $(this).offset().top + 'px'
                  }, 500);
                  return this; // for chaining...
             }
        })(jQuery);

        $(document).ready(function(){

          var url = document.URL, idx = url.indexOf("#") ;
          var hash = idx != -1 ? url.substring(idx+1) : "";

          $(window).load(function(){
             // Remove the # from the hash, as different browsers may or may not include it
             var anchor_to_scroll_to = location.hash.replace('#','');
             if ( anchor_to_scroll_to != '' ) {
                 anchor_to_scroll_to = '#' + anchor_to_scroll_to ;
                 $(anchor_to_scroll_to).goTo();
             }
            });
        });
    /* STOP --- scroll till anchror */

Python script header

From the manpage for env (GNU coreutils 6.10):

env - run a program in a modified environment

In theory you could use env to reset the environment (removing many of the existing environment variables) or add additional environment variables in the script header. Practically speaking, the two versions you mentioned are identical. (Though others have mentioned a good point: specifying python through env lets you abstractly specify python without knowing its path.)

VS 2017 Git Local Commit DB.lock error on every commit

My automatically generated .gitignore file contained /.vs instead of .vs/. Fixing this typo fixed the problem!

JavaScript Promises - reject vs. throw

An example to try out. Just change isVersionThrow to false to use reject instead of throw.

_x000D_
_x000D_
const isVersionThrow = true_x000D_
_x000D_
class TestClass {_x000D_
  async testFunction () {_x000D_
    if (isVersionThrow) {_x000D_
      console.log('Throw version')_x000D_
      throw new Error('Fail!')_x000D_
    } else {_x000D_
      console.log('Reject version')_x000D_
      return new Promise((resolve, reject) => {_x000D_
        reject(new Error('Fail!'))_x000D_
      })_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
const test = async () => {_x000D_
  const test = new TestClass()_x000D_
  try {_x000D_
    var response = await test.testFunction()_x000D_
    return response _x000D_
  } catch (error) {_x000D_
    console.log('ERROR RETURNED')_x000D_
    throw error _x000D_
  }  _x000D_
}_x000D_
_x000D_
test()_x000D_
.then(result => {_x000D_
  console.log('result: ' + result)_x000D_
})_x000D_
.catch(error => {_x000D_
  console.log('error: ' + error)_x000D_
})
_x000D_
_x000D_
_x000D_

React native ERROR Packager can't listen on port 8081

Take the terminal and type

fuser 8081/tcp

You will get a Process id which is using port 8081 Now kill the process

kill <pid>

Getting the number of filled cells in a column (VBA)

You can also use

Cells.CurrentRegion

to give you a range representing the bounds of your data on the current active sheet

Msdn says on the topic

Returns a Range object that represents the current region. The current region is a range bounded by any combination of blank rows and blank columns. Read-only.

Then you can determine the column count via

Cells.CurrentRegion.Columns.Count

and the row count via

Cells.CurrentRegion.Rows.Count

Get selected value/text from Select on change

I have tried to explain with my own sample, but I hope it will help you. You don't need onchange="test()" Please run code snippet for getting a live result.

_x000D_
_x000D_
document.getElementById("cars").addEventListener("change", displayCar);_x000D_
_x000D_
function displayCar() {_x000D_
  var selected_value = document.getElementById("cars").value;_x000D_
  alert(selected_value);_x000D_
}
_x000D_
<select id="cars">_x000D_
  <option value="bmw">BMW</option>_x000D_
  <option value="mercedes">Mercedes</option>_x000D_
  <option value="volkswagen">Volkswagen</option>_x000D_
  <option value="audi">Audi</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Remove redundant paths from $PATH variable

PATH=echo $PATH | sed 's/:/\n/g' | sort -u | sed ':a;N;$!ba;s/\n/:/g'

How can I take a screenshot with Selenium WebDriver?

Python

def test_url(self):
    self.driver.get("https://www.google.com/")
    self.driver.save_screenshot("test.jpg")

It will save a screenshot in the same directory the where script is saved.

Fluid or fixed grid system, in responsive design, based on Twitter Bootstrap

Fluid layout in Bootstrap 3.

Unlike Boostrap 2, Bootstrap 3 doesn't have a .container-fluid mixin to make a fluid container. The .container is a fixed width responsive grid layout. In a large screen, there are excessive white spaces in both sides of one's Web page content.

container-fluid is added back in Bootstrap 3.1

A fluid grid layout uses all screen width and works better in large screen. It turns out that it is easy to create a fluid grid layout using Bootstrap 3 mixins. The following line makes a fluid responsive grid layout:

.container-fixed;

The .container-fixed mixin sets the content to the center of the screen and add paddings. It doesn't specifies a fixed page width.

Another approach is to use Eric Flowers' CSS style

.my-fluid-container {
    padding-left: 15px;
    padding-right: 15px;
    margin-left: auto;
    margin-right: auto;
}

The program can't start because MSVCR110.dll is missing from your computer

This error appears when you wish to run a software which require the Microsoft Visual C++ Redistributable 2012. Download it fromMicrosoft website as x86 or x64 edition. Depending on the software you wish to install you need to install either the 32 bit or the 64 bit version. Visit the following link: http://www.microsoft.com/en-us/download/details.aspx?id=30679#

Internet Access in Ubuntu on VirtualBox

I had a similar issue in windows 7 + ubuntu 12.04 as guest. I resolved by

  • open 'network and sharing center' in windows
  • right click 'nw-bridge' -> 'properties'
  • Select "virtual box host only network" for the option "select adapters you want to use to connect computers on your local network"
  • go to virtual box.. select the network type as NAT.

How to move certain commits to be based on another branch in git?

// on your branch that holds the commit you want to pass
$ git log
// copy the commit hash found
$ git checkout [branch that will copy the commit]
$ git reset --hard [hash of the commit you want to copy from the other branch]
// remove the [brackets]

Other more useful commands here with explanation: Git Guide

key_load_public: invalid format

It seems that ssh cannot read your public key. But that doesn't matter.

You upload your public key to github, but you authenticate using your private key. See e.g. the FILES section in ssh(1).

Chrome & Safari Error::Not allowed to load local resource: file:///D:/CSS/Style.css

You wont be able to access a local resource from your aspx page (web server). Have you tried a relative path from your aspx page to your css file like so...

<link rel="stylesheet" media="all" href="/CSS/Style.css" type="text/css" />

The above assumes that you have a folder called CSS in the root of your website like this:

http://www.website.com/CSS/Style.css

jQuery ui datepicker with Angularjs

Here is my code-

var datePicker = angular.module('appointmentApp', []);

datePicker.directive('datepicker', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
         link: function (scope, element, attrs, ngModelCtrl) {
            $(element).datepicker({
                dateFormat: 'dd-mm-yy',
                onSelect: function (date) {
                    scope.appoitmentScheduleDate = date;
                    scope.$apply();
                }
            });
        }
    };
});

jQuery - Increase the value of a counter when a button is clicked

It's just

var counter = 0;

$("#update").click(function() {
   counter++;
});

AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

RESTART YOUR IDE

I tried all of the different things but nothing seems to be working then I just restarted my IDE and it worked like charm.

Still, if it does not work then try restarting your system.

FYI, I am working on the following versions

opencv-contrib-python==4.4.0.46
opencv-python==4.1.2.30

How do I perform HTML decoding/encoding using Python/Django?

I found this in the Cheetah source code (here)

htmlCodes = [
    ['&', '&amp;'],
    ['<', '&lt;'],
    ['>', '&gt;'],
    ['"', '&quot;'],
]
htmlCodesReversed = htmlCodes[:]
htmlCodesReversed.reverse()
def htmlDecode(s, codes=htmlCodesReversed):
    """ Returns the ASCII decoded version of the given HTML string. This does
        NOT remove normal HTML tags like <p>. It is the inverse of htmlEncode()."""
    for code in codes:
        s = s.replace(code[1], code[0])
    return s

not sure why they reverse the list, I think it has to do with the way they encode, so with you it may not need to be reversed. Also if I were you I would change htmlCodes to be a list of tuples rather than a list of lists... this is going in my library though :)

i noticed your title asked for encode too, so here is Cheetah's encode function.

def htmlEncode(s, codes=htmlCodes):
    """ Returns the HTML encoded version of the given string. This is useful to
        display a plain ASCII text string on a web page."""
    for code in codes:
        s = s.replace(code[0], code[1])
    return s

What is the difference between AF_INET and PF_INET in socket programming?

Checking the header file solve's the problem. One can check for there system compiler.

For my system , AF_INET == PF_INET

AF == Address Family And PF == Protocol Family

Protocol families, same as address families.

enter image description here

How to use querySelectorAll only for elements that have a specific attribute set?

Extra Tips:

Multiple "nots", input that is NOT hidden and NOT disabled:

:not([type="hidden"]):not([disabled])

Also did you know you can do this:

node.parentNode.querySelectorAll('div');

This is equivelent to jQuery's:

$(node).parent().find('div');

Which will effectively find all divs in "node" and below recursively, HOT DAMN!

How to get all files under a specific directory in MATLAB?

You're looking for dir to return the directory contents.

To loop over the results, you can simply do the following:

dirlist = dir('.');
for i = 1:length(dirlist)
    dirlist(i)
end

This should give you output in the following format, e.g.:

name: 'my_file'
date: '01-Jan-2010 12:00:00'
bytes: 56
isdir: 0
datenum: []

Check if a Bash array contains a value

I generally write these kind of utilities to operate on the name of the variable, rather than the variable value, primarily because bash can't otherwise pass variables by reference.

Here's a version that works with the name of the array:

function array_contains # array value
{
    [[ -n "$1" && -n "$2" ]] || {
        echo "usage: array_contains <array> <value>"
        echo "Returns 0 if array contains value, 1 otherwise"
        return 2
    }

    eval 'local values=("${'$1'[@]}")'

    local element
    for element in "${values[@]}"; do
        [[ "$element" == "$2" ]] && return 0
    done
    return 1
}

With this, the question example becomes:

array_contains A "one" && echo "contains one"

etc.

VBA - Select columns using numbers?

In the example code below I use variables just to show how the command could be used for other situations.

FirstCol = 1
LastCol = FirstCol + 5
Range(Columns(FirstCol), Columns(LastCol)).Select

How do I find out which process is locking a file using .NET?

simpler with linq:

public void KillProcessesAssociatedToFile(string file)
    {
        GetProcessesAssociatedToFile(file).ForEach(x =>
        {
            x.Kill();
            x.WaitForExit(10000);
        });
    }

    public List<Process> GetProcessesAssociatedToFile(string file)
    {
        return Process.GetProcesses()
            .Where(x => !x.HasExited
                && x.Modules.Cast<ProcessModule>().ToList()
                    .Exists(y => y.FileName.ToLowerInvariant() == file.ToLowerInvariant())
                ).ToList();
    }

How do I set the version information for an existing .exe, .dll?

rcedit is relative new and works well from the command line: https://github.com/atom/rcedit

$ rcedit "path-to-exe-or-dll" --set-version-string "Comments" "This is an exe"
$ rcedit "path-to-exe-or-dll" --set-file-version "10.7"
$ rcedit "path-to-exe-or-dll" --set-product-version "10.7"

There's also an NPM module which wraps it from JavaScript and a Grunt task in case you're using Grunt.

Make columns of equal width in <table>

I think that this will do the trick:

table{
    table-layout: fixed;
    width: 300px;
}

Stop MySQL service windows

I'm on XP. I've installed MySQL-5.6.10 manually from .zip, no Windows auto-installer provided by MySQL site. The /bin directory of my MySQL is in my PATH. So I start the server with mysqld --console command, like this:

C:\Documents and Settings\User>mysqld --console
2013-04-12 14:39:19 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_times
tamp server option (see documentation for more details).

From now on it is running. And that cmd window is occupied. I open and use another one.

I've tried to use the answers from above but none of them can stop the server. Only errors are throw. So I stop the server with mysqladmin -u root shutdown on the other cmd window or with Ctrl + C on the cmd window it is running in. The latter works not so good as the former, sometimes I have to click Ctrl + C twice or more.

The log of the shutdown process is like this:

2013-04-12 17:55:29 3968 [Note] Giving 0 client threads a chance to die gracefully
2013-04-12 17:55:29 3968 [Note] Event Scheduler: Purging the queue. 0 events
2013-04-12 17:55:29 3968 [Note] Shutting down slave threads
2013-04-12 17:55:29 3968 [Note] Forcefully disconnecting 0 remaining clients
2013-04-12 17:55:29 3968 [Note] Binlog end
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'partition'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'PERFORMANCE_SCHEMA'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_DATAFILES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_TABLESPACES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN_COLS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_FIELDS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_COLUMNS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_INDEXES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_TABLESTATS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_TABLES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_INDEX_TABLE'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_INDEX_CACHE'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_CONFIG'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_BEING_DELETED'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_DELETED'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_INSERTED'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_DEFAULT_STOPWORD'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_METRICS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_BUFFER_POOL_STATS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE_LRU'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX_RESET'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMPMEM_RESET'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMPMEM'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP_RESET'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_LOCK_WAITS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_LOCKS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_TRX'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'InnoDB'
2013-04-12 17:55:29 3968 [Note] InnoDB: FTS optimize thread exiting.
2013-04-12 17:55:29 3968 [Note] InnoDB: Starting shutdown...
2013-04-12 17:55:30 3968 [Note] InnoDB: Shutdown completed; log sequence number 1719777
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'BLACKHOLE'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'ARCHIVE'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'MRG_MYISAM'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'MyISAM'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'MEMORY'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'CSV'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'sha256_password'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'mysql_old_password'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'mysql_native_password'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'binlog'
2013-04-12 17:55:30 3968 [Note] mysqld: Shutdown complete

And I still don't know if it is 100% right way to shutdown the server, but it works :)

Return HTTP status code 201 in flask

In your flask code, you should ideally specify the MIME type as often as possible, as well:

return html_page_str, 200, {'ContentType':'text/html'}

return json.dumps({'success':True}), 200, {'ContentType':'application/json'}

...etc

Oracle timestamp data type

Quite simply the number is the precision of the timestamp, the fraction of a second held in the column:

SQL> create table t23
  2  (ts0 timestamp(0)
  3   , ts3 timestamp(3)
  4  , ts6 timestamp(6)
  5  )
  6  /

Table created.

SQL> insert into t23 values (systimestamp, systimestamp, systimestamp)
  2  /

1 row created.

SQL> select * from t23
  2  /

TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM


SQL> 

If we don't specify a precision then the timestamp defaults to six places.

SQL> alter table t23 add ts_def timestamp;

Table altered.

SQL> update t23      
  2  set ts_def = systimestamp
  3  /

1 row updated.

SQL> select * from t23
  2  /

TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
TS_DEF
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
24-JAN-12 05.59.27.293305 AM


SQL> 

Note that I'm running on Linux so my TIMESTAMP column actually gives me precision to six places i.e. microseconds. This would also be the case on most (all?) flavours of Unix. On Windows the limit is three places i.e. milliseconds. (Is this still true of the most modern flavours of Windows - citation needed).

As might be expected, the documentation covers this. Find out more.


"when you create timestamp(9) this gives you nanos right"

Only if the OS supports it. As you can see, my OEL appliance does not:

SQL> alter table t23 add ts_nano timestamp(9)
  2  /

Table altered.

SQL> update t23 set ts_nano = systimestamp(9)
  2  /

1 row updated.

SQL> select * from t23
  2  /

TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
TS_DEF
---------------------------------------------------------------------------
TS_NANO
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
24-JAN-12 05.59.27.293305 AM
24-JAN-12 08.28.03.990557000 AM


SQL> 

(Those trailing zeroes could be a coincidence but they aren't.)

How to use sbt from behind proxy?

To provide one answer that will work for all Windows-users:

Add the following to your sbtconfig.txt (C:\Program Files (x86)\sbt\conf)

-Dhttp.proxyHost=XXXXXXX -Dhttp.proxyPort=YYYY -Dhttp.proxySet=true -Dhttps.proxyHost=XXXXXXX -Dhttps.proxyPort=YYYY -Dhttps.proxySet=true

Replace both XXXXXXX with your proxyHost, and both YYYY with your proxyPort.

If you get the error "Could not find or load main class" you need to set your JAVA_HOME:

set JAVA_HOME=C:\Progra~1\Java\jdkxxxxxx

When on 64-bit windows, use:

Progra~1 = 'Program Files'

Progra~2 = 'Program Files(x86)'

Composer Warning: openssl extension is missing. How to enable in WAMP

WAMP uses different php.ini files in the CLI and for Apache. when you enable php_openssl through the WAMP UI, you enable it for Apache, not for the CLI. You need to modify C:\wamp\bin\php\php-5.4.3\php.ini to enable it for the CLI.

Get list of data-* attributes using javascript / jQuery

A pure JavaScript solution ought to be offered as well, as the solution is not difficult:

var a = [].filter.call(el.attributes, function(at) { return /^data-/.test(at.name); });

This gives an array of attribute objects, which have name and value properties:

if (a.length) {
    var firstAttributeName = a[0].name;
    var firstAttributeValue = a[0].value;
}

Edit: To take it a step further, you can get a dictionary by iterating the attributes and populating a data object:

var data = {};
[].forEach.call(el.attributes, function(attr) {
    if (/^data-/.test(attr.name)) {
        var camelCaseName = attr.name.substr(5).replace(/-(.)/g, function ($0, $1) {
            return $1.toUpperCase();
        });
        data[camelCaseName] = attr.value;
    }
});

You could then access the value of, for example, data-my-value="2" as data.myValue;

jsfiddle.net/3KFYf/33

Edit: If you wanted to set data attributes on your element programmatically from an object, you could:

Object.keys(data).forEach(function(key) {
    var attrName = "data-" + key.replace(/[A-Z]/g, function($0) {
        return "-" + $0.toLowerCase();
    });
    el.setAttribute(attrName, data[key]);
});

jsfiddle.net/3KFYf/34

EDIT: If you are using babel or TypeScript, or coding only for es6 browsers, this is a nice place to use es6 arrow functions, and shorten the code a bit:

var a = [].filter.call(el.attributes, at => /^data-/.test(at.name));

How to display a range input slider vertically

Its very simple. I had implemented using -webkit-appearance: slider-vertical, It worked in chorme, Firefox, Edge

<input type="range">
input[type=range]{
    writing-mode: bt-lr; /* IE */
    -webkit-appearance: slider-vertical; /* WebKit */
    width: 50px;
    height: 200px;
    padding: 0 24px;
    outline: none;
    background:transparent;
}

change the date format in laravel view page

Method One:

Using the strtotime() to time is the best format to change the date to the given format.

strtotime() - Parse about any English textual datetime description into a Unix timestamp

The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.

Example:

<?php
$timestamp = strtotime( "February 26, 2007" );  
print date('Y-m-d', $timestamp );
?>

Output:

2007-02-26

Method Two:

date_format() - Return a new DateTime object, and then format the date:

<?php
$date=date_create("2013-03-15");
echo date_format($date,"Y/m/d H:i:s");
?>

Output:

 2013/03/15 00:00:00 

How to break nested loops in JavaScript?

See Aaron's. Otherwise: j=5;i=5 instead of break.

Slide div left/right using jQuery

$('#hello').hide('slide', {direction: 'left'}, 1000); requires the jQuery-ui library. See http://www.jqueryui.com

Getting the Username from the HKEY_USERS values

By searching for my userid in the registry, I found

HKEY_CURRENT_USER\Volatile Environment\Username

How to return JSON with ASP.NET & jQuery

Asp.net is pretty good at automatically converting .net objects to json. Your List object if returned in your webmethod should return a json/javascript array. What I mean by this is that you shouldn't change the return type to string (because that's what you think the client is expecting) when returning data from a method. If you return a .net array from a webmethod a javaScript array will be returned to the client. It doesn't actually work too well for more complicated objects, but for simple array data its fine.

Of course, it's then up to you to do what you need to do on the client side.

I would be thinking something like this:

[WebMethod]
public static List GetProducts()
{
   var products  = context.GetProducts().ToList();   
   return products;
}

There shouldn't really be any need to initialise any custom converters unless your data is more complicated than simple row/col data

Responsive Image full screen and centered - maintain aspect ratio, not exceed window

You could use a div with a background image instead and this CSS3 property:

background-size: contain

You can check out an example on:

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Scaling_background_images#contain

To quote Mozilla:

The contain value specifies that regardless of the size of the containing box, the background image should be scaled so that each side is as large as possible while not exceeding the length of the corresponding side of the container.

However, keep in mind that your image will be upscaled if the div is larger than your original image.

Python string class like StringBuilder in C#?

In case you are here looking for a fast string concatenation method in Python, then you do not need a special StringBuilder class. Simple concatenation works just as well without the performance penalty seen in C#.

resultString = ""

resultString += "Append 1"
resultString += "Append 2"

See Antoine-tran's answer for performance results

sqlite database default time value 'now'

This is a full example based on the other answers and comments to the question. In the example the timestamp (created_at-column) is saved as unix epoch UTC timezone and converted to local timezone only when necessary.

Using unix epoch saves storage space - 4 bytes integer vs. 24 bytes string when stored as ISO8601 string, see datatypes. If 4 bytes is not enough that can be increased to 6 or 8 bytes.

Saving timestamp on UTC timezone makes it convenient to show a reasonable value on multiple timezones.

SQLite version is 3.8.6 that ships with Ubuntu LTS 14.04.

$ sqlite3 so.db
SQLite version 3.8.6 2014-08-15 11:46:33
Enter ".help" for usage hints.
sqlite> .headers on

create table if not exists example (
   id integer primary key autoincrement
  ,data text not null unique
  ,created_at integer(4) not null default (strftime('%s','now'))
);

insert into example(data) values
 ('foo')
,('bar')
;

select
 id
,data
,created_at as epoch
,datetime(created_at, 'unixepoch') as utc
,datetime(created_at, 'unixepoch', 'localtime') as localtime
from example
order by id
;

id|data|epoch     |utc                |localtime
1 |foo |1412097842|2014-09-30 17:24:02|2014-09-30 20:24:02
2 |bar |1412097842|2014-09-30 17:24:02|2014-09-30 20:24:02

Localtime is correct as I'm located at UTC+2 DST at the moment of the query.

Install pip in docker

This command worked fine for me:

RUN apt-get -y install python3-pip

convert htaccess to nginx

You can easily make a Php script to parse your old htaccess, I am using this one for PRestashop rules :

$content = $_POST['content'];

    $lines   = explode(PHP_EOL, $content);
    $results = '';

    foreach($lines as $line)
    {
        $items = explode(' ', $line);

        $q = str_replace("^", "^/", $items[1]);

        if (substr($q, strlen($q) - 1) !== '$') $q .= '$';

        $buffer = 'rewrite "'.$q.'" "'.$items[2].'" last;';

        $results .= $buffer.PHP_EOL;
    }

    die($results);

How to check whether an array is empty using PHP?

I have solved this issue with following code.

$catArray=array();                          

$catIds=explode(',',$member['cat_id']);
if(!empty($catIds[0])){
foreach($catIds as $cat_id){
$catDetail=$this->Front_Category->get_category_detail($cat_id);
$catArray[]=$catDetail['allData']['cat_title'];
}
echo implode(',',$catArray);
}

How to get all checked checkboxes

In IE9+, Chrome or Firefox you can do:

var checkedBoxes = document.querySelectorAll('input[name=mycheckboxes]:checked');

How do I test if a string is empty in Objective-C?

Simply Check your string length

 if (!yourString.length)
 {
   //your code  
 }

a message to NIL will return nil or 0, so no need to test for nil :).

Happy coding ...

How to clone all remote branches in Git?

This variation will clone a remote repo with all branches available locally without having to checkout each branch one by one. No fancy scripts needed.

Make a folder with the same name of the repo you wish to clone and cd into for example:

mkdir somerepo
cd somerepo

Now do these commands but with actual repo usersname/reponame

git clone --bare [email protected]:someuser/somerepo.git .git
git config --bool core.bare false
git reset --hard
git branch

Voiala! you have all the branches there!

Git:nothing added to commit but untracked files present

Follow all the steps.

Step 1: initialize git

$ git init

Step 2: Check files are exist or not.

$git ls

Step 3 : Add the file

$git add filename

Step 4: Add comment to show

$git commit -m "your comment"

Step 5: Link to your repository

$git remote add origin  "copy repository link  and paste here"

Step 6: Push on Git

$ git push -u origin master

The server is not responding (or the local MySQL server's socket is not correctly configured) in wamp server

If you use MAMP, make sure it's started. :)

I just ran into this problem, and after starting MAMP the error went away. Not my finest moment.

What is the size of ActionBar in pixels?

@AZ13's answer is good, but as per the Android design guidelines, the ActionBar should be at least 48dp high.

How can I extract a number from a string in JavaScript?

Use this one-line code to get the first number in a string without getting errors:

var myInt = parseInt(myString.replace(/^[^0-9]+/, ''), 10);

What does on_delete do on Django models?

Let's say you have two models, one named Person and another one named Companies.

By definition, one person can create more than one company.

Considering a company can have one and only one person, we want that when a person is deleted that all the companies associated with that person also be deleted.

So, we start by creating a Person model, like this

class Person(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=20)

    def __str__(self):
        return self.id+self.name

Then, the Companies model can look like this

class Companies(models.Model):
    title = models.CharField(max_length=20)
    description=models.CharField(max_length=10)
    person= models.ForeignKey(Person,related_name='persons',on_delete=models.CASCADE)

Notice the usage of on_delete=models.CASCADE in the model Companies. That is to delete all companies when the person that owns it (instance of class Person) is deleted.

How do I use Node.js Crypto to create a HMAC-SHA1 hash?

A few years ago it was said that update() and digest() were legacy methods and the new streaming API approach was introduced. Now the docs say that either method can be used. For example:

var crypto    = require('crypto');
var text      = 'I love cupcakes';
var secret    = 'abcdeg'; //make this your secret!!
var algorithm = 'sha1';   //consider using sha256
var hash, hmac;

// Method 1 - Writing to a stream
hmac = crypto.createHmac(algorithm, secret);    
hmac.write(text); // write in to the stream
hmac.end();       // can't read from the stream until you call end()
hash = hmac.read().toString('hex');    // read out hmac digest
console.log("Method 1: ", hash);

// Method 2 - Using update and digest:
hmac = crypto.createHmac(algorithm, secret);
hmac.update(text);
hash = hmac.digest('hex');
console.log("Method 2: ", hash);

Tested on node v6.2.2 and v7.7.2

See https://nodejs.org/api/crypto.html#crypto_class_hmac. Gives more examples for using the streaming approach.

GIT_DISCOVERY_ACROSS_FILESYSTEM not set

Just type git init into your command line and press enter. Then run your command again, you probably were running git remote add origin [your-repository].

That should work, if it doesn't, just let me know.

Remove all special characters from a string in R?

Instead of using regex to remove those "crazy" characters, just convert them to ASCII, which will remove accents, but will keep the letters.

astr <- "Ábcdêãçoàúü"
iconv(astr, from = 'UTF-8', to = 'ASCII//TRANSLIT')

which results in

[1] "Abcdeacoauu"

Google Maps v3 - limit viewable area and zoom level

This may be helpful.

  var myOptions = {
      center: new google.maps.LatLng($lat,$lang),
      zoom: 7,
      disableDefaultUI: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

The Zoom level can be customizable according to the requirement.

Docker-Compose can't connect to Docker Daemon

Another reason why this error can show up: for me it was a malformed image-path definition in the docker-compose.yml:

  service:
    image: ${CONTAINER_REGISTRY_BASE}/my-service
   ...

Lookis ok'ish first, but i had CONTAINER_REGISTRY_BASE=eu.gcr.io/my-project/ set on the env. Apparently the // in the image path caused this error.

docker-compose: v.1.21.2
docker: 18.03.1-ce

Ruby String to Date Conversion

What is wrong with Date.parse method?

str = "Tue, 10 Aug 2010 01:20:19 -0400 (EDT)"
date = Date.parse str
=> #<Date: 4910837/2,0,2299161>
puts date
2010-08-10

It seems to work.

The only problem here is time zone. If you want date in UTC time zone, then it is better to use Time object, suppose we have string:

str = "Tue, 10 Aug 2010 01:20:19 +0400"
puts Date.parse str
2010-08-10
puts Date.parse(Time.parse(str).utc.to_s)
2010-08-09

I couldn't find simpler method to convert Time to Date.

Reading file line by line (with space) in Unix Shell scripting - Issue

You want to read raw lines to avoid problems with backslashes in the input (use -r):

while read -r line; do
   printf "<%s>\n" "$line"
done < file.txt

This will keep whitespace within the line, but removes leading and trailing whitespace. To keep those as well, set the IFS empty, as in

while IFS= read -r line; do
   printf "%s\n" "$line"
done < file.txt

This now is an equivalent of cat < file.txt as long as file.txt ends with a newline.

Note that you must double quote "$line" in order to keep word splitting from splitting the line into separate words--thus losing multiple whitespace sequences.

How to remove all event handlers from an event

I just found How to suspend events when setting a property of a WinForms control. It will remove all events from a control:

namespace CMessWin05
{
    public class EventSuppressor
    {
        Control _source;
        EventHandlerList _sourceEventHandlerList;
        FieldInfo _headFI;
        Dictionary<object, Delegate[]> _handlers;
        PropertyInfo _sourceEventsInfo;
        Type _eventHandlerListType;
        Type _sourceType;


        public EventSuppressor(Control control)
        {
            if (control == null)
                throw new ArgumentNullException("control", "An instance of a control must be provided.");

            _source = control;
            _sourceType = _source.GetType();
            _sourceEventsInfo = _sourceType.GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic);
            _sourceEventHandlerList = (EventHandlerList)_sourceEventsInfo.GetValue(_source, null);
            _eventHandlerListType = _sourceEventHandlerList.GetType();
            _headFI = _eventHandlerListType.GetField("head", BindingFlags.Instance | BindingFlags.NonPublic);
        }

        private void BuildList()
        {
            _handlers = new Dictionary<object, Delegate[]>();
            object head = _headFI.GetValue(_sourceEventHandlerList);
            if (head != null)
            {
                Type listEntryType = head.GetType();
                FieldInfo delegateFI = listEntryType.GetField("handler", BindingFlags.Instance | BindingFlags.NonPublic);
                FieldInfo keyFI = listEntryType.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
                FieldInfo nextFI = listEntryType.GetField("next", BindingFlags.Instance | BindingFlags.NonPublic);
                BuildListWalk(head, delegateFI, keyFI, nextFI);
            }
        }

        private void BuildListWalk(object entry, FieldInfo delegateFI, FieldInfo keyFI, FieldInfo nextFI)
        {
            if (entry != null)
            {
                Delegate dele = (Delegate)delegateFI.GetValue(entry);
                object key = keyFI.GetValue(entry);
                object next = nextFI.GetValue(entry);

                Delegate[] listeners = dele.GetInvocationList();
                if(listeners != null && listeners.Length > 0)
                    _handlers.Add(key, listeners);

                if (next != null)
                {
                    BuildListWalk(next, delegateFI, keyFI, nextFI);
                }
            }
        }

        public void Resume()
        {
            if (_handlers == null)
                throw new ApplicationException("Events have not been suppressed.");

            foreach (KeyValuePair<object, Delegate[]> pair in _handlers)
            {
                for (int x = 0; x < pair.Value.Length; x++)
                    _sourceEventHandlerList.AddHandler(pair.Key, pair.Value[x]);
            }

            _handlers = null;
        }

        public void Suppress()
        {
            if (_handlers != null)
                throw new ApplicationException("Events are already being suppressed.");

            BuildList();

            foreach (KeyValuePair<object, Delegate[]> pair in _handlers)
            {
                for (int x = pair.Value.Length - 1; x >= 0; x--)
                    _sourceEventHandlerList.RemoveHandler(pair.Key, pair.Value[x]);
            }
        }

    }
}

C# convert int to string with padding zeros?

public static string ToLeadZeros(this int strNum, int num)
{
    var str = strNum.ToString();
    return str.PadLeft(str.Length + num, '0');
}

// var i = 1;
// string num = i.ToLeadZeros(5);

How to copy an object by value, not by reference

I know this is a little bit too late but it might just help someone.

In my case I already had a method to make the Object from a json Object and make json from the object. with this you can simply create a new instance of the object and use it to restore. For instance in a function parsing a final object

_x000D_
_x000D_
public void update(final Object object){ _x000D_
  final Object original = Object.makeFromJSON(object.toJSON()); _x000D_
  // the original is not affected by changes made to object _x000D_
}
_x000D_
_x000D_
_x000D_

PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

Just an additional note - if the server runs on a port other than 80 (as might be common on a development/intranet machine) then HTTP_HOST contains the port, while SERVER_NAME does not.

$_SERVER['HTTP_HOST'] == 'localhost:8080'
$_SERVER['SERVER_NAME'] == 'localhost'

(At least that's what I've noticed in Apache port-based virtualhosts)

As Mike has noted below, HTTP_HOST does not contain :443 when running on HTTPS (unless you're running on a non-standard port, which I haven't tested).

Pass values of checkBox to controller action in asp.net mvc4

None of the previous solutions worked for me. Finally I found that the action should be coded as:

public ActionResult Index(string MyCheck = null)

and then, when checked the passed value was "on", not "true". Else, it is always null.

Hope it helps somebody!

How do I parse JSON with Ruby on Rails?

This answer is quite old. pguardiario's got it.

One site to check out is JSON implementation for Ruby. This site offers a gem you can install for a much faster C extension variant.

With the benchmarks given their documentation page they claim that it is 21.500x faster than ActiveSupport::JSON.decode

The code would be the same as Milan Novota's answer with this gem, but the parsing would just be:

parsed_json = JSON(your_json_string)

jQuery: Check if div with certain class name exists

Here is a solution without using Jquery

var hasClass = element.classList.contains('class name to search');
// hasClass is boolean
if(hasClass === true)
{
     // Class exists
}

reference link

How can I write a regex which matches non greedy?

The non-greedy ? works perfectly fine. It's just that you need to select dot matches all option in the regex engines (regexpal, the engine you used, also has this option) you are testing with. This is because, regex engines generally don't match line breaks when you use .. You need to tell them explicitly that you want to match line-breaks too with .

For example,

<img\s.*?>

works fine!

Check the results here.

Also, read about how dot behaves in various regex flavours.

How to convert date format to milliseconds?

You could use

Calendar cal = Calendar.getInstance();
cal.setTime(beginupd);
long millis = cal.getTimeInMillis();

ImageMagick security policy 'PDF' blocking conversion

I was experiencing this issue with nextcloud which would fail to create thumbnails for pdf files.

However, none of the suggested steps would solve the issue for me.

Eventually I found the reason: The accepted answer did work but I had to also restart php-fpm after editing the policy.xml file:

 sudo systemctl restart php7.2-fpm.service

How to run a script file remotely using SSH

You can do:

ssh user@host 'bash -s' < /path/script.sh

What happens to a declared, uninitialized variable in C? Does it have a value?

The basic answer is, yes it is undefined.

If you are seeing odd behavior because of this, it may depended on where it is declared. If within a function on the stack then the contents will more than likely be different every time the function gets called. If it is a static or module scope it is undefined but will not change.

@AspectJ pointcut for all methods of a class with specific annotation

You should combine a type pointcut with a method pointcut.

These pointcuts will do the work to find all public methods inside a class marked with an @Monitor annotation:

@Pointcut("within(@org.rejeev.Monitor *)")
public void beanAnnotatedWithMonitor() {}

@Pointcut("execution(public * *(..))")
public void publicMethod() {}

@Pointcut("publicMethod() && beanAnnotatedWithMonitor()")
public void publicMethodInsideAClassMarkedWithAtMonitor() {}

Advice the last pointcut that combines the first two and you're done!

If you're interested, I have written a cheat sheet with @AspectJ style here with a corresponding example document here.

Fake "click" to activate an onclick method

You can also try getting the element's onclick attribute and then passing into eval. This should work despite the big taboo over eval. I put a sample below

eval(document.getElementById('elementId').getAttribute('onclick'));

Android: How to enable/disable option menu item on button click?

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    // getMenuInflater().inflate(R.menu.home, menu);
    return false;
}

How do I solve the INSTALL_FAILED_DEXOPT error?

I found there's one reason for this problem: not enough space on mobile. So I delete several APP from mobile and it's fixed.

Windows batch: sleep

Microsoft has a sleep function you can call directly.

    Usage:  sleep      time-to-sleep-in-seconds
            sleep [-m] time-to-sleep-in-milliseconds
            sleep [-c] commited-memory ratio (1%-100%)

You can just say sleep 1 for example to sleep for 1 second in your batch script.

IMO Ping is a bit of a hack for this use case.

Identifier is undefined

From the update 2 and after narrowing down the problem scope, we can easily find that there is a brace missing at the end of the function addWord. The compiler will never explicitly identify such a syntax error. instead, it will assume that the missing function definition located in some other object file. The linker will complain about it and hence directly will be categorized under one of the broad the error phrases which is identifier is undefined. Reasonably, because with the current syntax the next function definition (in this case is ac_search) will be included under the addWord scope. Hence, it is not a global function anymore. And that is why compiler will not see this function outside addWord and will throw this error message stating that there is no such a function. A very good elaboration about the compiler and the linker can be found in this article

AngularJs ReferenceError: $http is not defined

Probably you haven't injected $http service to your controller. There are several ways of doing that.

Please read this reference about DI. Then it gets very simple:

function MyController($scope, $http) {
   // ... your code
}

Cast IList to List

If you have an IList containing interfaces, you can cast it like this:

List to IList

List<Foo> Foos = new List<Foo>(); 
IList<IFoo> IFoos = Foos.ToList<IFoo>();

IList to List

IList<IFoo> IFoos = new List<IFoo>();
List<Foo> Foos = new List<Foo>(IFoos.Select(x => (Foo)x));

This assumes Foo has IFoo interfaced.

How to check identical array in most efficient way?

You could compare String representations so:

array1.toString() == array2.toString()
array1.toString() !== array3.toString()

but that would also make

array4 = ['1',2,3,4,5]

equal to array1 if that matters to you

Why is January month 0 in Java Calendar?

Personally, I took the strangeness of the Java calendar API as an indication that I needed to divorce myself from the Gregorian-centric mindset and try to program more agnostically in that respect. Specifically, I learned once again to avoid hardcoded constants for things like months.

Which of the following is more likely to be correct?

if (date.getMonth() == 3) out.print("March");

if (date.getMonth() == Calendar.MARCH) out.print("March");

This illustrates one thing that irks me a little about Joda Time - it may encourage programmers to think in terms of hardcoded constants. (Only a little, though. It's not as if Joda is forcing programmers to program badly.)

Cannot refer to a non-final variable inside an inner class defined in a different method

Java doesn't support true closures, even though using an anonymous class like you are using here (new TimerTask() { ... }) looks like a kind of closure.

edit - See the comments below - the following is not a correct explanation, as KeeperOfTheSoul points out.

This is why it doesn't work:

The variables lastPrice and price are local variables in the main() method. The object that you create with the anonymous class might last until after the main() method returns.

When the main() method returns, local variables (such as lastPrice and price) will be cleaned up from the stack, so they won't exist anymore after main() returns.

But the anonymous class object references these variables. Things would go horribly wrong if the anonymous class object tries to access the variables after they have been cleaned up.

By making lastPrice and price final, they are not really variables anymore, but constants. The compiler can then just replace the use of lastPrice and price in the anonymous class with the values of the constants (at compile time, of course), and you won't have the problem with accessing non-existent variables anymore.

Other programming languages that do support closures do it by treating those variables specially - by making sure they don't get destroyed when the method ends, so that the closure can still access the variables.

@Ankur: You could do this:

public static void main(String args[]) {
    int period = 2000;
    int delay = 2000;

    Timer timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {
        // Variables as member variables instead of local variables in main()
        private double lastPrice = 0;
        private Price priceObject = new Price();
        private double price = 0;

        public void run() {
            price = priceObject.getNextPrice(lastPrice);
            System.out.println();
            lastPrice = price;
        }
    }, delay, period);      
}

How to import local packages without gopath

I have a similar problem and the solution I am currently using uses Go 1.11 modules. I have the following structure

- projects
  - go.mod
  - go.sum
  - project1
    - main.go
  - project2
    - main.go
  - package1
    - lib.go
  - package2
    - lib.go

And I am able to import package1 and package2 from project1 and project2 by using

import (
    "projects/package1"
    "projects/package2"
)

After running go mod init projects. I can use go build from project1 and project2 directories or I can do go build -o project1/exe project1/*.go from the projects directory.

The downside of this method is that all your projects end up sharing the same dependency list in go.mod. I am still looking for a solution to this problem, but it looks like it might be fundamental.

Long Press in JavaScript?

There is no 'jQuery' magic, just JavaScript timers.

var pressTimer;

$("a").mouseup(function(){
  clearTimeout(pressTimer);
  // Clear timeout
  return false;
}).mousedown(function(){
  // Set timeout
  pressTimer = window.setTimeout(function() { ... Your Code ...},1000);
  return false; 
});

How to correct TypeError: Unicode-objects must be encoded before hashing?

The error already says what you have to do. MD5 operates on bytes, so you have to encode Unicode string into bytes, e.g. with line.encode('utf-8').

Firebug like plugin for Safari browser

Firebug is great, but Safari provides its own built-in development tools.

If you haven't already tried Safari's development kit, go to Safari-->Preferences-->Advanced, and check the box next to "Show Develop menu in menu bar".

Once you have the Develop menu enabled, you can use the Web Inspector to get a lot of the same functionality that Firebug provides.

SQL LEFT-JOIN on 2 fields for MySQL

select a.ip, a.os, a.hostname, a.port, a.protocol,
       b.state
from a
left join b on a.ip = b.ip 
           and a.port = b.port

Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

Building on what is mentioned in the comments, the simplest solution would be:

@RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Collection<BudgetDTO> updateConsumerBudget(@RequestBody SomeDto someDto) throws GeneralException, ParseException {

    //whatever

}

class SomeDto {

   private List<WhateverBudgerPerDateDTO> budgetPerDate;


  //getters setters
}

The solution assumes that the HTTP request you are creating actually has

Content-Type:application/json instead of text/plain

How to synchronize a static variable among threads running different instances of a class in Java?

We can also use ReentrantLock to achieve the synchronization for static variables.

public class Test {

    private static int count = 0;
    private static final ReentrantLock reentrantLock = new ReentrantLock(); 
    public void foo() {  
        reentrantLock.lock();
        count = count + 1;
        reentrantLock.unlock();
    }  
}

Bootstrap 4 File Input

 <!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">

    <title>Hello, world!</title>
  </head>
  <body>
    <h1>Hello, world!</h1>
  <div class="custom-file">
    <input type="file" class="custom-file-input" id="inputGroupFile01">
    <label class="custom-file-label" for="inputGroupFile01">Choose file</label>
  </div>
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
 <script>
$(function() {
  $(document).on('change', ':file', function() {var input = $(this), numFiles = input.get(0).files ? input.get(0).files.length : 1,
        label = input.val().replace(/\\/g, '/').replace(/.*\//, '');input.trigger('fileselect', [numFiles, label]);
  });
  $(document).ready( function() {
      $(':file').on('fileselect', function(event, numFiles, label) {var input = $(this).parents('.custom-file').find('.custom-file-label'),
      log = numFiles > 1 ? numFiles + ' files selected' : label;if( input.length ) {input.text(log);} else {if( log ) alert(log);}});
  });
});
 </script>
  </body>
</html>

Converting char[] to byte[]

You could make a method:

public byte[] toBytes(char[] data) {
byte[] toRet = new byte[data.length];
for(int i = 0; i < toRet.length; i++) {
toRet[i] = (byte) data[i];
}
return toRet;
}

Hope this helps

Catch checked change event of a checkbox

use the click event for best compatibility with MSIE

$(document).ready(function() {
    $("input[type=checkbox]").click(function() {
        alert("state changed");
    });
});

How to set cellpadding and cellspacing in table with CSS?

Use padding on the cells and border-spacing on the table. The former will give you cellpadding while the latter will give you cellspacing.

table { border-spacing: 5px; } /* cellspacing */

th, td { padding: 5px; } /* cellpadding */

jsFiddle Demo

Difference between webdriver.get() and webdriver.navigate()

CASE-1

In the below code I navigated to 3 different URLs and when the execution comes to navigate command, it navigated back to facebook home page.

public class FirefoxInvoke {
                @Test
                public static void browserInvoke()
                {
                    System.setProperty("webdriver.gecko.driver", "gecko-driver-path");
                WebDriver driver=new FirefoxDriver();
                System.out.println("Before"+driver.getTitle());
                driver.get("http://www.google.com");
                driver.get("http://www.facebook.com");
                driver.get("http://www.india.com");
                driver.navigate().back();
                driver.quit();
                }

                public static void main(String[] args) {
                    // TODO Auto-generated method stub
            browserInvoke();
                }

            }

CASE-2:

In below code, I have used navigate() instead of get(), but both the snippets(Case-1 and Case-2) are working exactly the same, just the case-2 execution time is less than of case-1

public class FirefoxInvoke {
                @Test
                public static void browserInvoke()
                {
                    System.setProperty("webdriver.gecko.driver", "gecko-driver-path");
                WebDriver driver=new FirefoxDriver();
                System.out.println("Before"+driver.getTitle());
                driver.navigate().to("http://www.google.com");
                driver.navigate().to("http://www.facebook.com");
                driver.navigate().to("http://www.india.com");
                driver.navigate().back();
                driver.quit();
                }

                public static void main(String[] args) {
                    // TODO Auto-generated method stub
            browserInvoke();
                }

            }
  • So the main difference between get() and navigate() is, both are performing the same task but with the use of navigate() you can move back() or forward() in your session's history.
  • navigate() is faster than get() because navigate() does not wait for the page to load fully or completely.

LISTAGG function: "result of string concatenation is too long"

Since the aggregates string can be longer than 4000 bytes, you can't use the LISTAGG function. You could potentially create a user-defined aggregate function that returns a CLOB rather than a VARCHAR2. There is an example of a user-defined aggregate that returns a CLOB in the original askTom discussion that Tim links to from that first discussion.

Excel formula to display ONLY month and year?

First thing first. set the column in which you are working in by clicking on format cells->number-> date and then format e.g Jan-16 representing Jan, 1, 2016. and then apply either of the formulas above.

exit application when click button - iOS

You can use exit method to quit an ios app :

exit(0);

You should say same alert message and ask him to quit

Another way is by using [[NSThread mainThread] exit]

However you should not do this way

According to Apple, your app should not terminate on its own. Since the user did not hit the Home button, any return to the Home screen gives the user the impression that your app crashed. This is confusing, non-standard behavior and should be avoided.

What represents a double in sql server?

For SQL Sever:

Decimal Type is 128 bit signed number Float is a 64 bit signed number.

The real answer is Float, I was incorrect about decimal.

The reason is if you use a decimal you will never fill 64 bit of the decimal type.

Although decimal won't give you an error if you try to use a int type.

Here is a nice reference chart of the types.

Java method to swap primitives

It depends on what you want to do. This code swaps two elements of an array.

void swap(int i, int j, int[] arr) {
  int t = arr[i];
  arr[i] = arr[j];
  arr[j] = t;
}

Something like this swaps the content of two int[] of equal length.

void swap(int[] arr1, int[] arr2) {
  int[] t = arr1.clone();
  System.arraycopy(arr2, 0, arr1, 0, t.length);
  System.arraycopy(t, 0, arr2, 0, t.length);
}

Something like this swaps the content of two BitSet (using the XOR swap algorithm):

void swap(BitSet s1, BitSet s2) {
  s1.xor(s2);
  s2.xor(s1);
  s1.xor(s2);
}

Something like this swaps the x and y fields of some Point class:

void swapXY(Point p) {
  int t = p.x;
  p.x = p.y;
  p.y = t;
}

Checking if a variable is an integer

Basically, an integer n is a power of three, if there exists an integer x such that n == 3x.

So to verify that you can use this functions

def is_power_of_three(n)
  return false unless n.positive?

  n == 3**(Math.log10(n)/Math.log10(3)).to_f.round(2)
end

jQuery: find element by text

Fellas, I know this is old but hey I've this solution which I think works better than all. First and foremost overcomes the Case Sensitivity that the jquery :contains() is shipped with:

var text = "text";

var search = $( "ul li label" ).filter( function ()
{
    return $( this ).text().toLowerCase().indexOf( text.toLowerCase() ) >= 0;
}).first(); // Returns the first element that matches the text. You can return the last one with .last()

Hope someone in the near future finds it helpful.

SPAN vs DIV (inline-block)

According to the HTML spec, <span> is an inline element and <div> is a block element. Now that can be changed using the display CSS property but there is one issue: in terms of HTML validation, you can't put block elements inside inline elements so:

<p>...<div>foo</div>...</p>

is not strictly valid even if you change the <div> to inline or inline-block.

So, if your element is inline or inline-block use a <span>. If it's a block level element, use a <div>.

Can my enums have friendly names?

public enum myEnum
{
         ThisNameWorks, 
         This_Name_can_be_used_instead,

}

C# find biggest number

using System;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        int[] numbers = { 3, 9, 5 };
        int biggestNumber = numbers.Max();
        Console.WriteLine(biggestNumber);
        Console.ReadLine();
    }
}

How do you add a JToken to an JObject?

TL;DR: You should add a JProperty to a JObject. Simple. The index query returns a JValue, so figure out how to get the JProperty instead :)


The accepted answer is not answering the question as it seems. What if I want to specifically add a JProperty after a specific one? First, lets start with terminologies which really had my head worked up.

  • JToken = The mother of all other types. It can be A JValue, JProperty, JArray, or JObject. This is to provide a modular design to the parsing mechanism.
  • JValue = any Json value type (string, int, boolean).
  • JProperty = any JValue or JContainer (see below) paired with a name (identifier). For example "name":"value".
  • JContainer = The mother of all types which contain other types (JObject, JValue).
  • JObject = a JContainer type that holds a collection of JProperties
  • JArray = a JContainer type that holds a collection JValue or JContainer.

Now, when you query Json item using the index [], you are getting the JToken without the identifier, which might be a JContainer or a JValue (requires casting), but you cannot add anything after it, because it is only a value. You can change it itself, query more deep values, but you cannot add anything after it for example.

What you actually want to get is the property as whole, and then add another property after it as desired. For this, you use JOjbect.Property("name"), and then create another JProperty of your desire and then add it after this using AddAfterSelf method. You are done then.

For more info: http://www.newtonsoft.com/json/help/html/ModifyJson.htm

This is the code I modified.

public class Program
{
  public static void Main()
  {
    try
    {
      string jsonText = @"
      {
        ""food"": {
          ""fruit"": {
            ""apple"": {
              ""colour"": ""red"",
              ""size"": ""small""
            },
            ""orange"": {
              ""colour"": ""orange"",
              ""size"": ""large""
            }
          }
        }
      }";

      var foodJsonObj = JObject.Parse(jsonText);
      var bananaJson = JObject.Parse(@"{ ""banana"" : { ""colour"": ""yellow"", ""size"": ""medium""}}");

      var fruitJObject = foodJsonObj["food"]["fruit"] as JObject;
      fruitJObject.Property("orange").AddAfterSelf(new JProperty("banana", fruitJObject));

      Console.WriteLine(foodJsonObj.ToString());
    }
    catch (Exception ex)
    {
      Console.WriteLine(ex.GetType().Name + ": " + ex.Message);
    }
  }
}

Creating a thumbnail from an uploaded image

UPDATE:

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

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

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

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

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

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

WebSocket with SSL

The WebSocket connection starts its life with an HTTP or HTTPS handshake. When the page is accessed through HTTP, you can use WS or WSS (WebSocket secure: WS over TLS) . However, when your page is loaded through HTTPS, you can only use WSS - browsers don't allow to "downgrade" security.

Tips for debugging .htaccess rewrite rules

Set environment variables and use headers to receive them:

You can create new environment variables with RewriteRule lines, as mentioned by OP:

RewriteRule ^(.*) - [E=TEST0:%{DOCUMENT_ROOT}/blog/html_cache/$1.html]

But if you can't get a server-side script to work, how can you then read this environment variable? One solution is to set a header:

Header set TEST_FOOBAR "%{REDIRECT_TEST0}e"

The value accepts format specifiers, including the %{NAME}e specifier for environment variables (don't forget the lowercase e). Sometimes, you'll need to add the REDIRECT_ prefix, but I haven't worked out when the prefix gets added and when it doesn't.

How to check if all elements of a list matches a condition?

If you want to check if any item in the list violates a condition use all:

if all([x[2] == 0 for x in lista]):
    # Will run if all elements in the list has x[2] = 0 (use not to invert if necessary)

To remove all elements not matching, use filter

# Will remove all elements where x[2] is 0
listb = filter(lambda x: x[2] != 0, listb)

How do you set autocommit in an SQL Server session?

I wanted a more permanent and quicker way. Because I tend to forget to add extra lines before writing my actual Update/Insert queries.

I did it by checking SET IMPLICIT_TRANSACTIONS check-box from Options. To navigate to Options Select Tools>Options>Query Execution>SQL Server>ANSI in your Microsoft SQL Server Management Studio.

Just make sure to execute commit or rollback after you are done executing your queries. Otherwise, the table you would have run the query will be locked for others.

How to make the main content div fill height of screen with css

This question is a duplicate of Make a div fill the height of the remaining screen space and the correct answer is to use the flexbox model.

All major browsers and IE11+ support Flexbox. For IE 10 or older, or Android 4.3 and older, you can use the FlexieJS shim.

Note how simple the markup and the CSS are. No table hacks or anything.

html, body {
  height: 100%;
  margin: 0; padding: 0;  /* to avoid scrollbars */
}

#wrapper {
  display: flex;  /* use the flex model */
  min-height: 100%;
  flex-direction: column;  /* learn more: http://philipwalton.github.io/solved-by-flexbox/demos/sticky-footer/ */
}

#header {
  background: yellow;
  height: 100px;  /* can be variable as well */
}

#body {
  flex: 1;
  border: 1px solid orange;
}

#footer{
  background: lime;
}
<div id="wrapper">
  <div id="header">Title</div>
  <div id="body">Body</div>
  <div id="footer">
    Footer<br/>
    of<br/>
    variable<br/>
    height<br/>
  </div>
</div>

In the CSS above, the flex property shorthands the flex-grow, flex-shrink, and flex-basis properties to establish the flexibility of the flex items. Mozilla has a good introduction to the flexible boxes model.

MySQL show current connection info

You can use the status command in MySQL client.

mysql> status;
--------------
mysql  Ver 14.14 Distrib 5.5.8, for Win32 (x86)

Connection id:          1
Current database:       test
Current user:           ODBC@localhost
SSL:                    Not in use
Using delimiter:        ;
Server version:         5.5.8 MySQL Community Server (GPL)
Protocol version:       10
Connection:             localhost via TCP/IP
Server characterset:    latin1
Db     characterset:    latin1
Client characterset:    gbk
Conn.  characterset:    gbk
TCP port:               3306
Uptime:                 7 min 16 sec

Threads: 1  Questions: 21  Slow queries: 0  Opens: 33  Flush tables: 1  Open tables: 26  Queries per second avg: 0.48
--------------

mysql>

Which language uses .pde extension?

This code is from Processing.org an open source Java based IDE. You can find it Processing.org. The Arduino IDE also uses this extension, although they run on a hardware board.

EDIT - And yes it is C syntax, used mostly for art or live media presentations.

Call static method with reflection

I prefer simplicity...

private void _InvokeNamespaceClassesStaticMethod(string namespaceName, string methodName, params object[] parameters) {
    foreach(var _a in AppDomain.CurrentDomain.GetAssemblies()) {
        foreach(var _t in _a.GetTypes()) {
            try {
                if((_t.Namespace == namespaceName) && _t.IsClass) _t.GetMethod(methodName, (BindingFlags.Static | BindingFlags.Public))?.Invoke(null, parameters);
            } catch { }
        }
    }
}

Usage...

    _InvokeNamespaceClassesStaticMethod("mySolution.Macros", "Run");

But in case you're looking for something a little more robust, including the handling of exceptions...

private InvokeNamespaceClassStaticMethodResult[] _InvokeNamespaceClassStaticMethod(string namespaceName, string methodName, bool throwExceptions, params object[] parameters) {
    var results = new List<InvokeNamespaceClassStaticMethodResult>();
    foreach(var _a in AppDomain.CurrentDomain.GetAssemblies()) {
        foreach(var _t in _a.GetTypes()) {
            if((_t.Namespace == namespaceName) && _t.IsClass) {
                var method_t = _t.GetMethod(methodName, parameters.Select(_ => _.GetType()).ToArray());
                if((method_t != null) && method_t.IsPublic && method_t.IsStatic) {
                    var details_t = new InvokeNamespaceClassStaticMethodResult();
                    details_t.Namespace = _t.Namespace;
                    details_t.Class = _t.Name;
                    details_t.Method = method_t.Name;
                    try {
                        if(method_t.ReturnType == typeof(void)) {
                            method_t.Invoke(null, parameters);
                            details_t.Void = true;
                        } else {
                            details_t.Return = method_t.Invoke(null, parameters);
                        }
                    } catch(Exception ex) {
                        if(throwExceptions) {
                            throw;
                        } else {
                            details_t.Exception = ex;
                        }
                    }
                    results.Add(details_t);
                }
            }
        }
    }
    return results.ToArray();
}

private class InvokeNamespaceClassStaticMethodResult {
    public string Namespace;
    public string Class;
    public string Method;
    public object Return;
    public bool Void;
    public Exception Exception;
}

Usage is pretty much the same...

_InvokeNamespaceClassesStaticMethod("mySolution.Macros", "Run", false);

Skipping every other element after the first

There are more ways than one to skin a cat. - Seba Smith

arr = list(range(10)) # Range from 0-9

# List comprehension: Range with conditional
print [arr[index] for index in range(len(arr)) if index % 2 == 0]

# List comprehension: Range with step
print [arr[index] for index in range(0, len(arr), 2)]

# List comprehension: Enumerate with conditional
print [item for index, item in enumerate(arr) if index % 2 == 0]

# List filter: Index in range
print filter(lambda index: index % 2 == 0, range(len(arr)))

# Extended slice
print arr[::2]

Maven artifact and groupId naming

Consider following as for building basic first Maven application:

groupId

  • com.companyname.project

artifactId

  • project

version

  • 0.0.1

How do I create an .exe for a Java program?

If Java is installed on the target machine, there is no need to create an .exe file. A .jar file should be sufficient.

How to read .pem file to get private and public key

One option is to use bouncycastle's PEMParser:

Class for parsing OpenSSL PEM encoded streams containing X509 certificates, PKCS8 encoded keys and PKCS7 objects.

In the case of PKCS7 objects the reader will return a CMS ContentInfo object. Public keys will be returned as well formed SubjectPublicKeyInfo objects, private keys will be returned as well formed PrivateKeyInfo objects. In the case of a private key a PEMKeyPair will normally be returned if the encoding contains both the private and public key definition. CRLs, Certificates, PKCS#10 requests, and Attribute Certificates will generate the appropriate BC holder class.

Here is an example of using the Parser test code:

package org.bouncycastle.openssl.test;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.Signature;
import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPrivateKey;

import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.cms.CMSObjectIdentifiers;
import org.bouncycastle.asn1.cms.ContentInfo;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x9.ECNamedCurveTable;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMDecryptorProvider;
import org.bouncycastle.openssl.PEMEncryptedKeyPair;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.PEMWriter;
import org.bouncycastle.openssl.PasswordFinder;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder;
import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
import org.bouncycastle.operator.InputDecryptorProvider;
import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo;
import org.bouncycastle.util.test.SimpleTest;

/**
 * basic class for reading test.pem - the password is "secret"
 */
public class ParserTest
    extends SimpleTest
{
    private static class Password
        implements PasswordFinder
    {
        char[]  password;

        Password(
            char[] word)
        {
            this.password = word;
        }

        public char[] getPassword()
        {
            return password;
        }
    }

    public String getName()
    {
        return "PEMParserTest";
    }

    private PEMParser openPEMResource(
        String          fileName)
    {
        InputStream res = this.getClass().getResourceAsStream(fileName);
        Reader fRd = new BufferedReader(new InputStreamReader(res));
        return new PEMParser(fRd);
    }

    public void performTest()
        throws Exception
    {
        PEMParser       pemRd = openPEMResource("test.pem");
        Object          o;
        PEMKeyPair      pemPair;
        KeyPair         pair;

        while ((o = pemRd.readObject()) != null)
        {
            if (o instanceof KeyPair)
            {
                //pair = (KeyPair)o;

                //System.out.println(pair.getPublic());
                //System.out.println(pair.getPrivate());
            }
            else
            {
                //System.out.println(o.toString());
            }
        }

        // test bogus lines before begin are ignored.
        pemRd = openPEMResource("extratest.pem");

        while ((o = pemRd.readObject()) != null)
        {
            if (!(o instanceof X509CertificateHolder))
            {
                fail("wrong object found");
            }
        }

        //
        // pkcs 7 data
        //
        pemRd = openPEMResource("pkcs7.pem");
        ContentInfo d = (ContentInfo)pemRd.readObject();

        if (!d.getContentType().equals(CMSObjectIdentifiers.envelopedData))
        {
            fail("failed envelopedData check");
        }

        //
        // ECKey
        //
        pemRd = openPEMResource("eckey.pem");
        ASN1ObjectIdentifier ecOID = (ASN1ObjectIdentifier)pemRd.readObject();
        X9ECParameters ecSpec = ECNamedCurveTable.getByOID(ecOID);

        if (ecSpec == null)
        {
            fail("ecSpec not found for named curve");
        }

        pemPair = (PEMKeyPair)pemRd.readObject();

        pair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemPair);

        Signature sgr = Signature.getInstance("ECDSA", "BC");

        sgr.initSign(pair.getPrivate());

        byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };

        sgr.update(message);

        byte[]  sigBytes = sgr.sign();

        sgr.initVerify(pair.getPublic());

        sgr.update(message);

        if (!sgr.verify(sigBytes))
        {
            fail("EC verification failed");
        }

        if (!pair.getPublic().getAlgorithm().equals("ECDSA"))
        {
            fail("wrong algorithm name on public got: " + pair.getPublic().getAlgorithm());
        }

        if (!pair.getPrivate().getAlgorithm().equals("ECDSA"))
        {
            fail("wrong algorithm name on private");
        }

        //
        // ECKey -- explicit parameters
        //
        pemRd = openPEMResource("ecexpparam.pem");
        ecSpec = (X9ECParameters)pemRd.readObject();

        pemPair = (PEMKeyPair)pemRd.readObject();

        pair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemPair);

        sgr = Signature.getInstance("ECDSA", "BC");

        sgr.initSign(pair.getPrivate());

        message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };

        sgr.update(message);

        sigBytes = sgr.sign();

        sgr.initVerify(pair.getPublic());

        sgr.update(message);

        if (!sgr.verify(sigBytes))
        {
            fail("EC verification failed");
        }

        if (!pair.getPublic().getAlgorithm().equals("ECDSA"))
        {
            fail("wrong algorithm name on public got: " + pair.getPublic().getAlgorithm());
        }

        if (!pair.getPrivate().getAlgorithm().equals("ECDSA"))
        {
            fail("wrong algorithm name on private");
        }

        //
        // writer/parser test
        //
        KeyPairGenerator      kpGen = KeyPairGenerator.getInstance("RSA", "BC");

        pair = kpGen.generateKeyPair();

        keyPairTest("RSA", pair);

        kpGen = KeyPairGenerator.getInstance("DSA", "BC");
        kpGen.initialize(512, new SecureRandom());
        pair = kpGen.generateKeyPair();

        keyPairTest("DSA", pair);

        //
        // PKCS7
        //
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        PEMWriter             pWrt = new PEMWriter(new OutputStreamWriter(bOut));

        pWrt.writeObject(d);

        pWrt.close();

        pemRd = new PEMParser(new InputStreamReader(new ByteArrayInputStream(bOut.toByteArray())));
        d = (ContentInfo)pemRd.readObject();

        if (!d.getContentType().equals(CMSObjectIdentifiers.envelopedData))
        {
            fail("failed envelopedData recode check");
        }


        // OpenSSL test cases (as embedded resources)
        doOpenSslDsaTest("unencrypted");
        doOpenSslRsaTest("unencrypted");

        doOpenSslTests("aes128");
        doOpenSslTests("aes192");
        doOpenSslTests("aes256");
        doOpenSslTests("blowfish");
        doOpenSslTests("des1");
        doOpenSslTests("des2");
        doOpenSslTests("des3");
        doOpenSslTests("rc2_128");

        doOpenSslDsaTest("rc2_40_cbc");
        doOpenSslRsaTest("rc2_40_cbc");
        doOpenSslDsaTest("rc2_64_cbc");
        doOpenSslRsaTest("rc2_64_cbc");

        doDudPasswordTest("7fd98", 0, "corrupted stream - out of bounds length found");
        doDudPasswordTest("ef677", 1, "corrupted stream - out of bounds length found");
        doDudPasswordTest("800ce", 2, "unknown tag 26 encountered");
        doDudPasswordTest("b6cd8", 3, "DEF length 81 object truncated by 56");
        doDudPasswordTest("28ce09", 4, "DEF length 110 object truncated by 28");
        doDudPasswordTest("2ac3b9", 5, "DER length more than 4 bytes: 11");
        doDudPasswordTest("2cba96", 6, "DEF length 100 object truncated by 35");
        doDudPasswordTest("2e3354", 7, "DEF length 42 object truncated by 9");
        doDudPasswordTest("2f4142", 8, "DER length more than 4 bytes: 14");
        doDudPasswordTest("2fe9bb", 9, "DER length more than 4 bytes: 65");
        doDudPasswordTest("3ee7a8", 10, "DER length more than 4 bytes: 57");
        doDudPasswordTest("41af75", 11, "unknown tag 16 encountered");
        doDudPasswordTest("1704a5", 12, "corrupted stream detected");
        doDudPasswordTest("1c5822", 13, "unknown object in getInstance: org.bouncycastle.asn1.DERUTF8String");
        doDudPasswordTest("5a3d16", 14, "corrupted stream detected");
        doDudPasswordTest("8d0c97", 15, "corrupted stream detected");
        doDudPasswordTest("bc0daf", 16, "corrupted stream detected");
        doDudPasswordTest("aaf9c4d",17, "corrupted stream - out of bounds length found");

        doNoPasswordTest();

        // encrypted private key test
        InputDecryptorProvider pkcs8Prov = new JceOpenSSLPKCS8DecryptorProviderBuilder().build("password".toCharArray());
        pemRd = openPEMResource("enckey.pem");

        PKCS8EncryptedPrivateKeyInfo encPrivKeyInfo = (PKCS8EncryptedPrivateKeyInfo)pemRd.readObject();
        JcaPEMKeyConverter   converter = new JcaPEMKeyConverter().setProvider("BC");

        RSAPrivateCrtKey privKey = (RSAPrivateCrtKey)converter.getPrivateKey(encPrivKeyInfo.decryptPrivateKeyInfo(pkcs8Prov));

        if (!privKey.getPublicExponent().equals(new BigInteger("10001", 16)))
        {
            fail("decryption of private key data check failed");
        }

        // general PKCS8 test

        pemRd = openPEMResource("pkcs8test.pem");

        Object privInfo;

        while ((privInfo = pemRd.readObject()) != null)
        {
            if (privInfo instanceof PrivateKeyInfo)
            {
                privKey = (RSAPrivateCrtKey)converter.getPrivateKey(PrivateKeyInfo.getInstance(privInfo));
            }
            else
            {
                privKey = (RSAPrivateCrtKey)converter.getPrivateKey(((PKCS8EncryptedPrivateKeyInfo)privInfo).decryptPrivateKeyInfo(pkcs8Prov));
            }
            if (!privKey.getPublicExponent().equals(new BigInteger("10001", 16)))
            {
                fail("decryption of private key data check failed");
            }
        }
    }

    private void keyPairTest(
        String   name,
        KeyPair pair) 
        throws IOException
    {
        PEMParser pemRd;
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        PEMWriter             pWrt = new PEMWriter(new OutputStreamWriter(bOut));

        pWrt.writeObject(pair.getPublic());

        pWrt.close();

        pemRd = new PEMParser(new InputStreamReader(new ByteArrayInputStream(bOut.toByteArray())));

        SubjectPublicKeyInfo pub = SubjectPublicKeyInfo.getInstance(pemRd.readObject());
        JcaPEMKeyConverter   converter = new JcaPEMKeyConverter().setProvider("BC");

        PublicKey k = converter.getPublicKey(pub);

        if (!k.equals(pair.getPublic()))
        {
            fail("Failed public key read: " + name);
        }

        bOut = new ByteArrayOutputStream();
        pWrt = new PEMWriter(new OutputStreamWriter(bOut));

        pWrt.writeObject(pair.getPrivate());

        pWrt.close();

        pemRd = new PEMParser(new InputStreamReader(new ByteArrayInputStream(bOut.toByteArray())));

        KeyPair kPair = converter.getKeyPair((PEMKeyPair)pemRd.readObject());
        if (!kPair.getPrivate().equals(pair.getPrivate()))
        {
            fail("Failed private key read: " + name);
        }

        if (!kPair.getPublic().equals(pair.getPublic()))
        {
            fail("Failed private key public read: " + name);
        }
    }

    private void doOpenSslTests(
        String baseName)
        throws IOException
    {
        doOpenSslDsaModesTest(baseName);
        doOpenSslRsaModesTest(baseName);
    }

    private void doOpenSslDsaModesTest(
        String baseName)
        throws IOException
    {
        doOpenSslDsaTest(baseName + "_cbc");
        doOpenSslDsaTest(baseName + "_cfb");
        doOpenSslDsaTest(baseName + "_ecb");
        doOpenSslDsaTest(baseName + "_ofb");
    }

    private void doOpenSslRsaModesTest(
        String baseName)
        throws IOException
    {
        doOpenSslRsaTest(baseName + "_cbc");
        doOpenSslRsaTest(baseName + "_cfb");
        doOpenSslRsaTest(baseName + "_ecb");
        doOpenSslRsaTest(baseName + "_ofb");
    }

    private void doOpenSslDsaTest(
        String name)
        throws IOException
    {
        String fileName = "dsa/openssl_dsa_" + name + ".pem";

        doOpenSslTestFile(fileName, DSAPrivateKey.class);
    }

    private void doOpenSslRsaTest(
        String name)
        throws IOException
    {
        String fileName = "rsa/openssl_rsa_" + name + ".pem";

        doOpenSslTestFile(fileName, RSAPrivateKey.class);
    }

    private void doOpenSslTestFile(
        String  fileName,
        Class   expectedPrivKeyClass)
        throws IOException
    {
        JcaPEMKeyConverter   converter = new JcaPEMKeyConverter().setProvider("BC");
        PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().setProvider("BC").build("changeit".toCharArray());
        PEMParser pr = openPEMResource("data/" + fileName);
        Object o = pr.readObject();

        if (o == null || !((o instanceof PEMKeyPair) || (o instanceof PEMEncryptedKeyPair)))
        {
            fail("Didn't find OpenSSL key");
        }

        KeyPair kp = (o instanceof PEMEncryptedKeyPair) ?
            converter.getKeyPair(((PEMEncryptedKeyPair)o).decryptKeyPair(decProv)) : converter.getKeyPair((PEMKeyPair)o);

        PrivateKey privKey = kp.getPrivate();

        if (!expectedPrivKeyClass.isInstance(privKey))
        {
            fail("Returned key not of correct type");
        }
    }

    private void doDudPasswordTest(String password, int index, String message)
    {
        // illegal state exception check - in this case the wrong password will
        // cause an underlying class cast exception.
        try
        {
            PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().setProvider("BC").build(password.toCharArray());

            PEMParser pemRd = openPEMResource("test.pem");
            Object o;

            while ((o = pemRd.readObject()) != null)
            {
                if (o instanceof PEMEncryptedKeyPair)
                {
                    ((PEMEncryptedKeyPair)o).decryptKeyPair(decProv);
                }
            }

            fail("issue not detected: " + index);
        }
        catch (IOException e)
        {
            if (e.getCause() != null && !e.getCause().getMessage().endsWith(message))
            {
               fail("issue " + index + " exception thrown, but wrong message");
            }
            else if (e.getCause() == null && !e.getMessage().equals(message))
            {
                               e.printStackTrace();
               fail("issue " + index + " exception thrown, but wrong message");
            }
        }
    }

    private void doNoPasswordTest()
        throws IOException
    {
        PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().setProvider("BC").build("".toCharArray());

        PEMParser pemRd = openPEMResource("smimenopw.pem");
        Object o;
        PrivateKeyInfo key = null;

        while ((o = pemRd.readObject()) != null)
        {
             key = (PrivateKeyInfo)o;
        }

        if (key == null)
        {
            fail("private key not detected");
        }
    }

    public static void main(
        String[]    args)
    {
        Security.addProvider(new BouncyCastleProvider());

        runTest(new ParserTest());
    }
}

How to disable and then enable onclick event on <div> with javascript

You can disable the event by applying following code:

with .attr() API

$('#your_id').attr("disabled", "disabled");

or with .prop() API

$('#your_id').prop('disabled', true);

Setting DEBUG = False causes 500 Error

For what it's worth - I was getting a 500 with DEBUG = False on some pages only. Tracing back the exception with pdb revealed a missing asset (I suspect the {% static ... %} template tag was the culprit for the 500.

Execute a large SQL script (with GO commands)

use the following method to split the string and execute batch by batch

using System;
using System.IO;
using System.Text.RegularExpressions;
namespace RegExTrial
{
    class Program
    {
        static void Main(string[] args)
        {
            string sql = String.Empty;
            string path=@"D:\temp\sample.sql";
            using (StreamReader reader = new StreamReader(path)) {
                sql = reader.ReadToEnd();
            }            
            //Select any GO (ignore case) that starts with at least 
            //one white space such as tab, space,new line, verticle tab etc
            string pattern="[\\s](?i)GO(?-i)";

            Regex matcher = new Regex(pattern, RegexOptions.Compiled);
            int start = 0;
            int end = 0;
            Match batch=matcher.Match(sql);
            while (batch.Success) {
                end = batch.Index;
                string batchQuery = sql.Substring(start, end - start).Trim();
                //execute the batch
                ExecuteBatch(batchQuery);
                start = end + batch.Length;
                batch = matcher.Match(sql,start);
            }

        }

        private static void ExecuteBatch(string command)
        { 
            //execute your query here
        }

    }
}

Make a nav bar stick

/* Add css in your style */


.sticky-header {
    position: fixed;
    width: 100%;
    left: 0;
    top: 0;
    z-index: 100;
    border-top: 0;
    transition: 0.3s;
}


/* and use this javascript code: */

$(document).ready(function() {

  $(window).scroll(function () {
    if ($(window).scrollTop() > ) {
      $('.headercss').addClass('sticky-header');
    } else{
      $('.headercss').removeClass('sticky-header');
    }
  });
});

How do I request and receive user input in a .bat and use it to run a certain program?

Add quotation marks (" ") around the %INPUT% so it looks like this:

If "%INPUT%" == "y" goto yes
If "%INPUT%" == "n" goto no
If "%INPUT%" == "Y" goto yes
If "%INPUT%" == "N" goto no

How to handle invalid SSL certificates with Apache HttpClient?

I'm useing httpclient 3.1.X ,and this works for me

        try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        sslContext.init(null, new TrustManager[]{trustManager}, null);
        SslContextSecureProtocolSocketFactory socketFactory = new SslContextSecureProtocolSocketFactory(sslContext,false);
        Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory) socketFactory, 443));//??????HttpUtils
    } catch (Throwable e) {
        e.printStackTrace();

}

public class SslContextSecureProtocolSocketFactory implements      SecureProtocolSocketFactory {

private SSLContext sslContext;
private boolean verifyHostname;

public SslContextSecureProtocolSocketFactory(SSLContext sslContext, boolean verifyHostname) {
    this.verifyHostname = true;
    this.sslContext = sslContext;
    this.verifyHostname = verifyHostname;
}

public SslContextSecureProtocolSocketFactory(SSLContext sslContext) {
    this(sslContext, true);
}

public SslContextSecureProtocolSocketFactory(boolean verifyHostname) {
    this((SSLContext)null, verifyHostname);
}

public SslContextSecureProtocolSocketFactory() {
    this((SSLContext)null, true);
}

public synchronized void setHostnameVerification(boolean verifyHostname) {
    this.verifyHostname = verifyHostname;
}

public synchronized boolean getHostnameVerification() {
    return this.verifyHostname;
}

public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException {
    SSLSocketFactory sf = this.getSslSocketFactory();
    SSLSocket sslSocket = (SSLSocket)sf.createSocket(host, port, clientHost, clientPort);
    this.verifyHostname(sslSocket);
    return sslSocket;
}

public Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    if(params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    } else {
        int timeout = params.getConnectionTimeout();
        Socket socket = null;
        SSLSocketFactory socketfactory = this.getSslSocketFactory();
        if(timeout == 0) {
            socket = socketfactory.createSocket(host, port, localAddress, localPort);
        } else {
            socket = socketfactory.createSocket();
            InetSocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
            InetSocketAddress remoteaddr = new InetSocketAddress(host, port);
            socket.bind(localaddr);
            socket.connect(remoteaddr, timeout);
        }

        this.verifyHostname((SSLSocket)socket);
        return socket;
    }
}

public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    SSLSocketFactory sf = this.getSslSocketFactory();
    SSLSocket sslSocket = (SSLSocket)sf.createSocket(host, port);
    this.verifyHostname(sslSocket);
    return sslSocket;
}

public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
    SSLSocketFactory sf = this.getSslSocketFactory();
    SSLSocket sslSocket = (SSLSocket)sf.createSocket(socket, host, port, autoClose);
    this.verifyHostname(sslSocket);
    return sslSocket;
}

private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException {
    synchronized(this) {
        if(!this.verifyHostname) {
            return;
        }
    }

    SSLSession session = socket.getSession();
    String hostname = session.getPeerHost();

    try {
        InetAddress.getByName(hostname);
    } catch (UnknownHostException var10) {
        throw new UnknownHostException("Could not resolve SSL sessions server hostname: " + hostname);
    }

    X509Certificate[] certs = (X509Certificate[])((X509Certificate[])session.getPeerCertificates());
    if(certs != null && certs.length != 0) {
        X500Principal subjectDN = certs[0].getSubjectX500Principal();
        List cns = this.getCNs(subjectDN);
        boolean foundHostName = false;
        Iterator i$ = cns.iterator();
        AntPathMatcher matcher  = new AntPathMatcher();
        while(i$.hasNext()) {
            String cn = (String)i$.next();
            if(matcher.match(cn.toLowerCase(),hostname.toLowerCase())) {
                foundHostName = true;
                break;
            }
        }

        if(!foundHostName) {
            throw new SSLPeerUnverifiedException("HTTPS hostname invalid: expected \'" + hostname + "\', received \'" + cns + "\'");
        }
    } else {
        throw new SSLPeerUnverifiedException("No server certificates found!");
    }
}

private List<String> getCNs(X500Principal subjectDN) {
    ArrayList cns = new ArrayList();
    StringTokenizer st = new StringTokenizer(subjectDN.getName(), ",");

    while(st.hasMoreTokens()) {
        String cnField = st.nextToken();
        if(cnField.startsWith("CN=")) {
            cns.add(cnField.substring(3));
        }
    }

    return cns;
}

protected SSLSocketFactory getSslSocketFactory() {
    SSLSocketFactory sslSocketFactory = null;
    synchronized(this) {
        if(this.sslContext != null) {
            sslSocketFactory = this.sslContext.getSocketFactory();
        }
    }

    if(sslSocketFactory == null) {
        sslSocketFactory = (SSLSocketFactory)SSLSocketFactory.getDefault();
    }

    return sslSocketFactory;
}

public synchronized void setSSLContext(SSLContext sslContext) {
    this.sslContext = sslContext;
}

}

Formatting a number with leading zeros in PHP

When I need 01 instead of 1, the following worked for me:

$number = 1;
$number = str_pad($number, 2, '0', STR_PAD_LEFT);

How to tune Tomcat 5.5 JVM Memory settings without using the configuration program

I use following setenv.bat contents:

==============setenv.bat============

    set JAVA_OPTS=-XX:MaxPermSize=256m -Xms256M -Xmx768M -Xdebug -Xnoagent  -Xrunjdwp:transport=dt_socket,address=7777,server=y,suspend=n %JAVA_OPTS%

====================================

It also enables debugging and sets debug port to 7777, and appends previous content of JAVA_OPTS.

Is it possible to change the radio button icon in an android radio button group

You can put custom image in radiobutton like normal button. for that create one XML file in drawable folder e.g

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/sub_screens_aus_hl" 
    android:state_pressed="true"/>  
<item android:drawable="@drawable/sub_screens_aus" 
    android:state_checked="true"/>  
<item android:drawable="@drawable/sub_screens_aus" 
    android:state_focused="true" />
<item android:drawable="@drawable/sub_screens_aus_dis" />  
</selector> 

Here you can use 3 different images for radiobutton

and use this file to RadioButton like:

android:button="@drawable/aus"
android:layout_height="120dp"
android:layout_width="wrap_content" 

How to "z-index" to make a menu always on top of the content

You most probably don't need z-index to do that. You can use relative and absolute positioning.

I advise you to take a better look at css positioning and the difference between relative and absolute positioning... I saw you're setting position: absolute; to an element and trying to float that element. It won't work friend! When you understand positioning in CSS it will make your work a lot easier! ;)

Edit: Just to be clear, positioning is not a replacement for them and I do use z-index. I just try to avoid using them. Using z-indexes everywhere seems easy and fun at first... until you have bugs related to them and find yourself having to revisit and manage z-indexes.