Programs & Examples On #Hashalgorithm

0

The module was expected to contain an assembly manifest

I found another strange reason and i thought maybe another developer confused as me. I did run install.bat that created to install my service in developer Command Prompt of VS2010 but my service generated in VS2012. it was going to this error and drives me to crazy but i try VS2012 Developer Command Prompt tools and everything gone to be OK. I don't no why but my problem was solved. so you can test it and if anyone know reason of that please share with us. Thanks.

Reading large text files with streams in C#

You might be better off to use memory-mapped files handling here.. The memory mapped file support will be around in .NET 4 (I think...I heard that through someone else talking about it), hence this wrapper which uses p/invokes to do the same job..

Edit: See here on the MSDN for how it works, here's the blog entry indicating how it is done in the upcoming .NET 4 when it comes out as release. The link I have given earlier on is a wrapper around the pinvoke to achieve this. You can map the entire file into memory, and view it like a sliding window when scrolling through the file.

When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

If you are using Spring 3, the easiest way is:

 @RequestMapping(method = RequestMethod.GET)   
 public ModelAndView showResults(final HttpServletRequest request, Principal principal) {

     final String currentUser = principal.getName();

 }

mySQL :: insert into table, data from another table?

Answered by zerkms is the correct method. But, if someone looking to insert more extra column in the table then you can get it from the following:

INSERT INTO action_2_members (`campaign_id`, `mobile`, `email`, `vote`, `vote_date`, `current_time`)
SELECT `campaign_id`, `from_number`, '[email protected]', `received_msg`, `date_received`, 1502309889 FROM `received_txts` WHERE `campaign_id` = '8'

In the above query, there are 2 extra columns named email & current_time.

How To Accept a File POST

See the code below, adapted from this article, which demonstrates the simplest example code I could find. It includes both file and memory (faster) uploads.

public HttpResponseMessage Post()
{
    var httpRequest = HttpContext.Current.Request;
    if (httpRequest.Files.Count < 1)
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }

    foreach(string file in httpRequest.Files)
    {
        var postedFile = httpRequest.Files[file];
        var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
        postedFile.SaveAs(filePath);
        // NOTE: To store in memory use postedFile.InputStream
    }

    return Request.CreateResponse(HttpStatusCode.Created);
}

Ajax LARAVEL 419 POST error

You don't have any data that you're submitting! Try adding this line to your ajax:

data: $('form').serialize(),

Make sure you change the name to match!

Also your data should be submitted inside of a form submit function.

Your code should look something like this:

_x000D_
_x000D_
<script>_x000D_
 $(function () {_x000D_
  $('form').on('submit', function (e) {_x000D_
   e.preventDefault();_x000D_
   $.ajax({_x000D_
    type: 'post',_x000D_
    url: 'company.php',_x000D_
    data: $('form').serialize(),_x000D_
    success: function () {_x000D_
     alert('form was submitted');_x000D_
    }_x000D_
   });_x000D_
  });_x000D_
 });_x000D_
</script>
_x000D_
_x000D_
_x000D_

Convert decimal to binary in python

I agree with @aaronasterling's answer. However, if you want a non-binary string that you can cast into an int, then you can use the canonical algorithm:

def decToBin(n):
    if n==0: return ''
    else:
        return decToBin(n/2) + str(n%2)

Set TextView text from html-formatted string resource in XML

Escape your HTML tags ...

<resources>
    <string name="somestring">
        &lt;B&gt;Title&lt;/B&gt;&lt;BR/&gt;
        Content
    </string>
</resources>

Using ffmpeg to encode a high quality video

You need to specify the -vb option to increase the video bitrate, otherwise you get the default which produces smaller videos but with more artifacts.

Try something like this:

ffmpeg -r 25 -i %4d.png -vb 20M myvideo.mpg

Using async/await with a forEach loop

Using Task, futurize, and a traversable List, you can simply do

async function printFiles() {
  const files = await getFiles();

  List(files).traverse( Task.of, f => readFile( f, 'utf-8'))
    .fork( console.error, console.log)
}

Here is how you'd set this up

import fs from 'fs';
import { futurize } from 'futurize';
import Task from 'data.task';
import { List } from 'immutable-ext';

const future = futurizeP(Task)
const readFile = future(fs.readFile)

Another way to have structured the desired code would be

const printFiles = files => 
  List(files).traverse( Task.of, fn => readFile( fn, 'utf-8'))
    .fork( console.error, console.log)

Or perhaps even more functionally oriented

// 90% of encodings are utf-8, making that use case super easy is prudent

// handy-library.js
export const readFile = f =>
  future(fs.readFile)( f, 'utf-8' )

export const arrayToTaskList = list => taskFn => 
  List(files).traverse( Task.of, taskFn ) 

export const readFiles = files =>
  arrayToTaskList( files, readFile )

export const printFiles = files => 
  readFiles(files).fork( console.error, console.log)

Then from the parent function

async function main() {
  /* awesome code with side-effects before */
  printFiles( await getFiles() );
  /* awesome code with side-effects after */
}

If you really wanted more flexibility in encoding, you could just do this (for fun, I'm using the proposed Pipe Forward operator )

import { curry, flip } from 'ramda'

export const readFile = fs.readFile 
  |> future,
  |> curry,
  |> flip

export const readFileUtf8 = readFile('utf-8')

PS - I didn't try this code on the console, might have some typos... "straight freestyle, off the top of the dome!" as the 90s kids would say. :-p

Qt - reading from a text file

You have to replace string line

QString line = in.readLine();

into while:

QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
    QMessageBox::information(0, "error", file.errorString());
}

QTextStream in(&file);

while(!in.atEnd()) {
    QString line = in.readLine();    
    QStringList fields = line.split(",");    
    model->appendRow(fields);    
}

file.close();

lexical or preprocessor issue file not found occurs while archiving?

Delete the unit testing from your project follow the below steps this will solve the issue.

select your project from the project navigator to open the project editor. From the target delete the test from the left side of the project editor and press the Delete key.

How do you set a JavaScript onclick event to a class with css

Asking about "a class" in the question title, the answer is getElementsByClassName:

  var hrefs = document.getElementsByClassName("YOUR-CLASS-NAME-HERE");
  for (var i = 0; i < hrefs.length; i++) {
   hrefs.item(i).addEventListener('click', function(e){
    e.preventDefault(); /*use if you want to prevent the original link following action*/
    alert('hohoho');
   });
  }

Why do we use Base64?

It is more that the media validates the string encoding, so we want to ensure that the data is acceptable by a handling application (and doesn't contain a binary sequence representing EOL for example)

Imagine you want to send binary data in an email with encoding UTF-8 -- The email may not display correctly if the stream of ones and zeros creates a sequence which isn't valid Unicode in UTF-8 encoding.

The same type of thing happens in URLs when we want to encode characters not valid for a URL in the URL itself:

http://www.foo.com/hello my friend -> http://www.foo.com/hello%20my%20friend

This is because we want to send a space over a system that will think the space is smelly.

All we are doing is ensuring there is a 1-to-1 mapping between a known good, acceptable and non-detrimental sequence of bits to another literal sequence of bits, and that the handling application doesn't distinguish the encoding.

In your example, man may be valid ASCII in first form; but often you may want to transmit values that are random binary (ie sending an image in an email):

MIME-Version: 1.0
Content-Description: "Base64 encode of a.gif"
Content-Type: image/gif; name="a.gif"
Content-Transfer-Encoding: Base64
Content-Disposition: attachment; filename="a.gif"

Here we see that a GIF image is encoded in base64 as a chunk of an email. The email client reads the headers and decodes it. Because of the encoding, we can be sure the GIF doesn't contain anything that may be interpreted as protocol and we avoid inserting data that SMTP or POP may find significant.

What are the differences between stateless and stateful systems, and how do they impact parallelism?

A stateful server keeps state between connections. A stateless server does not.

So, when you send a request to a stateful server, it may create some kind of connection object that tracks what information you request. When you send another request, that request operates on the state from the previous request. So you can send a request to "open" something. And then you can send a request to "close" it later. In-between the two requests, that thing is "open" on the server.

When you send a request to a stateless server, it does not create any objects that track information regarding your requests. If you "open" something on the server, the server retains no information at all that you have something open. A "close" operation would make no sense, since there would be nothing to close.

HTTP and NFS are stateless protocols. Each request stands on its own.

Sometimes cookies are used to add some state to a stateless protocol. In HTTP (web pages), the server sends you a cookie and then the browser holds the state, only to send it back to the server on a subsequent request.

SMB is a stateful protocol. A client can open a file on the server, and the server may deny other clients access to that file until the client closes it.

Get url without querystring

Try this:

urlString=Request.RawUrl.ToString.Substring(0, Request.RawUrl.ToString.IndexOf("?"))

from this: http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye you'll get this: mypage.aspx

How can I send JSON response in symfony2 controller

Symfony 2.1 has a JsonResponse class.

return new JsonResponse(array('name' => $name));

The passed in array will be JSON encoded the status code will default to 200 and the content type will be set to application/json.

There is also a handy setCallback function for JSONP.

c# razor url parameter from view

You can use the following:

Request.Params["paramName"]

See also: When do Request.Params and Request.Form differ?

How do I get Flask to run on port 80?

So it's throwing up that error message because you have apache2 running on port 80.

If this is for development, I would just leave it as it is on port 5000.

If it's for production either:

Not Recommended

  • Stop apache2 first;

Not recommended as it states in the documentation:

You can use the builtin server during development, but you should use a full deployment option for production applications. (Do not use the builtin development server in production.)

Recommended

  • Proxy HTTP traffic through apache2 to Flask.

This way, apache2 can handle all your static files (which it's very good at - much better than the debug server built into Flask) and act as a reverse proxy for your dynamic content, passing those requests to Flask.

Here's a link to the official documentation about setting up Flask with Apache + mod_wsgi.

Edit 1 - Clarification for @Djack

Proxy HTTP traffic to Flask through apache2

When a request comes to the server on port 80 (HTTP) or port 443 (HTTPS) a web server like Apache or Nginx handles the connection of the request and works out what to do with it. In our case a request received should be configured to be passed through to Flask on the WSGI protocol and handled by the Python code. This is the "dynamic" part.

reverse proxy for dynamic content

There are a few advantages to configuring your web server like the above;

  • SSL Termination - The web server will be optimized to handle HTTPS requests with only a little configuration. Don't "roll your own" in Python which is probably very insecure in comparison.
  • Security - Opening a port to the internet requires careful consideration of security. Flask's development server is not designed for this and could have open bugs or security issues in comparison to a web server designed for this purpose. Note that a badly configured web server can also be insecure!
  • Static File Handling - It is possible for the builtin Flask web server to handle static files however this is not recommended; Nginx/Apache are much more efficient at handling static files like images, CSS, Javascript files and will only pass "dynamic" requests (those where the content is often read from a database or the content changes) to be handled by the Python code.
  • +more. This is bordering on scope for this question. If you want more info do some research into this area.

Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio

It may have been because I am still new to VS and definitely new to C, but the only thing that allowed me to build was adding

#pragma warning(disable:4996)

At the top of my file, this suppressed the C4996 error I was getting with sprintf

A bit annoying but perfect for my tiny bit of code and by far the easiest.

I read about it here: https://msdn.microsoft.com/en-us/library/2c8f766e.aspx

Extract source code from .jar file

I believe this can be done very easily. You can always extract the source files (Java files) of a jar file into a zip.

Steps to get sources of a jar file as a zip :

  1. Download JAD from http://techieme.in/resources-needed/ and save it at any
    location on your system.
  2. Drag and drop the jar for which you want the sources on the JAD. 3 JAD UI will open with all the package structure in a tree format.
  3. Click on File menu and select save jar sources.
  4. It will save the sources as a zip with the same name as the jar.

Hope this helps.

The link is dead due to some reason so adding the link from where you can download the JDGUI

Change Placeholder Text using jQuery

$(document).ready(function(){ 
     $("input[type=search]").attr("placeholder","this is a test");
});

Finding what branch a Git commit came from

This simple command works like a charm:

git name-rev <SHA>

For example (where test-branch is the branch name):

git name-rev 651ad3a
251ad3a remotes/origin/test-branch

Even this is working for complex scenarios, like:

origin/branchA/
              /branchB
                      /commit<SHA1>
                                   /commit<SHA2>

Here git name-rev commit<SHA2> returns branchB.

Why cannot cast Integer to String in java?

You can't cast explicitly anything to a String that isn't a String. You should use either:

"" + myInt;

or:

Integer.toString(myInt);

or:

String.valueOf(myInt);

I prefer the second form, but I think it's personal choice.

Edit OK, here's why I prefer the second form. The first form, when compiled, could instantiate a StringBuffer (in Java 1.4) or a StringBuilder in 1.5; one more thing to be garbage collected. The compiler doesn't optimise this as far as I could tell. The second form also has an analogue, Integer.toString(myInt, radix) that lets you specify whether you want hex, octal, etc. If you want to be consistent in your code (purely aesthetically, I guess) the second form can be used in more places.

Edit 2 I assumed you meant that your integer was an int and not an Integer. If it's already an Integer, just use toString() on it and be done.

How to change the button text of <input type="file" />?

Hide the file input. Create a new input to capture a click event and forward it to the hidden input:

<input type="button" id="loadFileXml" value="loadXml" onclick="document.getElementById('file').click();" />
<input type="file" style="display:none;" id="file" name="file"/>

JBoss vs Tomcat again

First the facts, neither is better. As you already mentioned, Tomcat provides a servlet container that supports the Servlet specification (Tomcat 7 supports Servlet 3.0). JBoss AS, a 'complete' application server supports Java EE 6 (including Servlet 3.0) in its current version.

Tomcat is fairly lightweight and in case you need certain Java EE features beyond the Servlet API, you can easily enhance Tomcat by providing the required libraries as part of your application. For example, if you need JPA features you can include Hibernate or OpenEJB and JPA works nearly out of the box.

How to decide whether to use Tomcat or a full stack Java EE application server:

When starting your project you should have an idea what it requires. If you're in a large enterprise environment JBoss (or any other Java EE server) might be the right choice as it provides built-in support for e.g:

  1. JMS messaging for asynchronous integration
  2. Web Services engine (JAX-WS and/or JAX-RS)
  3. Management capabilities like JMX and a scripted administration interface
  4. Advanced security, e.g. out-of-the-box integration with 3rd party directories
  5. EAR file instead of "only" WAR file support
  6. all the other "great" Java EE features I can't remember :-)

In my opinion Tomcat is a very good fit if it comes to web centric, user facing applications. If backend integration comes into play, a Java EE application server should be (at least) considered. Last but not least, migrating a WAR developed for Tomcat to JBoss should be a 1 day excercise.

Second, you should also take the usage inside your environment into account. In case your organization already runs say 1,000 JBoss instances, you might always go with that regardless of your concrete requirements (consider aspects like cost for operations or upskilling). Of course, this applies vice versa.

my 2 cent

How to convert CLOB to VARCHAR2 inside oracle pl/sql

This is my aproximation:

  Declare 
  Variableclob Clob;
  Temp_Save Varchar2(32767); //whether it is greater than 4000

  Begin
  Select reportClob Into Temp_Save From Reporte Where Id=...;
  Variableclob:=To_Clob(Temp_Save);
  Dbms_Output.Put_Line(Variableclob);


  End;

ASP.NET Forms Authentication failed for the request. Reason: The ticket supplied has expired

I was getting this same error, in our case it was caused by a load balancer. We hade to make sure that the persistance was set to Source IP. Otherwise the login form was opened by one server, and processed by the other, which would fail to set the authentication cookie correctly. Maybe this helps someone else

How to test multiple variables against a value?

To test multiple variables with one single value: if 1 in {a,b,c}:

To test multiple values with one variable: if a in {1, 2, 3}:

PHP combine two associative arrays into one array

Check out array_merge().

$array3 = array_merge($array1, $array2);

Typescript input onchange event.target.value

  function handle_change(
    evt: React.ChangeEvent<HTMLInputElement>
  ): string {
    evt.persist(); // This is needed so you can actually get the currentTarget
    const inputValue = evt.currentTarget.value;

    return inputValue
  }

And make sure you have "lib": ["dom"] in your tsconfig.

error: ORA-65096: invalid common user or role name in oracle

Might be, more safe alternative to "_ORACLE_SCRIPT"=true is to change "_common_user_prefix" from C## to an empty string. When it's null - any name can be used for common user. Found there.

During changing that value you may face another issue - ORA-02095 - parameter cannot be modified, that can be fixed in a several ways, based on your configuration (source).

So for me worked that:

alter system set _common_user_prefix = ''; scope=spfile;

AppFabric installation failed because installer MSI returned with error code : 1603

Looks like I got all the possible issues with that installation.

Troubleshooting: look at actual log file (in the log provided by the installer look for LOGFILE=...):

Process.Start: C:\Windows\system32\msiexec.exe /quiet /norestart /i "c:\2964b29c3cd7dcb37c9e\Packages\AppFabric-1.1-for-Windows-Server-64.msi" ADDDEFAULT=Worker,WorkerAdmin,CacheService,CacheClient,CacheAdmin,Setup /l*vx "c:\Temp\AppServerSetup1_1(2014-07-09 11-58-09).log" LOGFILE="c:\Temp\AppServerSetup1_1_CustomActions(2014-07-09 11-58-09).log" INSTALLDIR="C:\Program Files\AppFabric 1.1 for Windows Server" LANGID=en-US

After you located the actual log file, check for errors. I had to:

  1. Fails to create AS_Observer:
    • Exec: c:\Windows\system32\net.exe localgroup AS_Observers /delete
  2. Fails to set ACLs on config folder:
    • Exec: md C:\Windows\SysWOW64\inetsrv\config
  3. COM not registered:
    • Install activation service feature for .NET 3.5 (both HTTP and non-HTTP) and enable HTTP activation for .NET 4.5

done. Hope that helps.

How can I unstage my files again after making a local commit?

To me, the following is more readable (thus preferable) way to do it:

git reset HEAD~1

Instead of 1, there could be any number of commits you want to unstage.

Getting a "This application is modifying the autolayout engine from a background thread" error?

It needs to be placed inside a different thread that allows the UI to update as soon as execution of thread function completes:

Modern Swift:

DispatchQueue.main.async {
    // Update UI
}

Older versions of Swift, pre Swift 3.

dispatch_async(dispatch_get_main_queue(){
    // code here
})

Objective-C:

dispatch_async(dispatch_get_main_queue(), ^{
    // code here
});

How to change facet labels?

If you have two facets hospital and room but want to rename just one, you can use:

facet_grid( hospital ~ room, labeller = labeller(hospital = as_labeller(hospital_names)))

For renaming two facets using the vector-based approach (as in naught101's answer), you can do:

facet_grid( hospital ~ room, labeller = labeller(hospital = as_labeller(hospital_names),
                                                 room = as_labeller(room_names)))

Error while trying to retrieve text for error ORA-01019

Well,

Just worked it out. While having both installations we have two ORACLE_HOME directories and both have SQAORA32.dll files. While looking up for ORACLE_HOMe my app was getting confused..I just removed the Client oracle home entry as oracle client is by default present in oracle DB Now its working...Thanks!!

How to unpackage and repackage a WAR file

Non programmatically, you can just open the archive using the 7zip UI to add/remove or extract/replace files without the structure changing. I didn't know it was a problem using other things until now :)

mysql: get record count between two date-time

May be with:

SELECT count(*) FROM `table` 
where 
    created_at>='2011-03-17 06:42:10' and created_at<='2011-03-17 07:42:50';

or use between:

SELECT count(*) FROM `table` 
where 
    created_at between '2011-03-17 06:42:10' and '2011-03-17 07:42:50';

You can change the datetime as per your need. May be use curdate() or now() to get the desired dates.

How to set web.config file to show full error message

If you're using ASP.NET MVC you might also need to remove the HandleErrorAttribute from the Global.asax.cs file:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
}

ImportError: No module named 'google'

got this from cloud service documentation

pip install --upgrade google-cloud-translate

Worked for me !

URL Encoding using C#

I have written a C# method that url-encodes ALL symbols:

    /// <summary>
    /// !#$345Hf} ? %21%23%24%33%34%35%48%66%7D
    /// </summary>
    public static string UrlEncodeExtended( string value )
    {
        char[] chars = value.ToCharArray();
        StringBuilder encodedValue = new StringBuilder();
        foreach (char c in chars)
        {
            encodedValue.Append( "%" + ( (int)c ).ToString( "X2" ) );
        }
        return encodedValue.ToString();
    }

Save Dataframe to csv directly to s3 Python

I like s3fs which lets you use s3 (almost) like a local filesystem.

You can do this:

import s3fs

bytes_to_write = df.to_csv(None).encode()
fs = s3fs.S3FileSystem(key=key, secret=secret)
with fs.open('s3://bucket/path/to/file.csv', 'wb') as f:
    f.write(bytes_to_write)

s3fs supports only rb and wb modes of opening the file, that's why I did this bytes_to_write stuff.

Simple way to understand Encapsulation and Abstraction

Abstraction is hiding the information or providing only necessary details to the client.

e.g Car Brakes- You just know that pressing the pedals will stop the vehicle but you don't need to know how it works internally.

Advantage of Abstraction Tomorrow if brake implementation changes from drum brake to disk brake, as a client, you don't need to change(i.e your code will not change)

Encapsulation is binding the data and behaviors together in a single unit. Also it is a language mechanism for restricting access to some components(this can be achieved by access modifiers like private,protected etc.)

For e.g. Class has attributes(i.e data) and behaviors (i.e methods that operate on that data)

C++ vector of char array

FFWD to 2019. Although this code worketh in 2011 too.

// g++ prog.cc -Wall -std=c++11
#include <iostream>
#include <vector>

 using namespace std;

 template<size_t N>
    inline 
      constexpr /* compile time */
      array<char,N> string_literal_to_array ( char const (&charrar)[N] )
 {
    return std::to_array( charrar) ;
 }

 template<size_t N>
    inline 
      /* run time */
      vector<char> string_literal_to_vector ( char const (&charrar)[N] )
 {
    return { charrar, charrar + N };
 }


int main()
{
   constexpr auto arr = string_literal_to_array("Compile Time");
   auto cv = string_literal_to_vector ("Run Time") ;
   return 42;
}

Advice: try optimizing the use of std::string. For char buffering std::array<char,N> is the fastest, std::vector<char> is faster.

https://wandbox.org/permlink/wcasstoY56MWbHqd

Putting text in top left corner of matplotlib plot

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 6))
plt.text(0.1, 0.9, 'text', size=15, color='purple')

# or 

fig, axe = plt.subplots(figsize=(6, 6))
axe.text(0.1, 0.9, 'text', size=15, color='purple')

Output of Both

enter image description here

import matplotlib.pyplot as plt

# Build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
ax = plt.gca()
p = plt.Rectangle((left, bottom), width, height, fill=False)
p.set_transform(ax.transAxes)
p.set_clip_on(False)
ax.add_patch(p)


ax.text(left, bottom, 'left top',
        horizontalalignment='left',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, bottom, 'left bottom',
        horizontalalignment='left',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right bottom',
        horizontalalignment='right',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right top',
        horizontalalignment='right',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(right, bottom, 'center top',
        horizontalalignment='center',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'right center',
        horizontalalignment='right',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'left center',
        horizontalalignment='left',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(0.5 * (left + right), 0.5 * (bottom + top), 'middle',
        horizontalalignment='center',
        verticalalignment='center',
        transform=ax.transAxes)

ax.text(right, 0.5 * (bottom + top), 'centered',
        horizontalalignment='center',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, top, 'rotated\nwith newlines',
        horizontalalignment='center',
        verticalalignment='center',
        rotation=45,
        transform=ax.transAxes)

plt.axis('off')

plt.show()

enter image description here

How to remove a virtualenv created by "pipenv run"

I know that question is a bit old but

In root of project where Pipfile is located you could run

pipenv --venv

which returns

/Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU

and then remove this env by typing

rm -rf /Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU

CSS 100% height with padding/margin

Frank's example confused me a bit - it didn't work in my case because I didn't understand positioning well enough yet. It's important to note that the parent container element needs to have a non-static position (he mentioned this but I overlooked it, and it wasn't in his example).

Here's an example where the child - given padding and a border - uses absolute positioning to fill the parent 100%. The parent uses relative positioning in order to provide a point of reference for the child's position while remaining in the normal flow - the next element "more-content" is not affected:

#box {
    position: relative;
    height: 300px;
    width: 600px;
}

#box p {
    position: absolute;
    border-style: dashed;
    padding: 1em;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}
<div id="box">
  <p>100% height and width!</p>
</div>
<div id="more-content">
</div>

A useful link for quickly learning CSS positioning

Unable to preventDefault inside passive event listener

To still be able to scroll this worked for me

if (e.changedTouches.length > 1) e.preventDefault();

How do I convert a String object into a Hash object?

I came to this question after writing a one-liner for this purpose, so I share my code in case it helps somebody. Works for a string with only one level depth and possible empty values (but not nil), like:

"{ :key_a => 'value_a', :key_b => 'value_b', :key_c => '' }"

The code is:

the_string = '...'
the_hash = Hash.new
the_string[1..-2].split(/, /).each {|entry| entryMap=entry.split(/=>/); value_str = entryMap[1]; the_hash[entryMap[0].strip[1..-1].to_sym] = value_str.nil? ? "" : value_str.strip[1..-2]}

Understanding Fragment's setRetainInstance(boolean)

SetRetainInstance(true) allows the fragment sort of survive. Its members will be retained during configuration change like rotation. But it still may be killed when the activity is killed in the background. If the containing activity in the background is killed by the system, it's instanceState should be saved by the system you handled onSaveInstanceState properly. In another word the onSaveInstanceState will always be called. Though onCreateView won't be called if SetRetainInstance is true and fragment/activity is not killed yet, it still will be called if it's killed and being tried to be brought back.

Here are some analysis of the android activity/fragment hope it helps. http://ideaventure.blogspot.com.au/2014/01/android-activityfragment-life-cycle.html

Producing a new line in XSLT

I added the DOCTYPE directive you see here:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xsl:stylesheet [
  <!ENTITY nl "&#xa;">
]>
<xsl:stylesheet xmlns:x="http://www.w3.org/2005/02/query-test-XQTSCatalog"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="2.0">

This allows me to use &nl; instead of &#xa; to produce a newline in the output. Like other solutions, this is typically placed inside a <xsl:text> tag.

How to detect the swipe left or Right in Android?

You should be extend a class from View.OnTouchListener and handle the onTouch method by overriding it.

interface SwipeListener {
    fun onSwipeLeft()
    fun onSwipeRight()
}

class SwipeGestureListener internal constructor(
    private val listener: SwipeListener,
    private val minDistance: Int = DEFAULT_SWIPE_MIN_DISTANCE
) : View.OnTouchListener {
    companion object {
        const val DEFAULT_SWIPE_MIN_DISTANCE = 200
    }

    private var anchorX = 0F

    override fun onTouch(view: View, event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                anchorX = event.x
                return true
            }
            MotionEvent.ACTION_UP -> {
                if (abs(event.x - anchorX) > minDistance) {
                    if (event.x > anchorX) {
                        listener.onSwipeRight()
                    } else {
                        listener.onSwipeLeft()
                    }
                }
                return true
            }
        }
        return view.performClick()
    }
}

You can just easily implement it like this in your Activity or Fragment.

class MainActivity : AppCompatActivity(), SwipeListener {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        viewGroup.setOnTouchListener(SwipeGestureListener(this))
    }

    override fun onSwipeLeft() {
        Toast.makeText(this, "Swipe Left", Toast.LENGTH_SHORT).show()
    }

    override fun onSwipeRight() {
        Toast.makeText(this, "Swipe Right", Toast.LENGTH_SHORT).show()
    }
}

month name to month number and vice versa in python

def month_num2abbr(month):
    month = int(month)
    import calendar
    months_abbr = {month: index for index, month in enumerate(calendar.month_abbr) if month}
    for abbr, month_num in months_abbr.items():
        if month_num==month:
            return abbr
    return False

print(month_num2abbr(7))

Soft Edges using CSS?

You can use CSS gradient - although there are not consistent across browsers so You would have to code it for every one

Like that: CSS3 Transparency + Gradient

Gradient should be more transparent on top or on top right corner (depending on capabilities)

How can I create a Java method that accepts a variable number of arguments?

You could write a convenience method:

public PrintStream print(String format, Object... arguments) {
    return System.out.format(format, arguments);
}

But as you can see, you've simply just renamed format (or printf).

Here's how you could use it:

private void printScores(Player... players) {
    for (int i = 0; i < players.length; ++i) {
        Player player = players[i];
        String name   = player.getName();
        int    score  = player.getScore();
        // Print name and score followed by a newline
        System.out.format("%s: %d%n", name, score);
    }
}

// Print a single player, 3 players, and all players
printScores(player1);
System.out.println();
printScores(player2, player3, player4);
System.out.println();
printScores(playersArray);

// Output
Abe: 11

Bob: 22
Cal: 33
Dan: 44

Abe: 11
Bob: 22
Cal: 33
Dan: 44

Note there's also the similar System.out.printf method that behaves the same way, but if you peek at the implementation, printf just calls format, so you might as well use format directly.

How come I can't remove the blue textarea border in Twitter Bootstrap?

Your best bet is to right click > inspect the element.

I am using Bootstrap 4 and none of the suggestions worked until I did this.

Once I found where the relevant code was in the inspect window, I copied and pasted the relevant code that was causing the :focus to be outlined blue and changed it accordingly.

This is the code that worked in my css

.btn.focus, .btn:focus
{
outline: 0;
box-shadow: 0 0 0 0;
}

How to open URL in Microsoft Edge from the command line?

All the other solutions work for Microsoft Edge (legacy) and on Windows 10 only. As of 2020, it will be discontinued and replaced by Microsoft Edge (Chromium based).

The solution that works with the new Edge on Windows 7, 8 and 10 is :

start msedge URL

Source :

How to permanently add a private key with ssh-add on Ubuntu?

This worked for me.

ssh-agent /bin/sh
ssh-add /path/to/your/key

Is there Unicode glyph Symbol to represent "Search"

You can simply add this CSS to your header

<link href='http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css' rel='stylesheet' type='text/css'>

next add this code in place where you want to display a glyph symbol.

<div class="fa fa-search"></div> <!-- smaller -->
<div class="fa fa-search fa-2x"></div> <!-- bigger -->

Have fun.

(.text+0x20): undefined reference to `main' and undefined reference to function

This rule

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o

is wrong. It says to create a file named producer.o (with -o producer.o), but you want to create a file named main. Please excuse the shouting, but ALWAYS USE $@ TO REFERENCE THE TARGET:

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o

As Shahbaz rightly points out, the gmake professionals would also use $^ which expands to all the prerequisites in the rule. In general, if you find yourself repeating a string or name, you're doing it wrong and should use a variable, whether one of the built-ins or one you create.

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ $^

Stop on first error

Maybe you want set -e:

www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:

This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.

How do browser cookie domains work?

Although there is the RFC 2965 (Set-Cookie2, had already obsoleted RFC 2109) that should define the cookie nowadays, most browsers don’t fully support that but just comply to the original specification by Netscape.

There is a distinction between the Domain attribute value and the effective domain: the former is taken from the Set-Cookie header field and the latter is the interpretation of that attribute value. According to the RFC 2965, the following should apply:

  • If the Set-Cookie header field does not have a Domain attribute, the effective domain is the domain of the request.
  • If there is a Domain attribute present, its value will be used as effective domain (if the value does not start with a . it will be added by the client).

Having the effective domain it must also domain-match the current requested domain for being set; otherwise the cookie will be revised. The same rule applies for choosing the cookies to be sent in a request.


Mapping this knowledge onto your questions, the following should apply:

  • Cookie with Domain=.example.com will be available for www.example.com
  • Cookie with Domain=.example.com will be available for example.com
  • Cookie with Domain=example.com will be converted to .example.com and thus will also be available for www.example.com
  • Cookie with Domain=example.com will not be available for anotherexample.com
  • www.example.com will be able to set cookie for example.com
  • www.example.com will not be able to set cookie for www2.example.com
  • www.example.com will not be able to set cookie for .com

And to set and read a cookie for/by www.example.com and example.com, set it for .www.example.com and .example.com respectively. But the first (.www.example.com) will only be accessible for other domains below that domain (e.g. foo.www.example.com or bar.www.example.com) where .example.com can also be accessed by any other domain below example.com (e.g. foo.example.com or bar.example.com).

How do you keep parents of floated elements from collapsing?

My favourite method is using a clearfix class for parent element

.clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}

.clearfix {
    display: inline-block;
}

* html .clearfix {
    height: 1%;
}

.clearfix {
    display: block;
}

conflicting types error when compiling c program using gcc

To answer a more generic case, this error is noticed when you pick a function name which is already used in some built in library. For e.g., select.

A simple method to know about it is while compiling the file, the compiler will indicate the previous declaration.

Javascript: How to pass a function with string parameters as a parameter to another function

One way would be to just escape the quotes properly:

<input type="button" value="click" id="mybtn"
       onclick="myfunction('/myController/myAction', 
               'myfuncionOnOK(\'/myController2/myAction2\', 
                   \'myParameter2\');',
               'myfuncionOnCancel(\'/myController3/myAction3\', 
                   \'myParameter3\');');">

In this case, though, I think a better way to handle this would be to wrap the two handlers in anonymous functions:

<input type="button" value="click" id="mybtn"
       onclick="myfunction('/myController/myAction', 
                function() { myfuncionOnOK('/myController2/myAction2', 
                             'myParameter2'); },
                function() { myfuncionOnCancel('/myController3/myAction3', 
                             'myParameter3'); });">

And then, you could call them from within myfunction like this:

function myfunction(url, onOK, onCancel)
{
    // Do whatever myfunction would normally do...

    if (okClicked)
    {
        onOK();
    }

    if (cancelClicked)
    {
        onCancel();
    }
}

That's probably not what myfunction would actually look like, but you get the general idea. The point is, if you use anonymous functions, you have a lot more flexibility, and you keep your code a lot cleaner as well.

Is it possible to change the location of packages for NuGet?

In addition to Shane Kms answer, if you've activated Nuget Package Restore, you edit the NuGet.config located in the .nuget-folder as follows:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <repositoryPath>..\..\ExtLibs\Packages</repositoryPath>
</configuration>

Notice the extra "..\", as it backtracks from the .nuget-folder and not the solution folder.

How to use std::sort to sort an array in C++

#include <algorithm>
static const size_t v_size = 2000;
int v[v_size];
// Fill the array by values
std::sort(v,v+v_size); 

In C++11:

#include <algorithm>
#include <array>
std::array<int, 2000> v;
// Fill the array by values
std::sort(v.begin(),v.end()); 

Download pdf file using jquery ajax

You can do this with html5 very easily:

var link = document.createElement('a');
link.href = "/WWW/test.pdf";
link.download = "file_" + new Date() + ".pdf";
link.click();
link.remove()

How to use onResume()?

Re-review the Android Activity Lifecycle reference. There is a nice picture, and the table showing what methods get called. reference Link google

https://developer.android.com/reference/android/app/Activity.html

.htaccess File Options -Indexes on Subdirectories

htaccess files affect the directory they are placed in and all sub-directories, that is an htaccess file located in your root directory (yoursite.com) would affect yoursite.com/content, yoursite.com/content/contents, etc.

http://www.javascriptkit.com/howto/htaccess.shtml

Check if number is prime number

This version calculates a list of primes square roots and only checks if the list of prime numbers below the square root, and uses a binarysearch in the list to find known primes. I looped through to check the first 1,000,000 primes, and it took about 7 seconds.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            //test();
            testMax();
            Console.ReadLine();
        }

        static void testMax()
        {
            List<int> CheckPrimes = Enumerable.Range(2, 1000000).ToList();
            PrimeChecker pc = new PrimeChecker(1000000);
            foreach (int i in CheckPrimes)
            {
                if (pc.isPrime(i))
                {
                    Console.WriteLine(i);
                }
            }
        }
    }

    public class PrimeChecker{
        public List<int> KnownRootPrimesList;
        public int HighestKnownPrime = 3;

        public PrimeChecker(int Max=1000000){
            KnownRootPrimesList = new List<int>();
            KnownRootPrimesList.Add(2);
            KnownRootPrimesList.Add(3);
            isPrime(Max);
        }

        public bool isPrime(int value)
        {
            int srt = Convert.ToInt32(Math.Ceiling(Math.Sqrt(Convert.ToDouble(value))));
            if(srt > HighestKnownPrime)
            {
                for(int i = HighestKnownPrime + 1; i <= srt; i++)
                {
                    if (i > HighestKnownPrime)
                    {
                        if(isPrimeCalculation(i))
                        {
                                KnownRootPrimesList.Add(i);
                                HighestKnownPrime = i;
                        }
                    }
                }
            }
            bool isValuePrime = isPrimeCalculation(value);
            return(isValuePrime);
        }

        private bool isPrimeCalculation(int value)
        {
            if (value < HighestKnownPrime)
            {
                if (KnownRootPrimesList.BinarySearch(value) > -1)
                {
                    return (true);
                }
                else
                {
                    return (false);
                }
            }
            int srt = Convert.ToInt32(Math.Ceiling(Math.Sqrt(Convert.ToDouble(value))));
            bool isPrime = true;
            List<int> CheckList = KnownRootPrimesList.ToList();
            if (HighestKnownPrime + 1 < srt)
            {
                CheckList.AddRange(Enumerable.Range(HighestKnownPrime + 1, srt));
            }
            foreach(int i in CheckList)
            {
                isPrime = ((value % i) != 0);
                if(!isPrime)
                {
                    break;
                }
            }
            return (isPrime);
        }

        public bool isPrimeStandard(int value)
        {
            int srt = Convert.ToInt32(Math.Ceiling(Math.Sqrt(Convert.ToDouble(value))));
            bool isPrime = true;
            List<int> CheckList = Enumerable.Range(2, srt).ToList();
            foreach (int i in CheckList)
            {
                isPrime = ((value % i) != 0);
                if (!isPrime)
                {
                    break;
                }
            }
            return (isPrime);
        }
    }
}

Visual Studio: ContextSwitchDeadlock

You can solve this by unchecking contextswitchdeadlock from

Debug->Exceptions ... -> Expand MDA node -> uncheck -> contextswitchdeadlock

FloatingActionButton example with Support Library

I just found some issues on FAB and I want to enhance another answer.


setRippleColor issue

So, the issue will come once you set the ripple color (FAB color on pressed) programmatically through setRippleColor. But, we still have an alternative way to set it, i.e. by calling:

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
ColorStateList rippleColor = ContextCompat.getColorStateList(context, R.color.fab_ripple_color);
fab.setBackgroundTintList(rippleColor);

Your project need to has this structure:

/res/color/fab_ripple_color.xml

enter image description here

And the code from fab_ripple_color.xml is:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="@color/fab_color_pressed" />
    <item android:state_focused="true" android:color="@color/fab_color_pressed" />
    <item android:color="@color/fab_color_normal"/>
</selector>

Finally, alter your FAB slightly:

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_action_add"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    app:fabSize="normal"
    app:borderWidth="0dp"
    app:elevation="6dp"
    app:pressedTranslationZ="12dp"
    app:rippleColor="@android:color/transparent"/> <!-- set to transparent color -->

For API level 21 and higher, set margin right and bottom to 24dp:

...
android:layout_marginRight="24dp"
android:layout_marginBottom="24dp" />

FloatingActionButton design guides

As you can see on my FAB xml code above, I set:

        ...
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        app:elevation="6dp"
        app:pressedTranslationZ="12dp"
        ...
  • By setting these attributes, you don't need to set layout_marginTop and layout_marginRight again (only on pre-Lollipop). Android will place it automatically on the right corned side of the screen, which the same as normal FAB in Android Lollipop.

        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
    

Or, you can use this in CoordinatorLayout:

        android:layout_gravity="end|bottom"
  • You need to have 6dp elevation and 12dp pressedTranslationZ, according to this guide from Google.

FAB rules

Can't accept license agreement Android SDK Platform 24

It is because by default at the time of this writing , Ionic CLI tool is defaulted to

<preference name="android-targetSdkVersion" value="LATEST_SDK_VERSION"/> 

That is the reason why it complains that you did not accept license agreement , but in reality you did not install the SDK packages for that API Level yet alone accept the license.

So what you need to do is either

  1. Change Your target SDK version
  2. Install latest SDK API level from SDK Manager

Changing your SDK version

You can do it manually and even verify it by running

ionic cordova platform add android 

the file can be found at your-awesome-app/config.xml open it and add this line , since its hidden as stated above

<preference name="android-targetSdkVersion" value="24"/>

If you are not sure which API LEVEL Number you are targeting open SDK Manager and look at the API levels (Numbers) available on your machine

Installing Latest SDK Package

You can add the current SDK Packages which the CLI is showing , Which in your case it is 24

Run SDK MANAGER as Admin

Run SDK Manager as Admin

Install the SDK API Packages which you are targeting

Thats where the SDK API level are written

How did I know this? I did it this morning and that's how I solved it and now am playing Sticky Bubble on Android to relax a bit.

Happy Deploying!

Oracle JDBC ojdbc6 Jar as a Maven Dependency

mvn install:install-file 
-Dfile=C:\Users\xxxx\Downloads\lib\ojdbc6.jar 
-DgroupId=com.oracle
-DartifactId=ojdbc6 -Dversion=11.2.0 -Dpackaging=jar

to resolve the ORACLE JAR issue with the Spring Application,

Oracle JDBC ojdbc6 Jar as a Maven Dependency

    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc6</artifactId>
        <version>11.2.0</version>
    </dependency>`

Export HTML table to pdf using jspdf

We can separate out section of which we need to convert in PDF

For example, if table is in class "pdf-table-wrap"

After this, we need to call html2canvas function combined with jsPDF

following is sample code

var pdf = new jsPDF('p', 'pt', [580, 630]);
html2canvas($(".pdf-table-wrap")[0], {
    onrendered: function(canvas) {
        document.body.appendChild(canvas);
        var ctx = canvas.getContext('2d');
        var imgData = canvas.toDataURL("image/png", 1.0);
        var width = canvas.width;
        var height = canvas.clientHeight;
        pdf.addImage(imgData, 'PNG', 20, 20, (width - 10), (height));

    }
});
setTimeout(function() {
    //jsPDF code to save file
    pdf.save('sample.pdf');
}, 0);

Complete tutorial is given here http://freakyjolly.com/create-multipage-html-pdf-jspdf-html2canvas/

Suppress/ print without b' prefix for bytes in Python 3

If we take a look at the source for bytes.__repr__, it looks as if the b'' is baked into the method.

The most obvious workaround is to manually slice off the b'' from the resulting repr():

>>> x = b'\x01\x02\x03\x04'

>>> print(repr(x))
b'\x01\x02\x03\x04'

>>> print(repr(x)[2:-1])
\x01\x02\x03\x04

Custom fonts and XML layouts (Android)

You can make easily custom textview class :-

So what you need to do first, make Custom textview class which extended with AppCompatTextView.

public class CustomTextView extends AppCompatTextView {
    private int mFont = FontUtils.FONTS_NORMAL;
    boolean fontApplied;

    public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs, context);
    }

    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs, context);
    }

    public CustomTextView(Context context) {
        super(context);
        init(null, context);
    }

    protected void init(AttributeSet attrs, Context cxt) {
        if (!fontApplied) {
            if (attrs != null) {
                mFont = attrs.getAttributeIntValue(
                        "http://schemas.android.com/apk/res-auto", "Lato-Regular.ttf",
                        -1);
            }
            Typeface typeface = getTypeface();
            int typefaceStyle = Typeface.NORMAL;
            if (typeface != null) {
                typefaceStyle = typeface.getStyle();
            }
            if (mFont > FontUtils.FONTS) {
                typefaceStyle = mFont;
            }
            FontUtils.applyFont(this, typefaceStyle);
            fontApplied = true;
        }
    }
}

Now , every time Custom text view call and we will get int value from attribute int fontValue = attrs.getAttributeIntValue("http://schemas.android.com/apk/res-auto","Lato-Regular.ttf",-1).

Or

We can also get getTypeface() from view which we set in our xml (android:textStyle="bold|normal|italic"). So do what ever you want to do.

Now, we make FontUtils for set any .ttf font into our view.

public class FontUtils {

    public static final int FONTS = 1;
    public static final int FONTS_NORMAL = 2;
    public static final int FONTS_BOLD = 3;
    public static final int FONTS_BOLD1 = 4;

    private static Map<String, Typeface> TYPEFACE = new HashMap<String, Typeface>();

    static Typeface getFonts(Context context, String name) {
        Typeface typeface = TYPEFACE.get(name);
        if (typeface == null) {
            typeface = Typeface.createFromAsset(context.getAssets(), name);
            TYPEFACE.put(name, typeface);
        }
        return typeface;
    }

    public static void applyFont(TextView tv, int typefaceStyle) {

        Context cxt = tv.getContext();
        Typeface typeface;

        if(typefaceStyle == Typeface.BOLD_ITALIC) {
            typeface = FontUtils.getFonts(cxt, "FaktPro-Normal.ttf");
        }else if (typefaceStyle == Typeface.BOLD || typefaceStyle == SD_FONTS_BOLD|| typefaceStyle == FONTS_BOLD1) {
            typeface = FontUtils.getFonts(cxt, "FaktPro-SemiBold.ttf");
        } else if (typefaceStyle == Typeface.ITALIC) {
            typeface = FontUtils.getFonts(cxt, "FaktPro-Thin.ttf");
        } else {
            typeface = FontUtils.getFonts(cxt, "FaktPro-Normal.ttf");
        }
        if (typeface != null) {
            tv.setTypeface(typeface);
        }
    }
}

how to get program files x86 env variable?

Another relevant environment variable is:

%ProgramW6432%

So, on a 64-bit machine running in 32-bit (WOW64) mode:

  • echo %programfiles% ==> C:\Program Files (x86)
  • echo %programfiles(x86)% ==> C:\Program Files (x86)
  • echo %ProgramW6432% ==> C:\Program Files

From Wikipedia:

The %ProgramFiles% variable points to the Program Files directory, which stores all the installed programs of Windows and others. The default on English-language systems is "C:\Program Files". In 64-bit editions of Windows (XP, 2003, Vista), there are also %ProgramFiles(x86)%, which defaults to "C:\Program Files (x86)", and %ProgramW6432%, which defaults to "C:\Program Files". The %ProgramFiles% itself depends on whether the process requesting the environment variable is itself 32-bit or 64-bit (this is caused by Windows-on-Windows 64-bit redirection).

Reference: http://en.wikipedia.org/wiki/Environment_variable

How can I create a self-signed cert for localhost?

I would recomment Pluralsight's tool for creating self-signed-certs: http://blog.pluralsight.com/selfcert-create-a-self-signed-certificate-interactively-gui-or-programmatically-in-net

Make your cert as a .pfx and import it into IIS. And add it as a trusted root cert authority.

How can one create an overlay in css?

Here is an overlay using a pseudo-element (eg: no need to add more markup to do it)

_x000D_
_x000D_
.box {_x000D_
  background: 0 0 url(http://ianfarb.com/wp-content/uploads/2013/10/nicholas-hodag.jpg);_x000D_
  width: 300px;_x000D_
  height: 200px;_x000D_
}_x000D_
_x000D_
.box:after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background: rgba(0, 0, 0, 0.4);_x000D_
}
_x000D_
  <div class="box"></div>
_x000D_
_x000D_
_x000D_

How to get the difference between two dictionaries in Python?

This function gives you all the diffs (and what stayed the same) based on the dictionary keys only. It also highlights some nice Dict comprehension, Set operations and python 3.6 type annotations :)

from typing import Dict, Any, Tuple
def get_dict_diffs(a: Dict[str, Any], b: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any], Dict[str, Any]]:

    added_to_b_dict: Dict[str, Any] = {k: b[k] for k in set(b) - set(a)}
    removed_from_a_dict: Dict[str, Any] = {k: a[k] for k in set(a) - set(b)}
    common_dict_a: Dict[str, Any] = {k: a[k] for k in set(a) & set(b)}
    common_dict_b: Dict[str, Any] = {k: b[k] for k in set(a) & set(b)}
    return added_to_b_dict, removed_from_a_dict, common_dict_a, common_dict_b

If you want to compare the dictionary values:

values_in_b_not_a_dict = {k : b[k] for k, _ in set(b.items()) - set(a.items())}

How to save a data.frame in R?

Let us say you have a data frame you created and named "Data_output", you can simply export it to same directory by using the following syntax.

write.csv(Data_output, "output.csv", row.names = F, quote = F)

credit to Peter and Ilja, UMCG, the Netherlands

Check if checkbox is NOT checked on click - jQuery

Do it like this

if (typeof $(this).attr("checked") == "undefined" )

// To check if checkbox is checked
if( $(this).attr("checked")=="checked")

Eliminating NAs from a ggplot

Try remove_missing instead with vars = the_variable. It is very important that you set the vars argument, otherwise remove_missing will remove all rows that contain an NA in any column!! Setting na.rm = TRUE will suppress the warning message.

ggplot(data = remove_missing(MyData, na.rm = TRUE, vars = the_variable),aes(x= the_variable, fill=the_variable, na.rm = TRUE)) + 
       geom_bar(stat="bin") 

Create a .tar.bz2 file Linux

You are not indicating what to include in the archive.

Go one level outside your folder and try:

sudo tar -cvjSf folder.tar.bz2 folder

Or from the same folder try

sudo tar -cvjSf folder.tar.bz2 *

Cheers!

JavaScript CSS how to add and remove multiple CSS classes to an element

just use this

element.getAttributeNode("class").value += " antherClass";

take care about Space to avoid mix old class with new class

Share variables between files in Node.js?

Global variables are almost never a good thing (maybe an exception or two out there...). In this case, it looks like you really just want to export your "name" variable. E.g.,

// module.js
var name = "foobar";
// export it
exports.name = name;

Then, in main.js...

//main.js
// get a reference to your required module
var myModule = require('./module');

// name is a member of myModule due to the export above
var name = myModule.name;

Changing Fonts Size in Matlab Plots

Jonas's answer is good, but I had to modify it slightly to get every piece of text on the screen to change:

set(gca,'FontSize',30,'fontWeight','bold')

set(findall(gcf,'type','text'),'FontSize',30,'fontWeight','bold')

How to remove files that are listed in the .gitignore but still on the repository?

I did a very straightforward solution by manipulating the output of the .gitignore statement with sed:

cat .gitignore | sed '/^#.*/ d' | sed '/^\s*$/ d' | sed 's/^/git rm -r /' | bash

Explanation:

  1. print the .gitignore file
  2. remove all comments from the print
  3. delete all empty lines
  4. add 'git rm -r ' to the start of the line
  5. execute every line.

Can't ping a local VM from the host

Try dropping all the firewall, the one from your VM and the one from you Laptop, or add the rule in your firewall where you can ping

Force youtube embed to start in 720p

None of the above solutions seem to work if the width/height is less than the line resolution of quality you select. For example, the following doesn't work for me in Chrome:

<iframe width="720" height="480" src="//youtube.com/embed/hUezoHa1ZF4?autoplay=true&rel=0&vq=hd720" frameborder="0" allowfullscreen></iframe>

I want to show the high quality video, but not use up 1280 x 720 pixels on the webpage.

When I go to youtube itself, playing 720p video in a 720x480 window looks better than 480p at the same size. I want to play 720p in a 720x480 window (downsampled better quality). There is no good solution yet afaik.

Set windows environment variables with a batch file

@ECHO OFF

:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/


:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"

:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m

:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m

PAUSE

Display number always with 2 decimal places in <input>

If you are using Angular 2 (apparently it also works for Angular 4 too), you can use the following to round to two decimal places{{ exampleNumber | number : '1.2-2' }}, as in:

<ion-input value="{{ exampleNumber | number : '1.2-2' }}"></ion-input>

BREAKDOWN

'1.2-2' means {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}:

  • A minimum of 1 digit will be shown before decimal point
  • It will show at least 2 digits after decimal point
  • But not more than 2 digits

Credit due here and here

How can I echo a newline in a batch file?

This worked for me, no delayed expansion necessary:

@echo off
(
echo ^<html^> 
echo ^<body^>
echo Hello
echo ^</body^>
echo ^</html^>
)
pause

It writes output like this:

<html>
<body>
Hello
</body>
</html>
Press any key to continue . . .

Get counts of all tables in a schema

You have to use execute immediate (dynamic sql).

DECLARE 
v_owner varchar2(40); 
v_table_name varchar2(40); 
cursor get_tables is 
select distinct table_name,user 
from user_tables 
where lower(user) = 'schema_name'; 
begin 
open get_tables; 
loop
    fetch get_tables into v_table_name,v_owner; 
    EXIT WHEN get_tables%NOTFOUND;
    execute immediate 'INSERT INTO STATS_TABLE(TABLE_NAME,SCHEMA_NAME,RECORD_COUNT,CREATED) 
    SELECT ''' || v_table_name || ''' , ''' || v_owner ||''',COUNT(*),TO_DATE(SYSDATE,''DD-MON-YY'')     FROM ' || v_table_name; 
end loop;
CLOSE get_tables; 
END; 

Python: How to increase/reduce the fontsize of x and y tick labels?

It is simpler than I thought it would be.

To set the font size of the x-axis ticks:

x_ticks=['x tick 1','x tick 2','x tick 3']
ax.set_xticklabels(x_ticks, rotation=0, fontsize=8)

To do it for the y-axis ticks:

y_ticks=['y tick 1','y tick 2','y tick 3']
ax.set_yticklabels(y_ticks, rotation=0, fontsize=8)

The arguments rotation and fontsize can easily control what I was after.

Reference: http://matplotlib.org/api/axes_api.html

Regular expression for a hexadecimal number?

How about the following?

0[xX][0-9a-fA-F]+

Matches expression starting with a 0, following by either a lower or uppercase x, followed by one or more characters in the ranges 0-9, or a-f, or A-F

An attempt was made to access a socket in a way forbidden by its access permissions

As per https://stackoverflow.com/a/33859341/446250, having internet connection sharing enabled for my ethernet adapter ended up causing this problem for me. Disabling the sharing fixed the problem

Swift error : signal SIGABRT how to solve it

For me it wasn't an outlet. I solved the problem by going to the error And reading what it said. (Also Noob..)

This was the error:

enter image description here

And The solution was here: enter image description here

Just scroll up in the output and the error will be revealed.

How can a LEFT OUTER JOIN return more records than exist in the left table?

Table1                Table2
_______               _________
1                      2
2                      2
3                      5
4                      6

SELECT Table1.Id, Table2.Id FROM Table1 LEFT OUTER JOIN Table2 ON Table1.Id=Table2.Id

Results:

1,null
2,2
2,2
3,null
4,null

When is TCP option SO_LINGER (0) required?

For my suggestion, please read the last section: “When to use SO_LINGER with timeout 0”.

Before we come to that a little lecture about:

  • Normal TCP termination
  • TIME_WAIT
  • FIN, ACK and RST

Normal TCP termination

The normal TCP termination sequence looks like this (simplified):

We have two peers: A and B

  1. A calls close()
    • A sends FIN to B
    • A goes into FIN_WAIT_1 state
  2. B receives FIN
    • B sends ACK to A
    • B goes into CLOSE_WAIT state
  3. A receives ACK
    • A goes into FIN_WAIT_2 state
  4. B calls close()
    • B sends FIN to A
    • B goes into LAST_ACK state
  5. A receives FIN
    • A sends ACK to B
    • A goes into TIME_WAIT state
  6. B receives ACK
    • B goes to CLOSED state – i.e. is removed from the socket tables

TIME_WAIT

So the peer that initiates the termination – i.e. calls close() first – will end up in the TIME_WAIT state.

To understand why the TIME_WAIT state is our friend, please read section 2.7 in "UNIX Network Programming" third edition by Stevens et al (page 43).

However, it can be a problem with lots of sockets in TIME_WAIT state on a server as it could eventually prevent new connections from being accepted.

To work around this problem, I have seen many suggesting to set the SO_LINGER socket option with timeout 0 before calling close(). However, this is a bad solution as it causes the TCP connection to be terminated with an error.

Instead, design your application protocol so the connection termination is always initiated from the client side. If the client always knows when it has read all remaining data it can initiate the termination sequence. As an example, a browser knows from the Content-Length HTTP header when it has read all data and can initiate the close. (I know that in HTTP 1.1 it will keep it open for a while for a possible reuse, and then close it.)

If the server needs to close the connection, design the application protocol so the server asks the client to call close().

When to use SO_LINGER with timeout 0

Again, according to "UNIX Network Programming" third edition page 202-203, setting SO_LINGER with timeout 0 prior to calling close() will cause the normal termination sequence not to be initiated.

Instead, the peer setting this option and calling close() will send a RST (connection reset) which indicates an error condition and this is how it will be perceived at the other end. You will typically see errors like "Connection reset by peer".

Therefore, in the normal situation it is a really bad idea to set SO_LINGER with timeout 0 prior to calling close() – from now on called abortive close – in a server application.

However, certain situation warrants doing so anyway:

  • If the a client of your server application misbehaves (times out, returns invalid data, etc.) an abortive close makes sense to avoid being stuck in CLOSE_WAIT or ending up in the TIME_WAIT state.
  • If you must restart your server application which currently has thousands of client connections you might consider setting this socket option to avoid thousands of server sockets in TIME_WAIT (when calling close() from the server end) as this might prevent the server from getting available ports for new client connections after being restarted.
  • On page 202 in the aforementioned book it specifically says: "There are certain circumstances which warrant using this feature to send an abortive close. One example is an RS-232 terminal server, which might hang forever in CLOSE_WAIT trying to deliver data to a stuck terminal port, but would properly reset the stuck port if it got an RST to discard the pending data."

I would recommend this long article which I believe gives a very good answer to your question.

Remove an onclick listener

Perhaps setOnClickListener(null) ?

How can I stop a While loop?

def determine_period(universe_array):
    period=0
    tmp=universe_array
    while period<12:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        if numpy.array_equal(tmp,universe_array) is True:
            break 
        period+=1

    return period

How to extract an assembly from the GAC?

One other direction--just unpack the MSI file and get the goodies that way. Saves you from the eventual uninstall . . .

Converting from signed char to unsigned char and back again?

I'm not 100% sure that I understand your question, so tell me if I'm wrong.

If I got it right, you are reading jbytes that are technically signed chars, but really pixel values ranging from 0 to 255, and you're wondering how you should handle them without corrupting the values in the process.

Then, you should do the following:

  • convert jbytes to unsigned char before doing anything else, this will definetly restore the pixel values you are trying to manipulate

  • use a larger signed integer type, such as int while doing intermediate calculations, this to make sure that over- and underflows can be detected and dealt with (in particular, not casting to a signed type could force to compiler to promote every type to an unsigned type in which case you wouldn't be able to detect underflows later on)

  • when assigning back to a jbyte, you'll want to clamp your value to the 0-255 range, convert to unsigned char and then convert again to signed char: I'm not certain the first conversion is strictly necessary, but you just can't be wrong if you do both

For example:

inline int fromJByte(jbyte pixel) {
    // cast to unsigned char re-interprets values as 0-255
    // cast to int will make intermediate calculations safer
    return static_cast<int>(static_cast<unsigned char>(pixel));
}

inline jbyte fromInt(int pixel) {
    if(pixel < 0)
        pixel = 0;

    if(pixel > 255)
        pixel = 255;

    return static_cast<jbyte>(static_cast<unsigned char>(pixel));
}

jbyte in = ...
int intermediate = fromJByte(in) + 30;
jbyte out = fromInt(intermediate);

Is putting a div inside an anchor ever correct?

With HTML5 specification... It is now possible to put a block-level element inside of an inline element. So now it's perfectly appropriate to put a 'div' or 'h1' inside of an 'a' element.

Facebook user url by id

The marked answer seems outdated and it won't work.

Facebook now only gives unique ID related to app which isn't equal to userId and profileUrl and username will come out to be empty.

Doing me?fields=id,name,links is also depreciated after Graph Version 2.4

The only option now is to request for user_links permission from your developer console.

enter image description here

and the pass it in scope when doing facebook login

scope: ['user_link'] }

or by doing an api call

Why can't I make a vector of references?

By their very nature, references can only be set at the time they are created; i.e., the following two lines have very different effects:

int & A = B;   // makes A an alias for B
A = C;         // assigns value of C to B.

Futher, this is illegal:

int & D;       // must be set to a int variable.

However, when you create a vector, there is no way to assign values to it's items at creation. You are essentially just making a whole bunch of the last example.

Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)

Matthew's supremely efficient script updated to use the dm_exec_sessions DMV, replacing the deprecated sysprocesses system table:

USE [master];
GO

DECLARE @Kill VARCHAR(8000) = '';

SELECT
    @Kill = @Kill + 'kill ' + CONVERT(VARCHAR(5), session_id) + ';'
FROM
    sys.dm_exec_sessions
WHERE
    database_id = DB_ID('<YourDB>');

EXEC sys.sp_executesql @Kill;

Alternative using WHILE loop (if you want to process any other operations per execution):

USE [master];
GO

DECLARE @DatabaseID SMALLINT = DB_ID(N'<YourDB>');    
DECLARE @SQL NVARCHAR(10);

WHILE EXISTS ( SELECT
                1
               FROM
                sys.dm_exec_sessions
               WHERE
                database_id = @DatabaseID )    
    BEGIN;
        SET @SQL = (
                    SELECT TOP 1
                        N'kill ' + CAST(session_id AS NVARCHAR(5)) + ';'
                    FROM
                        sys.dm_exec_sessions
                    WHERE
                        database_id = @DatabaseID
                   );
        EXEC sys.sp_executesql @SQL;
    END;

How do you run a script on login in *nix?

Search your local system's bash man page for ^INVOCATION for information on which file is going to be read at startup.

man bash
/^INVOCATION

Also in the FILES section,

   ~/.bash_profile
          The personal initialization file, executed for login shells
   ~/.bashrc
          The individual per-interactive-shell startup file

Add your script to the proper file. Make sure the script is in the $PATH, or use the absolute path to the script file.

How to set dropdown arrow in spinner?

Copy and paste this xml to show as a Dropdown and change your Dropdown color

 <?xml version="1.0" encoding="UTF-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/back1"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_width="wrap_content"
    android:layout_height="55dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="20dp" 
    android:background="@drawable/red">

    <Spinner android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:dropDownWidth="fill_parent" 
        android:popupBackground="@drawable/textbox"
        android:spinnerMode="dropdown"
        android:background="@drawable/drop_down_large"

     />

</LinearLayout>

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="55dp"
    android:layout_alignLeft="@+id/linearLayout1"
    android:layout_alignRight="@+id/linearLayout1"
    android:layout_below="@+id/linearLayout1"
    android:layout_marginTop="25dp"
    android:background="@drawable/red"
    android:ems="10"
    android:hint="enter card number" >

    <requestFocus />
</EditText>

<LinearLayout
    android:id="@+id/linearLayout2"
    android:layout_width="wrap_content"
    android:layout_height="55dp"
    android:layout_alignLeft="@+id/editText1"
    android:layout_alignRight="@+id/editText1"
    android:layout_below="@+id/editText1"
    android:layout_marginTop="33dp"
    android:orientation="horizontal" 
    android:background="@drawable/red">

    <Spinner
        android:id="@+id/spinner3"
        android:layout_width="72dp"
        android:layout_height="wrap_content"
         android:popupBackground="@drawable/textbox"
        android:spinnerMode="dropdown"
        android:background="@drawable/drop_down_large"
         />

    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="72dp"
        android:layout_height="wrap_content" 
        android:popupBackground="@drawable/textbox"
        android:spinnerMode="dropdown"
        android:background="@drawable/drop_down_large"
        />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="22dp"
        android:layout_height="match_parent"
        android:layout_weight="0.18"
        android:ems="10"
        android:hint="enter cvv" />

</LinearLayout>

<LinearLayout
    android:id="@+id/linearLayout3"
    android:layout_width="wrap_content"
    android:layout_height="55dp"
    android:layout_alignParentLeft="true"
    android:layout_alignRight="@+id/linearLayout2"
    android:layout_below="@+id/linearLayout2"
    android:layout_marginTop="26dp"
    android:orientation="vertical"
    android:background="@drawable/red" >
</LinearLayout>

<Spinner
    android:id="@+id/spinner4"
    android:layout_width="15dp"
    android:layout_height="18dp"
    android:layout_alignBottom="@+id/linearLayout3"
    android:layout_alignLeft="@+id/linearLayout3"
    android:layout_alignRight="@+id/linearLayout3"
    android:layout_alignTop="@+id/linearLayout3"
    android:popupBackground="@drawable/textbox"
        android:spinnerMode="dropdown"
        android:background="@drawable/drop_down_large"/>

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/linearLayout3"
    android:layout_marginTop="18dp"
    android:text="Add Amount"
    android:background="@drawable/buttonsty"/>

Drag and drop elements from list into separate blocks

I wrote some test code to check JQueryUI drag/drop. The example shows how to drag an element from a container and drop it to another container.

Markup-

<div class="row">
    <div class="col-xs-3">
      <div class="panel panel-default">
        <div class="panel-heading">
          <h1 class="panel-title">Panel 1</h1>
        </div>
        <div id="container1" class="panel-body box-container">
          <div itemid="itm-1" class="btn btn-default box-item">Item 1</div>
          <div itemid="itm-2" class="btn btn-default box-item">Item 2</div>
          <div itemid="itm-3" class="btn btn-default box-item">Item 3</div>
          <div itemid="itm-4" class="btn btn-default box-item">Item 4</div>
          <div itemid="itm-5" class="btn btn-default box-item">Item 5</div>
        </div>
      </div>
    </div>
    <div class="col-xs-3">
      <div class="panel panel-default">
        <div class="panel-heading">
          <h1 class="panel-title">Panel 2</h1>
        </div>
        <div id="container2" class="panel-body box-container"></div>
      </div>
    </div>
  </div>

JQuery codes-

$(document).ready(function() {

$('.box-item').draggable({
    cursor: 'move',
    helper: "clone"
});

$("#container1").droppable({
  drop: function(event, ui) {
    var itemid = $(event.originalEvent.toElement).attr("itemid");
    $('.box-item').each(function() {
      if ($(this).attr("itemid") === itemid) {
        $(this).appendTo("#container1");
      }
    });
  }
});

$("#container2").droppable({
  drop: function(event, ui) {
    var itemid = $(event.originalEvent.toElement).attr("itemid");
    $('.box-item').each(function() {
      if ($(this).attr("itemid") === itemid) {
        $(this).appendTo("#container2");
      }
    });
  }
});

});

CSS-

.box-container {
    height: 200px;
}

.box-item {
    width: 100%;
    z-index: 1000
}

Check the plunker JQuery Drag Drop

Node.js Hostname/IP doesn't match certificate's altnames

I was getting this when streaming to ElasticSearch from a Lambda function in AWS. Smashed my head a against a wall trying to figure it out. In the end when setting the request.headers['Host'] I was adding in the https:// to the domain for ES - changing this to [es-domain-name].eu-west-1.es.amazonaws.com (without https://) worked straight away. Below is the code I used to get it working, hopefully save anyone else smashing their head against a wall...

import path from 'path';
import AWS from 'aws-sdk';

const { region, esEndpoint } = process.env;
const endpoint = new AWS.Endpoint(esEndpoint);
const httpClient = new AWS.HttpClient();
const credentials = new AWS.EnvironmentCredentials('AWS');

/**
 * Sends a request to Elasticsearch
 *
 * @param {string} httpMethod - The HTTP method, e.g. 'GET', 'PUT', 'DELETE', etc
 * @param {string} requestPath - The HTTP path (relative to the Elasticsearch domain), e.g. '.kibana'
 * @param {string} [payload] - An optional JavaScript object that will be serialized to the HTTP request body
 * @returns {Promise} Promise - object with the result of the HTTP response
 */
export function sendRequest ({ httpMethod, requestPath, payload }) {
    const request = new AWS.HttpRequest(endpoint, region);

    request.method = httpMethod;
    request.path = path.join(request.path, requestPath);
    request.body = payload;
    request.headers['Content-Type'] = 'application/json';
    request.headers['Host'] = '[es-domain-name].eu-west-1.es.amazonaws.com';
    request.headers['Content-Length'] = Buffer.byteLength(request.body);
    const signer = new AWS.Signers.V4(request, 'es');
    signer.addAuthorization(credentials, new Date());

    return new Promise((resolve, reject) => {
        httpClient.handleRequest(
            request,
            null,
            response => {
                const { statusCode, statusMessage, headers } = response;
                let body = '';
                response.on('data', chunk => {
                    body += chunk;
                });
                response.on('end', () => {
                    const data = {
                        statusCode,
                        statusMessage,
                        headers
                    };
                    if (body) {
                        data.body = JSON.parse(body);
                    }
                    resolve(data);
                });
            },
            err => {
                reject(err);
            }
        );
    });
}

How do you stop MySQL on a Mac OS install?

If you installed the MySQL 5 package with MacPorts:

sudo launchctl  unload -w /Library/LaunchDaemons/org.macports.mysql.plist 

Or

sudo launchctl  unload -w /Library/LaunchDaemons/org.macports.mysql5-devel.plist 

if you installed the mysql5-devel package.

Show datalist labels but submit the actual value

I realize this may be a bit late, but I stumbled upon this and was wondering how to handle situations with multiple identical values, but different keys (as per bigbearzhu's comment).

So I modified Stephan Muller's answer slightly:

A datalist with non-unique values:

<input list="answers" name="answer" id="answerInput">
<datalist id="answers">
  <option value="42">The answer</option>
  <option value="43">The answer</option>
  <option value="44">Another Answer</option>
</datalist>
<input type="hidden" name="answer" id="answerInput-hidden">

When the user selects an option, the browser replaces input.value with the value of the datalist option instead of the innerText.

The following code then checks for an option with that value, pushes that into the hidden field and replaces the input.value with the innerText.

document.querySelector('#answerInput').addEventListener('input', function(e) {
    var input = e.target,   
        list = input.getAttribute('list'),
        options = document.querySelectorAll('#' + list + ' option[value="'+input.value+'"]'),
        hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden');

    if (options.length > 0) {
      hiddenInput.value = input.value;
      input.value = options[0].innerText;
      }

});

As a consequence the user sees whatever the option's innerText says, but the unique id from option.value is available upon form submit. Demo jsFiddle

What’s the best way to load a JSONObject from a json text file?

With java 8 you can try this:

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class JSONUtil {

    public static JSONObject parseJSONFile(String filename) throws JSONException, IOException {
        String content = new String(Files.readAllBytes(Paths.get(filename)));
        return new JSONObject(content);
    }

    public static void main(String[] args) throws IOException, JSONException {
        String filename = "path/to/file/abc.json";
        JSONObject jsonObject = parseJSONFile(filename);

        //do anything you want with jsonObject
    }
}

Can a for loop increment/decrement by more than one?

Andrew Whitaker's answer is true, but you can use any expression for any part.
Just remember the second (middle) expression should evaluate so it can be compared to a boolean true or false.

When I use a for loop, I think of it as

for (var i = 0; i < 10; ++i) {
    /* expression */
}

as being

var i = 0;
while( i < 10 ) {
    /* expression */
    ++i;
}

Codeigniter - no input file specified

RewriteEngine, DirectoryIndex in .htaccess file of CodeIgniter apps

I just changed the .htaccess file contents and as shown in the following links answer. And tried refreshing the page (which didn't work, and couldn't find the request to my controller) it worked.

Then just because of my doubt I undone the changes I did to my .htaccess inside my public_html folder back to original .htaccess content. So it's now as follows (which is originally it was):

DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php?/$1 [L,QSA]

And now also it works.

Hint: Seems like before the Rewrite Rules haven't been clearly setup within the Server context.

My file structure is as follows:

/
|- gheapp
|    |- application
|    L- system
|
|- public_html
|    |- .htaccess
|    L- index.php

And in the index.php I have set up the following paths to the system and the application:

$system_path = '../gheapp/system';
$application_folder = '../gheapp/application';

Note: by doing so, our application source code becomes hidden to the public at first.

Please, if you guys find anything wrong with my answer, comment and re-correct me!
Hope beginners would find this answer helpful.

Thanks!

How to get sp_executesql result into a variable?

This worked for me:

DECLARE @SQL NVARCHAR(4000)

DECLARE @tbl Table (
    Id int,
    Account varchar(50),
    Amount int
) 

-- Lots of code to Create my dynamic sql statement

insert into @tbl EXEC sp_executesql @SQL

select * from @tbl

python .replace() regex

No. Regular expressions in Python are handled by the re module.

article = re.sub(r'(?is)</html>.+', '</html>', article)

In general:

text_after = re.sub(regex_search_term, regex_replacement, text_before)

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

JavaScript - get the first day of the week from current date

var dt = new Date(); // current date of week
var currentWeekDay = dt.getDay();
var lessDays = currentWeekDay == 0 ? 6 : currentWeekDay - 1;
var wkStart = new Date(new Date(dt).setDate(dt.getDate() - lessDays));
var wkEnd = new Date(new Date(wkStart).setDate(wkStart.getDate() + 6));

This will work well.

Writing sqlplus output to a file

Make sure you have the access to the directory you are trying to spool. I tried to spool to root and it did not created the file (e.g c:\test.txt). You can check where you are spooling by issuing spool command.

java.text.ParseException: Unparseable date

  • Your formatting pattern fails to match the input string, as noted by other Answers.
  • Your input format is terrible.
  • You are using troublesome old date-time classes that were supplanted years ago by the java.time classes.

ISO 8601

Instead a format such as yours, use ISO 8601 standard formats for exchanging date-time values as text.

The java.time classes use the standard ISO 8601 formats by default when parsing/generating strings.

Proper time zone name

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

Your IST could mean Iceland Standard Time, India Standard Time, Ireland Standard Time, or others. The java.time classes are left to merely guessing, as there is no logical solution to this ambiguity.

java.time

The modern approach uses the java.time classes.

Define a formatting pattern to match your input strings.

String input = "Sat Jun 01 12:53:10 IST 2013";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );

zdt.toString(): 2013-06-01T12:53:10Z[Atlantic/Reykjavik]

If your input was not intended for Iceland, you should pre-parse the string to adjust to a proper time zone name. For example, if you are certain the input was intended for India, change IST to Asia/Kolkata.

String input = "Sat Jun 01 12:53:10 IST 2013".replace( "IST" , "Asia/Kolkata" );
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );

zdt.toString(): 2013-06-01T12:53:10+05:30[Asia/Kolkata]


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Java OCR implementation

There are a variety of OCR libraries out there. However, my experience is that the major commercial implementations, ABBYY, Omnipage, and ReadIris, far outdo the open-source or other minor implementations. These commercial libraries are not primarily designed to work with Java, though of course it is possible.

Of course, if your interest is to learn the code, the open-source implementations will do the trick.

How to call a method in another class in Java?

Instead of using this in your current class setClassRoomName("aClassName"); you have to use classroom.setClassRoomName("aClassName");

You have to add the class' and at a point like

yourClassNameWhereTheMethodIs.theMethodsName();

I know it's a really late answer but if someone starts learning Java and randomly sees this post he knows what to do.

Prevent content from expanding grid items

By default, a grid item cannot be smaller than the size of its content.

Grid items have an initial size of min-width: auto and min-height: auto.

You can override this behavior by setting grid items to min-width: 0, min-height: 0 or overflow with any value other than visible.

From the spec:

6.6. Automatic Minimum Size of Grid Items

To provide a more reasonable default minimum size for grid items, this specification defines that the auto value of min-width / min-height also applies an automatic minimum size in the specified axis to grid items whose overflow is visible. (The effect is analogous to the automatic minimum size imposed on flex items.)

Here's a more detailed explanation covering flex items, but it applies to grid items, as well:

This post also covers potential problems with nested containers and known rendering differences among major browsers.


To fix your layout, make these adjustments to your code:

.month-grid {
  display: grid;
  grid-template: repeat(6, 1fr) / repeat(7, 1fr);
  background: #fff;
  grid-gap: 2px;
  min-height: 0;  /* NEW */
  min-width: 0;   /* NEW; needed for Firefox */
}

.day-item {
  padding: 10px;
  background: #DFE7E7;
  overflow: hidden;  /* NEW */
  min-width: 0;      /* NEW; needed for Firefox */
}

jsFiddle demo


1fr vs minmax(0, 1fr)

The solution above operates at the grid item level. For a container level solution, see this post:

Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

I regularly use IntelliJ, PHPStorm and WebStorm. Would love to only use IntelliJ. As pointed out by the vendor the "Open Directory" functionality not being in IntelliJ is painful.

Now for the rub part; I have tried using IntelliJ as my single IDE and have found performance to be terrible compared to the lighter weight versions. Intellisense is almost useless in IntelliJ compared to WebStorm.

How to detect Adblock on my website?

timing's answer is nice thinked but no more working, so I have updated the name of the js file to 'adsense' from 'ads' and it is working back like a charm!

Here is the code, maybe this wil help someone:

<html>
      <head>
            <script src="/adsense.js"></script>
      </head>
             <body>
                   <script>
                           if( window.adblockDetecter === undefined ){
                           // Do anithing, adblocker detected!
                           alert('Adblocker Detected!');}
                   </script>
            </body>
</html>

In the Js file put just this line: var adblockDetecter = true;

Google Maps v2 - set both my location and zoom in

Its a late answer but I think it will help. Use this method:

protected void zoomMapInitial(LatLng finalPlace, LatLng currenLoc) {
    try {
        int padding = 200; // Space (in px) between bounding box edges and view edges (applied to all four sides of the bounding box)
        LatLngBounds.Builder bc = new LatLngBounds.Builder();

        bc.include(finalPlace);
        bc.include(currenLoc);
        googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bc.build(), padding));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Use this method after loading the map. Cheers!

What is the most accurate way to retrieve a user's correct IP address in PHP?

Just another clean way:

  function validateIp($var_ip){
    $ip = trim($var_ip);

    return (!empty($ip) &&
            $ip != '::1' &&
            $ip != '127.0.0.1' &&
            filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false)
            ? $ip : false;
  }

  function getClientIp() {
    $ip = @$this->validateIp($_SERVER['HTTP_CLIENT_IP']) ?:
          @$this->validateIp($_SERVER['HTTP_X_FORWARDED_FOR']) ?:
          @$this->validateIp($_SERVER['HTTP_X_FORWARDED']) ?:
          @$this->validateIp($_SERVER['HTTP_FORWARDED_FOR']) ?:
          @$this->validateIp($_SERVER['HTTP_FORWARDED']) ?:
          @$this->validateIp($_SERVER['REMOTE_ADDR']) ?:
          'LOCAL OR UNKNOWN ACCESS';

    return $ip;
  }

Why does this code using random strings print "hello world"?

I'll just leave it here. Whoever has a lot of (CPU) time to spare, feel free to experiment :) Also, if you have mastered some fork-join-fu to make this thing burn all CPU cores (just threads are boring, right?), please share your code. I would greatly appreciate it.

public static void main(String[] args) {
    long time = System.currentTimeMillis();
    generate("stack");
    generate("over");
    generate("flow");
    generate("rulez");

    System.out.println("Took " + (System.currentTimeMillis() - time) + " ms");
}

private static void generate(String goal) {
    long[] seed = generateSeed(goal, Long.MIN_VALUE, Long.MAX_VALUE);
    System.out.println(seed[0]);
    System.out.println(randomString(seed[0], (char) seed[1]));
}

public static long[] generateSeed(String goal, long start, long finish) {
    char[] input = goal.toCharArray();
    char[] pool = new char[input.length];
    label:
    for (long seed = start; seed < finish; seed++) {
        Random random = new Random(seed);

        for (int i = 0; i < input.length; i++)
            pool[i] = (char) random.nextInt(27);

        if (random.nextInt(27) == 0) {
            int base = input[0] - pool[0];
            for (int i = 1; i < input.length; i++) {
                if (input[i] - pool[i] != base)
                    continue label;
            }
            return new long[]{seed, base};
        }

    }

    throw new NoSuchElementException("Sorry :/");
}

public static String randomString(long i, char base) {
    System.out.println("Using base: '" + base + "'");
    Random ran = new Random(i);
    StringBuilder sb = new StringBuilder();
    for (int n = 0; ; n++) {
        int k = ran.nextInt(27);
        if (k == 0)
            break;

        sb.append((char) (base + k));
    }

    return sb.toString();
}

Output:

-9223372036808280701
Using base: 'Z'
stack
-9223372036853943469
Using base: 'b'
over
-9223372036852834412
Using base: 'e'
flow
-9223372036838149518
Using base: 'd'
rulez
Took 7087 ms

UnmodifiableMap (Java Collections) vs ImmutableMap (Google)

Guava Documentation

The JDK provides Collections.unmodifiableXXX methods, but in our opinion, these can be unwieldy and verbose; unpleasant to use everywhere you want to make defensive copies unsafe: the returned collections are only truly immutable if nobody holds a reference to the original collection inefficient: the data structures still have all the overhead of mutable collections, including concurrent modification checks, extra space in hash tables, etc.

How to force Docker for a clean build of an image

There's a --no-cache option:

docker build --no-cache -t u12_core -f u12_core .

In older versions of Docker you needed to pass --no-cache=true, but this is no longer the case.

Python: how to capture image from webcam on click using OpenCV

This is a simple program to capture an image from using a default camera. Also, It can Detect a human face.

import cv2
import sys
import logging as log
import datetime as dt
from time import sleep

cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
log.basicConfig(filename='webcam.log',level=log.INFO)

video_capture = cv2.VideoCapture(0)
anterior = 0

while True:
    if not video_capture.isOpened():
        print('Unable to load camera.')
        sleep(5)
        pass

    # Capture frame-by-frame
    ret, frame = video_capture.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30)
    )

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    if anterior != len(faces):
        anterior = len(faces)
        log.info("faces: "+str(len(faces))+" at "+str(dt.datetime.now()))


    # Display the resulting frame
    cv2.imshow('Video', frame)

    if cv2.waitKey(1) & 0xFF == ord('s'): 

        check, frame = video_capture.read()
        cv2.imshow("Capturing", frame)
        cv2.imwrite(filename='saved_img.jpg', img=frame)
        video_capture.release()
        img_new = cv2.imread('saved_img.jpg', cv2.IMREAD_GRAYSCALE)
        img_new = cv2.imshow("Captured Image", img_new)
        cv2.waitKey(1650)
        print("Image Saved")
        print("Program End")
        cv2.destroyAllWindows()

        break
    elif cv2.waitKey(1) & 0xFF == ord('q'):
        print("Turning off camera.")
        video_capture.release()
        print("Camera off.")
        print("Program ended.")
        cv2.destroyAllWindows()
        break

    # Display the resulting frame
    cv2.imshow('Video', frame)

# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()

output

enter image description here

Also, You can check out my GitHub code

Get model's fields in Django

As per the django documentation 2.2 you can use:

To get all fields: Model._meta.get_fields()

To get an individual field: Model._meta.get_field('field name')

ex. Session._meta.get_field('expire_date')

iPhone UIView Animation Best Practice

let's do try and checkout For Swift 3...

UIView.transition(with: mysuperview, duration: 0.75, options:UIViewAnimationOptions.transitionFlipFromRight , animations: {
    myview.removeFromSuperview()
}, completion: nil)

Excel VBA, error 438 "object doesn't support this property or method

The Error is here

lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1

wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this

lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
          wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1

Similarly

wsPOR.Range("A2:G" & lastrow).Select

should be

wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select

Center Contents of Bootstrap row container

With Bootstrap 4, there is a css class specifically for this. The below will center row content:

<div class="row justify-content-center">
  ...inner divs and content...
</div>

See: https://v4-alpha.getbootstrap.com/layout/grid/#horizontal-alignment, for more information.

What is the correct format to use for Date/Time in an XML file

If you are manually assembling the XML string use var.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fffffffZ")); That will output the official XML Date Time format. But you don't have to worry about format if you use the built-in serialization methods.

How to install libusb in Ubuntu

Usually to use the library you need to install the dev version.

Try

sudo apt-get install libusb-1.0-0-dev

Uploading images using Node.js, Express, and Mongoose

I'll answer my own question for the first time. I found an example straight from the source. Please forgive the poor indentation. I wasn't sure how to indent properly when copying and pasting. The code comes straight from Express multipart/form-data example on GitHub.

// Expose modules in ./support for demo purposes
require.paths.unshift(__dirname + '/../../support');

/**
 * Module dependencies.
 */

var express = require('../../lib/express')
  , form = require('connect-form');

var app = express.createServer(
  // connect-form (http://github.com/visionmedia/connect-form)
  // middleware uses the formidable middleware to parse urlencoded
  // and multipart form data
  form({ keepExtensions: true })
);

app.get('/', function(req, res){
  res.send('<form method="post" enctype="multipart/form-data">'
    + '<p>Image: <input type="file" name="image" /></p>'
    + '<p><input type="submit" value="Upload" /></p>'
    + '</form>');
});

app.post('/', function(req, res, next){

  // connect-form adds the req.form object
  // we can (optionally) define onComplete, passing
  // the exception (if any) fields parsed, and files parsed
  req.form.complete(function(err, fields, files){
    if (err) {
      next(err);
    } else {
      console.log('\nuploaded %s to %s'
        ,  files.image.filename
        , files.image.path);
      res.redirect('back');
    }
  });

  // We can add listeners for several form
  // events such as "progress"
  req.form.on('progress', function(bytesReceived, bytesExpected){
    var percent = (bytesReceived / bytesExpected * 100) | 0;
    process.stdout.write('Uploading: %' + percent + '\r');
  });
});

app.listen(3000);
console.log('Express app started on port 3000');

How do I get TimeSpan in minutes given two Dates?

I would do it like this:

int totalMinutes = (int)(end - start).TotalMinutes;

Common MySQL fields and their appropriate data types

Any Table ID

Use: INT(11).

MySQL indexes will be able to parse through an int list fastest.

Anything Security

Use: BINARY(x), or BLOB(x).

You can store security tokens, etc., as hex directly in BINARY(x) or BLOB(x). To retrieve from binary-type, use SELECT HEX(field)... or SELECT ... WHERE field = UNHEX("ABCD....").

Anything Date

Use: DATETIME, DATE, or TIME.

Always use DATETIME if you need to store both date and time (instead of a pair of fields), as a DATETIME indexing is more amenable to date-comparisons in MySQL.

Anything True-False

Use: BIT(1) (MySQL 8-only.) Otherwise, use BOOLEAN(1).

BOOLEAN is actually just an alias of TINYINT(1), which actually stores 0 to 255 (not exactly a true/false, is it?).

Anything You Want to call `SUM()`, `MAX()`, or similar functions on

Use: INT(11).

VARCHAR or other types of fields won't work with the SUM(), etc., functions.

Anything Over 1,000 Characters

Use: TEXT.

Max limit is 65,535.

Anything Over 65,535 Characters

Use: MEDIUMTEXT.

Max limit is 16,777,215.

Anything Over 16,777,215 Characters

Use: LONGTEXT.

Max limit is 4,294,967,295.

FirstName, LastName

Use : VARCHAR(255).

UTF-8 characters can take up three characters per visible character, and some cultures do not distinguish firstname and lastname. Additionally, cultures may have disagreements about which name is first and which name is last. You should name these fields Person.GivenName and Person.FamilyName.

Email Address

Use : VARCHAR(256).

The definition of an e-mail path is set in RFC821 in 1982. The maximum limit of an e-mail was set by RFC2821 in 2001, and these limits were kept unchanged by RFC5321 in 2008. (See the section: 4.5.3.1. Size Limits and Minimums.) RFC3696, published 2004, mistakenly cites the email address limit as 320 characters, but this was an "info-only" RFC that explicitly "defines no standards" according to its intro, so disregard it.

Phone

Use: VARCHAR(255).

You never know when the phone number will be in the form of "1800...", or "1-800", or "1-(800)", or if it will end with "ext. 42", or "ask for susan".

ZipCode

Use: VARCHAR(10).

You'll get data like 12345 or 12345-6789. Use validation to cleanse this input.

URL

Use: VARCHAR(2000).

Official standards support URL's much longer than this, but few modern browsers support URL's over 2,000 characters. See this SO answer: What is the maximum length of a URL in different browsers?

Price

Use: DECIMAL(11,2).

It goes up to 11.

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

Yes it is true.

If you create two instance of your class

Test t1 = new Test();
Test t2 = new Test();

Then t1.foo and t2.foo both synchronize on the same static object and hence block each other.

How to check if Location Services are enabled?

This if clause easily checks if location services are available in my opinion:

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        //All location services are disabled

}

How can I listen for a click-and-hold in jQuery?

Aircoded (but tested on this fiddle)

(function($) {
    function startTrigger(e) {
        var $elem = $(this);
        $elem.data('mouseheld_timeout', setTimeout(function() {
            $elem.trigger('mouseheld');
        }, e.data));
    }

    function stopTrigger() {
        var $elem = $(this);
        clearTimeout($elem.data('mouseheld_timeout'));
    }


    var mouseheld = $.event.special.mouseheld = {
        setup: function(data) {
            // the first binding of a mouseheld event on an element will trigger this
            // lets bind our event handlers
            var $this = $(this);
            $this.bind('mousedown', +data || mouseheld.time, startTrigger);
            $this.bind('mouseleave mouseup', stopTrigger);
        },
        teardown: function() {
            var $this = $(this);
            $this.unbind('mousedown', startTrigger);
            $this.unbind('mouseleave mouseup', stopTrigger);
        },
        time: 750 // default to 750ms
    };
})(jQuery);

// usage
$("div").bind('mouseheld', function(e) {
    console.log('Held', e);
})

"401 Unauthorized" on a directory

  1. Open IIS and select site that is causing 401
  2. Select Authentication property in IIS Header
  3. Select Anonymous Authentication
  4. Right click on it, select Edit and choose Application pool identity
  5. Restart site and it should work

Difference between PACKETS and FRAMES

Packet

A packet is the unit of data that is routed between an origin and a destination on the Internet or any other packet-switched network. When any file (e-mail message, HTML file, Graphics Interchange Format file, Uniform Resource Locator request, and so forth) is sent from one place to another on the Internet, the Transmission Control Protocol (TCP) layer of TCP/IP divides the file into "chunks" of an efficient size for routing. Each of these packets is separately numbered and includes the Internet address of the destination. The individual packets for a given file may travel different routes through the Internet. When they have all arrived, they are reassembled into the original file (by the TCP layer at the receiving end).

Frame

1) In telecommunications, a frame is data that is transmitted between network points as a unit complete with addressing and necessary protocol control information. A frame is usually transmitted serial bit by bit and contains a header field and a trailer field that "frame" the data. (Some control frames contain no data.)

2) In time-division multiplexing (TDM), a frame is a complete cycle of events within the time division period.

3) In film and video recording and playback, a frame is a single image in a sequence of images that are recorded and played back.

4) In computer video display technology, a frame is the image that is sent to the display image rendering devices. It is continuously updated or refreshed from a frame buffer, a highly accessible part of video RAM.

5) In artificial intelligence (AI) applications, a frame is a set of data with information about a particular object, process, or image. An example is the iris-print visual recognition system used to identify users of certain bank automated teller machines. This system compares the frame of data for a potential user with the frames in its database of authorized users.

Make a link open a new window (not tab)

I know that its bit old Q but if u get here by searching a solution so i got a nice one via jquery

  jQuery('a[target^="_new"]').click(function() {
    var width = window.innerWidth * 0.66 ;
    // define the height in
    var height = width * window.innerHeight / window.innerWidth ;
    // Ratio the hight to the width as the user screen ratio
    window.open(this.href , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));

});

it will open all the <a target="_new"> in a new window

EDIT:

1st, I did some little changes in the original code now it open the new window perfectly followed the user screen ratio (for landscape desktops)

but, I would like to recommend you to use the following code that open the link in new tab if you in mobile (thanks to zvona answer in other question):

jQuery('a[target^="_new"]').click(function() {
    return openWindow(this.href);
}


function openWindow(url) {

    if (window.innerWidth <= 640) {
        // if width is smaller then 640px, create a temporary a elm that will open the link in new tab
        var a = document.createElement('a');
        a.setAttribute("href", url);
        a.setAttribute("target", "_blank");

        var dispatch = document.createEvent("HTMLEvents");
        dispatch.initEvent("click", true, true);

        a.dispatchEvent(dispatch);
    }
    else {
        var width = window.innerWidth * 0.66 ;
        // define the height in
        var height = width * window.innerHeight / window.innerWidth ;
        // Ratio the hight to the width as the user screen ratio
        window.open(url , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
    }
    return false;
}

Reorder HTML table rows using drag-and-drop

The jQuery UI sortable plugin provides drag-and-drop reordering. A save button can extract the IDs of each item to create a comma-delimited string of those IDs, added to a hidden textbox. The textbox is returned to the server using an async postback.

This fiddle example reorders table elements, but does not save them to a database.

The sortable plugin takes one line of code to turn any list into a sortable list. If you care to use them, it also provides CSS and images to provide a visual impact to sortable list (see the example that I linked to). Developers, however, must provide code to retrieve items in their new order. I embed unique IDs of each item in the list as an HTML attribute and then retrieve those IDs via jQuery.

For example:

// ----- code executed when the document loads
$(function() {
    wireReorderList();
});

function wireReorderList() {
    $("#reorderExampleItems").sortable();
    $("#reorderExampleItems").disableSelection();
}

function saveOrderClick() {
    // ----- Retrieve the li items inside our sortable list
    var items = $("#reorderExampleItems li");

    var linkIDs = [items.size()];
    var index = 0;

    // ----- Iterate through each li, extracting the ID embedded as an attribute
    items.each(
        function(intIndex) {
            linkIDs[index] = $(this).attr("ExampleItemID");
            index++;
        });

    $get("<%=txtExampleItemsOrder.ClientID %>").value = linkIDs.join(",");
}

How to word wrap text in HTML?

you can use this CSS

p {
  width: min-content;
  min-width: 100%;
}

What is the equivalent of Java static methods in Kotlin?

There is no static keyword in kotlin. kotlin docs recommends to use package-level functions if u want to follow DRY. Create a file with .kt extension and put your method in it.

package p
    fun m(){
    //fun body
    }

after compilation m will have a signature of public static final void

and

import p.m

?

How to make audio autoplay on chrome

As of April 2018, Chrome's autoplay policies changed:

"Chrome's autoplay policies are simple:

  • Muted autoplay is always allowed.

Autoplay with sound is allowed if:

  • User has interacted with the domain (click, tap, etc.).
  • On desktop, the user's Media Engagement Index threshold has been crossed, meaning the user has previously play video with sound.
  • On mobile, the user has added the site to his or her home screen.

Also

  • Top frames can delegate autoplay permission to their iframes to allow autoplay with sound. "

Chrome's developer site has more information, including some programming examples, which can be found here: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

How to debug (only) JavaScript in Visual Studio?

The debugger should automatically attach to the browser with Visual Studio 2012. You can use the debugger keyword to halt at a certain point in the application or use the breakpoints directly inside VS.

You can also detatch the default debugger in Visual Studio and use the Developer Tools which come pre loaded with Internet Explorer or FireBug etc.

To do this goto Visual Studio -> Debug -> Detatch All and then click Start debugging in Internet Explorer. You can then set breakpoints at this level. enter image description here

How should I set the default proxy to use default credentials?

This is the new suggested method.

WebRequest.GetSystemWebProxy();

jQuery - Detecting if a file has been selected in the file input

You should be able to attach an event handler to the onchange event of the input and have that call a function to set the text in your span.

<script type="text/javascript">
  $(function() {
     $("input:file").change(function (){
       var fileName = $(this).val();
       $(".filename").html(fileName);
     });
  });
</script>

You may want to add IDs to your input and span so you can select based on those to be specific to the elements you are concerned with and not other file inputs or spans in the DOM.

How to install pip for Python 3 on Mac OS X?

  1. brew install python3
  2. create alias in your shell profile

    • eg. alias pip3="python3 -m pip" in my .zshrc

? ~ pip3 --version

pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)

Where is adb.exe in windows 10 located?

Since you already have Android Studio installed, and require the environment variable ANDROID_HOME to be set, the easy way to do this is to add %ANDROID_HOME%\platform-tools to your path.

DataColumn Name from DataRow (not DataTable)

You need something like this:

foreach(DataColumn c in dr.Table.Columns)
{
  MessageBox.Show(c.ColumnName);
}

What is the difference/usage of homebrew, macports or other package installation tools?

Currently, Macports has many more packages (~18.6 K) than there are Homebrew formulae (~3.1K), owing to its maturity. Homebrew is slowly catching up though.

Macport packages tend to be maintained by a single person.

Macports can keep multiple versions of packages around, and you can enable or disable them to test things out. Sometimes this list can get corrupted and you have to manually edit it to get things back in order, although this is not too hard.

Both package managers will ask to be regularly updated. This can take some time.

Note: you can have both package managers on your system! It is not one or the other. Brew might complain but Macports won't.

Also, if you are dealing with python or ruby packages, use a virtual environment wherever possible.

PHP PDO with foreach and fetch

foreach over a statement is just a syntax sugar for the regular one-way fetch() loop. If you want to loop over your data more than once, select it as a regular array first

$sql = "SELECT * FROM users";
$stm = $dbh->query($sql);
// here you go:
$users = $stm->fetchAll();

foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}

Also quit that try..catch thing. Don't use it, but set the proper error reporting for PHP and PDO

Spring JPA @Query with LIKE

@Query("select b.equipSealRegisterId from EquipSealRegister b where b.sealName like %?1% and b.deleteFlag = '0'" )
    List<String>findBySeal(String sealname);

I have tried this code and it works.

unsigned int vs. size_t

In short, size_t is never negative, and it maximizes performance because it's typedef'd to be the unsigned integer type that's big enough -- but not too big -- to represent the size of the largest possible object on the target platform.

Sizes should never be negative, and indeed size_t is an unsigned type. Also, because size_t is unsigned, you can store numbers that are roughly twice as big as in the corresponding signed type, because we can use the sign bit to represent magnitude, like all the other bits in the unsigned integer. When we gain one more bit, we are multiplying the range of numbers we can represents by a factor of about two.

So, you ask, why not just use an unsigned int? It may not be able to hold big enough numbers. In an implementation where unsigned int is 32 bits, the biggest number it can represent is 4294967295. Some processors, such as the IP16L32, can copy objects larger than 4294967295 bytes.

So, you ask, why not use an unsigned long int? It exacts a performance toll on some platforms. Standard C requires that a long occupy at least 32 bits. An IP16L32 platform implements each 32-bit long as a pair of 16-bit words. Almost all 32-bit operators on these platforms require two instructions, if not more, because they work with the 32 bits in two 16-bit chunks. For example, moving a 32-bit long usually requires two machine instructions -- one to move each 16-bit chunk.

Using size_t avoids this performance toll. According to this fantastic article, "Type size_t is a typedef that's an alias for some unsigned integer type, typically unsigned int or unsigned long, but possibly even unsigned long long. Each Standard C implementation is supposed to choose the unsigned integer that's big enough--but no bigger than needed--to represent the size of the largest possible object on the target platform."

LINQ .Any VS .Exists - What's the difference?

As a continuation on Matas' answer on benchmarking.

TL/DR: Exists() and Any() are equally fast.

First off: Benchmarking using Stopwatch is not precise (see series0ne's answer on a different, but similiar, topic), but it is far more precise than DateTime.

The way to get really precise readings is by using Performance Profiling. But one way to get a sense of how the two methods' performance measure up to each other is by executing both methods loads of times and then comparing the fastest execution time of each. That way, it really doesn't matter that JITing and other noise gives us bad readings (and it does), because both executions are "equally misguiding" in a sense.

static void Main(string[] args)
    {
        Console.WriteLine("Generating list...");
        List<string> list = GenerateTestList(1000000);
        var s = string.Empty;

        Stopwatch sw;
        Stopwatch sw2;
        List<long> existsTimes = new List<long>();
        List<long> anyTimes = new List<long>();

        Console.WriteLine("Executing...");
        for (int j = 0; j < 1000; j++)
        {
            sw = Stopwatch.StartNew();
            if (!list.Exists(o => o == "0123456789012"))
            {
                sw.Stop();
                existsTimes.Add(sw.ElapsedTicks);
            }
        }

        for (int j = 0; j < 1000; j++)
        {
            sw2 = Stopwatch.StartNew();
            if (!list.Exists(o => o == "0123456789012"))
            {
                sw2.Stop();
                anyTimes.Add(sw2.ElapsedTicks);
            }
        }

        long existsFastest = existsTimes.Min();
        long anyFastest = anyTimes.Min();

        Console.WriteLine(string.Format("Fastest Exists() execution: {0} ticks\nFastest Any() execution: {1} ticks", existsFastest.ToString(), anyFastest.ToString()));
        Console.WriteLine("Benchmark finished. Press any key.");
        Console.ReadKey();
    }

    public static List<string> GenerateTestList(int count)
    {
        var list = new List<string>();
        for (int i = 0; i < count; i++)
        {
            Random r = new Random();
            int it = r.Next(0, 100);
            list.Add(new string('s', it));
        }
        return list;
    }

After executing the above code 4 times (which in turn do 1 000 Exists() and Any() on a list with 1 000 000 elements), it's not hard to see that the methods are pretty much equally fast.

Fastest Exists() execution: 57881 ticks
Fastest Any() execution: 58272 ticks

Fastest Exists() execution: 58133 ticks
Fastest Any() execution: 58063 ticks

Fastest Exists() execution: 58482 ticks
Fastest Any() execution: 58982 ticks

Fastest Exists() execution: 57121 ticks
Fastest Any() execution: 57317 ticks

There is a slight difference, but it's too small a difference to not be explained by background noise. My guess would be that if one would do 10 000 or 100 000 Exists() and Any() instead, that slight difference would disappear more or less.

Simplest two-way encryption using PHP

IMPORTANT this answer is valid only for PHP 5, in PHP 7 use built-in cryptographic functions.

Here is simple but secure enough implementation:

  • AES-256 encryption in CBC mode
  • PBKDF2 to create encryption key out of plain-text password
  • HMAC to authenticate the encrypted message.

Code and examples are here: https://stackoverflow.com/a/19445173/1387163

How do I use brew installed Python as the default Python?

Modify your $PATH, Add this in your bashrc or bash_profile:

export PATH=/usr/local/bin:/usr/local/sbin:~/bin:$PATH

more click here: Issue #89791

z-index not working with position absolute

I faced this issue a lot when using position: absolute;, I faced this issue by using position: relative in the child element. don't need to change position: absolute to relative, just need to add in the child element look into the beneath two examples:

_x000D_
_x000D_
let toggle = document.getElementById('toggle')

toggle.addEventListener("click", () => {
 toggle.classList.toggle('change');
})
_x000D_
.container {
  width: 60px;
  height: 22px;
  background: #333;
  border-radius: 20px;
  position: relative;
  cursor: pointer;

}

.change .slide {
  transform: translateX(33px);
}

.slide {
  transition: 0.5s;
  width: 20px;
  height: 20px;
  background: #fff;
  border-radius: 20px;
  margin: 2px 2px;
  z-index: 100;
}

.dot {
  width: 10px;
  height: 16px;
  background: red;
  position: absolute;
  top: 4px;
  right: 5px;
  z-index: 1;
}
_x000D_
<div class="container" id="toggle">
  <div class="slide"></div>
  <div class="dot"></div>
</div>
_x000D_
_x000D_
_x000D_

This's how it can be fixed using position relative:

_x000D_
_x000D_
let toggle = document.getElementById('toggle')

toggle.addEventListener("click", () => {
 toggle.classList.toggle('change');
})
_x000D_
.container {
  width: 60px;
  height: 22px;
  background: #333;
  border-radius: 20px;
  position: relative;
  cursor: pointer;

}

.change .slide {
  transform: translateX(33px);
}

.slide {
  transition: 0.5s;
  width: 20px;
  height: 20px;
  background: #fff;
  border-radius: 20px;
  margin: 2px 2px;
  z-index: 100;
  
  // Just add position relative;
  position: relative;
}

.dot {
  width: 10px;
  height: 16px;
  background: red;
  position: absolute;
  top: 4px;
  right: 5px;
  z-index: 1;
}
_x000D_
<div class="container" id="toggle">
  <div class="slide"></div>
  <div class="dot"></div>
</div>
_x000D_
_x000D_
_x000D_

Sandbox here

Can't bind to 'dataSource' since it isn't a known property of 'table'

  • Angular Core v6.0.2,
  • Angular Material, v6.0.2,
  • Angular CLI v6.0.0 (globally v6.1.2)

I had this issue when running ng test, so to fix it, I added to my xyz.component.spec.ts file:

import { MatTableModule } from '@angular/material';

And added it to imports section in TestBed.configureTestingModule({}):

beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ ReactiveFormsModule, HttpClientModule, RouterTestingModule, MatTableModule ],
      declarations: [ BookComponent ],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
    })
    .compileComponents();
}));

python xlrd unsupported format, or corrupt file.

Sometimes help to add ?raw=true at the end of a file path. For example:

wb = xlrd.open_workbook("Z:\\Data\\Locates\\3.8 locates.xls?raw=true")

Redraw datatables after using ajax to refresh the table content?

For users of modern DataTables (1.10 and above), all the answers and examples on this page are for the old api, not the new. I had a very hard time finding a newer example but finally did find this DT forum post (TL;DR for most folks) which led me to this concise example.

The example code worked for me after I finally noticed the $() selector syntax immediately surrounding the html string. You have to add a node not a string.

That example really is worth looking at but, in the spirit of SO, if you just want to see a snippet of code that works:

var table = $('#example').DataTable();
  table.rows.add( $(
          '<tr>'+
          '  <td>Tiger Nixon</td>'+
          '  <td>System Architect</td>'+
          '  <td>Edinburgh</td>'+
          '  <td>61</td>'+
          '  <td>2011/04/25</td>'+
          '  <td>$3,120</td>'+
          '</tr>'
  ) ).draw();

The careful reader might note that, since we are adding only one row of data, that table.row.add(...) should work as well and did for me.

Convert array of indices to 1-hot encoded numpy array

Here is a function that converts a 1-D vector to a 2-D one-hot array.

#!/usr/bin/env python
import numpy as np

def convertToOneHot(vector, num_classes=None):
    """
    Converts an input 1-D vector of integers into an output
    2-D array of one-hot vectors, where an i'th input value
    of j will set a '1' in the i'th row, j'th column of the
    output array.

    Example:
        v = np.array((1, 0, 4))
        one_hot_v = convertToOneHot(v)
        print one_hot_v

        [[0 1 0 0 0]
         [1 0 0 0 0]
         [0 0 0 0 1]]
    """

    assert isinstance(vector, np.ndarray)
    assert len(vector) > 0

    if num_classes is None:
        num_classes = np.max(vector)+1
    else:
        assert num_classes > 0
        assert num_classes >= np.max(vector)

    result = np.zeros(shape=(len(vector), num_classes))
    result[np.arange(len(vector)), vector] = 1
    return result.astype(int)

Below is some example usage:

>>> a = np.array([1, 0, 3])

>>> convertToOneHot(a)
array([[0, 1, 0, 0],
       [1, 0, 0, 0],
       [0, 0, 0, 1]])

>>> convertToOneHot(a, num_classes=10)
array([[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 0, 0, 0]])

XML shape drawable not rendering desired color

I had a similar problem and found that if you remove the size definition, it works for some reason.

Remove:

<size
    android:width="60dp"
    android:height="40dp" />

from the shape.

Let me know if this works!

PHP, MySQL error: Column count doesn't match value count at row 1

The number of column parameters in your insert query is 9, but you've only provided 8 values.

INSERT INTO dbname (id, Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')

The query should omit the "id" parameter, because it is auto-generated (or should be anyway):

INSERT INTO dbname (Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')

Determine function name from within that function (without using traceback)

I recently tried to use the above answers to access the docstring of a function from the context of that function but as the above questions were only returning the name string it did not work.

Fortunately I found a simple solution. If like me, you want to refer to the function rather than simply get the string representing the name you can apply eval() to the string of the function name.

import sys
def foo():
    """foo docstring"""
    print(eval(sys._getframe().f_code.co_name).__doc__)

How to change title of Activity in Android?

Try setTitle by itself, like this:

setTitle("Hello StackOverflow");

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Cascade will work when you delete something on table Courses. Any record on table BookCourses that has reference to table Courses will be deleted automatically.

But when you try to delete on table BookCourses only the table itself is affected and not on the Courses

follow-up question: why do you have CourseID on table Category?

Maybe you should restructure your schema into this,

CREATE TABLE Categories 
(
  Code CHAR(4) NOT NULL PRIMARY KEY,
  CategoryName VARCHAR(63) NOT NULL UNIQUE
);

CREATE TABLE Courses 
(
  CourseID INT NOT NULL PRIMARY KEY,
  BookID INT NOT NULL,
  CatCode CHAR(4) NOT NULL,
  CourseNum CHAR(3) NOT NULL,
  CourseSec CHAR(1) NOT NULL,
);

ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;

How can I create a text box for a note in markdown?

Here's a simple latex-based example.

---
header-includes:
    - \usepackage[most]{tcolorbox}
    - \definecolor{light-yellow}{rgb}{1, 0.95, 0.7}
    - \newtcolorbox{myquote}{colback=light-yellow,grow to right by=-10mm,grow to left by=-10mm, boxrule=0pt,boxsep=0pt,breakable}
    - \newcommand{\todo}[1]{\begin{myquote} \textbf{TODO:} \emph{#1} \end{myquote}}
---

blah blah

\todo{something}

blah

which results in: enter image description here

Unfortunately because this is latex, you can no-longer include markdown inside the TODO box (which is not a huge problem, usually), and it won't work when converting to formats other than PDF (e.g. html).

Using find to locate files that match one of multiple patterns

You could programmatically add more -name clauses, separated by -or:

find Documents \( -name "*.py" -or -name "*.html" \)

Or, go for a simple loop instead:

for F in Documents/*.{py,html}; do ...something with each '$F'... ; done

remove duplicates from sql union

Others have already answered your direct question, but perhaps you could simplify the query to eliminate the question (or have I missed something, and a query like the following will really produce substantially different results?):

select * 
    from calls c join users u
        on c.assigned_to = u.user_id 
        or c.requestor_id = u.user_id
    where u.dept = 4

Read a text file in R line by line

You should take care with readLines(...) and big files. Reading all lines at memory can be risky. Below is a example of how to read file and process just one line at time:

processFile = function(filepath) {
  con = file(filepath, "r")
  while ( TRUE ) {
    line = readLines(con, n = 1)
    if ( length(line) == 0 ) {
      break
    }
    print(line)
  }

  close(con)
}

Understand the risk of reading a line at memory too. Big files without line breaks can fill your memory too.

Opening PDF String in new window with javascript

var byteCharacters = atob(response.data);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
  byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var file = new Blob([byteArray], { type: 'application/pdf;base64' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);

You return a base64 string from the API or another source. You can also download it.

PHPmailer sending HTML CODE

all you need to do is just add $mail->IsHTML(true); to the code it works fine..

Print current call stack from a method in Python code

If you use python debugger, not only interactive probing of variables but you can get the call stack with the "where" command or "w".

So at the top of your program

import pdb

Then in the code where you want to see what is happening

pdb.set_trace()

and you get dropped into a prompt

How to position a div in bottom right corner of a browser?

This snippet works in IE7 at least

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Test</title>
<style>
  #foo {
    position: fixed;
    bottom: 0;
    right: 0;
  }
</style>
</head>
<body>
  <div id="foo">Hello World</div>
</body>
</html>

Why do I have to run "composer dump-autoload" command to make migrations work in laravel?

You should run:

composer dump-autoload

and if does not work you should:

re-install composer

syntax for creating a dictionary into another dictionary in python

dict1 = {}

dict1['dict2'] = {}

print dict1

>>> {'dict2': {},}

this is commonly known as nesting iterators into other iterators I think

Formatting a Date String in React Native

There is no need to include a bulky library such as Moment.js to fix such a simple issue.

The issue you are facing is not with formatting, but with parsing.

As John Shammas mentions in another answer, the Date constructor (and Date.parse) are picky about the input. Your 2016-01-04 10:34:23 may work in one JavaScript implementation, but not necessarily in the other.

According to the specification of ECMAScript 5.1, Date.parse supports (a simplification of) ISO 8601. That's good news, because your date is already very ISO 8601-like.

All you have to do is change the input format just a little. Swap the space for a T: 2016-01-04T10:34:23; and optionally add a time zone (2016-01-04T10:34:23+01:00), otherwise UTC is assumed.

Python 3 print without parenthesis

Although you need a pair of parentheses to print in Python 3, you no longer need a space after print, because it's a function. So that's only a single extra character.

If you still find typing a single pair of parentheses to be "unnecessarily time-consuming," you can do p = print and save a few characters that way. Because you can bind new references to functions but not to keywords, you can only do this print shortcut in Python 3.

Python 2:

>>> p = print
  File "<stdin>", line 1
    p = print
            ^
SyntaxError: invalid syntax

Python 3:

>>> p = print
>>> p('hello')
hello

It'll make your code less readable, but you'll save those few characters every time you print something.

How do I install Python OpenCV through Conda?

You just copy the cv2.pyd file to the C:\Users\USERNAME\Anaconda2\Lib directory.

You get the cv2.pyd file at this link (https://sourceforge.net/projects/opencvlibrary/files/).

The cv2.pyd is located at C:\Users\USERNAME\Desktop\opencv\build\python\2.7\x64.

Safest way to run BAT file from Powershell script

try running after changing file name from '-' to `_'

for eg: .\my_app\my_fle.bat

instead of .\\my-app\my-fle.bat

Or

cd my_app  
 .\my_file.bat

Insert HTML from CSS

This can be done. For example with Firefox

CSS

#hlinks {
  -moz-binding: url(stackexchange.xml#hlinks);
}

stackexchange.xml

<bindings xmlns="http://www.mozilla.org/xbl"
  xmlns:html="http://www.w3.org/1999/xhtml">
  <binding id="hlinks">
    <content>
      <children/>
      <html:a href="/privileges">privileges</html:a>
      <html:span class="lsep"> | </html:span>
      <html:a href="/users/logout">log out</html:a>
    </content>
  </binding>
</bindings>

ref 1

ref 2

Why is setTimeout(fn, 0) sometimes useful?

Both of these two top-rated answers are wrong. Check out the MDN description on the concurrency model and the event loop, and it should become clear what's going on (that MDN resource is a real gem). And simply using setTimeout can be adding unexpected problems in your code in addition to "solving" this little problem.

What's actually going on here is not that "the browser might not be quite ready yet because concurrency," or something based on "each line is an event that gets added to the back of the queue".

The jsfiddle provided by DVK indeed illustrates a problem, but his explanation for it isn't correct.

What's happening in his code is that he's first attaching an event handler to the click event on the #do button.

Then, when you actually click the button, a message is created referencing the event handler function, which gets added to the message queue. When the event loop reaches this message, it creates a frame on the stack, with the function call to the click event handler in the jsfiddle.

And this is where it gets interesting. We're so used to thinking of Javascript as being asynchronous that we're prone to overlook this tiny fact: Any frame has to be executed, in full, before the next frame can be executed. No concurrency, people.

What does this mean? It means that whenever a function is invoked from the message queue, it blocks the queue until the stack it generates has been emptied. Or, in more general terms, it blocks until the function has returned. And it blocks everything, including DOM rendering operations, scrolling, and whatnot. If you want confirmation, just try to increase the duration of the long running operation in the fiddle (e.g. run the outer loop 10 more times), and you'll notice that while it runs, you cannot scroll the page. If it runs long enough, your browser will ask you if you want to kill the process, because it's making the page unresponsive. The frame is being executed, and the event loop and message queue are stuck until it finishes.

So why this side-effect of the text not updating? Because while you have changed the value of the element in the DOM — you can console.log() its value immediately after changing it and see that it has been changed (which shows why DVK's explanation isn't correct) — the browser is waiting for the stack to deplete (the on handler function to return) and thus the message to finish, so that it can eventually get around to executing the message that has been added by the runtime as a reaction to our mutation operation, and in order to reflect that mutation in the UI.

This is because we are actually waiting for code to finish running. We haven't said "someone fetch this and then call this function with the results, thanks, and now I'm done so imma return, do whatever now," like we usually do with our event-based asynchronous Javascript. We enter a click event handler function, we update a DOM element, we call another function, the other function works for a long time and then returns, we then update the same DOM element, and then we return from the initial function, effectively emptying the stack. And then the browser can get to the next message in the queue, which might very well be a message generated by us by triggering some internal "on-DOM-mutation" type event.

The browser UI cannot (or chooses not to) update the UI until the currently executing frame has completed (the function has returned). Personally, I think this is rather by design than restriction.

Why does the setTimeout thing work then? It does so, because it effectively removes the call to the long-running function from its own frame, scheduling it to be executed later in the window context, so that it itself can return immediately and allow the message queue to process other messages. And the idea is that the UI "on update" message that has been triggered by us in Javascript when changing the text in the DOM is now ahead of the message queued for the long-running function, so that the UI update happens before we block for a long time.

Note that a) The long-running function still blocks everything when it runs, and b) you're not guaranteed that the UI update is actually ahead of it in the message queue. On my June 2018 Chrome browser, a value of 0 does not "fix" the problem the fiddle demonstrates — 10 does. I'm actually a bit stifled by this, because it seems logical to me that the UI update message should be queued up before it, since its trigger is executed before scheduling the long-running function to be run "later". But perhaps there're some optimisations in the V8 engine that may interfere, or maybe my understanding is just lacking.

Okay, so what's the problem with using setTimeout, and what's a better solution for this particular case?

First off, the problem with using setTimeout on any event handler like this, to try to alleviate another problem, is prone to mess with other code. Here's a real-life example from my work:

A colleague, in a mis-informed understanding on the event loop, tried to "thread" Javascript by having some template rendering code use setTimeout 0 for its rendering. He's no longer here to ask, but I can presume that perhaps he inserted timers to gauge the rendering speed (which would be the return immediacy of functions) and found that using this approach would make for blisteringly fast responses from that function.

First problem is obvious; you cannot thread javascript, so you win nothing here while you add obfuscation. Secondly, you have now effectively detached the rendering of a template from the stack of possible event listeners that might expect that very template to have been rendered, while it may very well not have been. The actual behaviour of that function was now non-deterministic, as was — unknowingly so — any function that would run it, or depend on it. You can make educated guesses, but you cannot properly code for its behaviour.

The "fix" when writing a new event handler that depended on its logic was to also use setTimeout 0. But, that's not a fix, it is hard to understand, and it is no fun to debug errors that are caused by code like this. Sometimes there's no problem ever, other times it concistently fails, and then again, sometimes it works and breaks sporadically, depending on the current performance of the platform and whatever else happens to going on at the time. This is why I personally would advise against using this hack (it is a hack, and we should all know that it is), unless you really know what you're doing and what the consequences are.

But what can we do instead? Well, as the referenced MDN article suggests, either split the work into multiple messages (if you can) so that other messages that are queued up may be interleaved with your work and executed while it runs, or use a web worker, which can run in tandem with your page and return results when done with its calculations.

Oh, and if you're thinking, "Well, couldn't I just put a callback in the long-running function to make it asynchronous?," then no. The callback doesn't make it asynchronous, it'll still have to run the long-running code before explicitly calling your callback.

Server.Transfer Vs. Response.Redirect

Response.Redirect() should be used when:

  • we want to redirect the request to some plain HTML pages on our server or to some other web server
  • we don't care about causing additional roundtrips to the server on each request
  • we do not need to preserve Query String and Form Variables from the original request
  • we want our users to be able to see the new redirected URL where he is redirected in his browser (and be able to bookmark it if its necessary)

Server.Transfer() should be used when:

  • we want to transfer current page request to another .aspx page on the same server
  • we want to preserve server resources and avoid the unnecessary roundtrips to the server
  • we want to preserve Query String and Form Variables (optionally)
  • we don't need to show the real URL where we redirected the request in the users Web Browser

Makefiles with source files in different directories

The VPATH option might come in handy, which tells make what directories to look in for source code. You'd still need a -I option for each include path, though. An example:

CXXFLAGS=-Ipart1/inc -Ipart2/inc -Ipart3/inc
VPATH=part1/src:part2/src:part3/src

OutputExecutable: part1api.o part2api.o part3api.o

This will automatically find the matching partXapi.cpp files in any of the VPATH specified directories and compile them. However, this is more useful when your src directory is broken into subdirectories. For what you describe, as others have said, you are probably better off with a makefile for each part, especially if each part can stand alone.

Selenium WebDriver: I want to overwrite value in field instead of appending to it with sendKeys using Java

Use this one, it is trusted solution and works well for all browsers:

protected void clearInput(WebElement webElement) {
    // isIE() - just checks is it IE or not - use your own implementation
    if (isIE() && "file".equals(webElement.getAttribute("type"))) {
        // workaround
        // if IE and input's type is file - do not try to clear it.
        // If you send:
        // - empty string - it will find file by empty path
        // - backspace char - it will process like a non-visible char
        // In both cases it will throw a bug.
        // 
        // Just replace it with new value when it is need to.
    } else {
        // if you have no StringUtils in project, check value still empty yet
        while (!StringUtils.isEmpty(webElement.getAttribute("value"))) {
            // "\u0008" - is backspace char
            webElement.sendKeys("\u0008");
        }
    }
}

If input has type="file" - do not clear it for IE. It will try to find file by empty path and will throw a bug.

More details you could find on my blog