Programs & Examples On #True type fonts

TrueType fonts are the major scalable font format designed by Apple. The TTF rendering engine can be found on many platforms including Apple's OSX, Microsoft's Windows, Linux, and inside of printers.

How can I extract embedded fonts from a PDF as valid font files?

Eventually found the FontForge Windows installer package and opened the PDF through the installed program. Worked a treat, so happy.

Using a custom (ttf) font in CSS

You need to use the css-property font-face to declare your font. Have a look at this fancy site: http://www.font-face.com/

Example:

@font-face {
  font-family: MyHelvetica;
  src: local("Helvetica Neue Bold"),
       local("HelveticaNeue-Bold"),
       url(MgOpenModernaBold.ttf);
  font-weight: bold;
}

See also: MDN @font-face

Convert or extract TTC font to TTF - how to?

You don't need any tool. Only a few clicks.

Windows 10 can handle ttc files with no problem.

You can double click the file and install it like any ttf. Then if you nead the individual ttf files you can go to C:\Windows\Fonts\Font Name and there you will findit. If you cant do this i suspect you have a corupt file.

The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

This could be an error in the web.config file.

Open up your URL in your browser, example:

http://localhost:61277/Email.svc

Check if you have a 500 Error.

HTTP Error 500.19 - Internal Server Error

Look for the error in these sections:

Config Error

Config File

Mockito: Mock private field initialization

Following code can be used to initialize mapper in REST client mock. The mapper field is private and needs to be set during unit test setup.

import org.mockito.internal.util.reflection.FieldSetter;

new FieldSetter(client, Client.class.getDeclaredField("mapper")).set(new Mapper());

Angular 2 execute script after template render

ngAfterViewInit() of AppComponent is a lifecycle callback Angular calls after the root component and it's children have been rendered and it should fit for your purpose.

See also https://angular.io/guide/lifecycle-hooks

Is there a way I can capture my iPhone screen as a video?

I used ScreenFlow to record the Simulator, and zoomed it and added static images as necessary. I then embedded the movie in an iPhone frame on my website. Turned out okay. See the Tweeps page for the result.

How to remove the Flutter debug banner?

  • If you are using Android Studio, you can find the option in the Flutter Inspector tab --> More Actions.

Android Studio

  • Or if you're using Dart DevTools, you can find the same button in the top right corner as well.

Dart DevTools

How to pass arguments within docker-compose?

This can now be done as of docker-compose v2+ as part of the build object;

docker-compose.yml

version: '2'
services:
    my_image_name:
        build:
            context: . #current dir as build context
            args:
                var1: 1
                var2: c

See the docker compose docs.

In the above example "var1" and "var2" will be sent to the build environment.

Note: any env variables (specified by using the environment block) which have the same name as args variable(s) will override that variable.

PHP CURL & HTTPS

Another option like Gavin Palmer answer is to use the .pem file but with a curl option

  1. download the last updated .pem file from https://curl.haxx.se/docs/caextract.html and save it somewhere on your server(outside the public folder)

  2. set the option in your code instead of the php.ini file.

In your code

curl_setopt($ch, CURLOPT_CAINFO, $_SERVER['DOCUMENT_ROOT'] .  "/../cacert-2017-09-20.pem");

NOTE: setting the cainfo in the php.ini like @Gavin Palmer did is better than setting it in your code like I did, because it will save a disk IO every time the function is called, I just make it like this in case you want to test the cainfo file on the fly instead of changing the php.ini while testing your function.

How to use the addr2line command in Linux?

Try adding the -f option to show the function names :

addr2line -f -e a.out 0x4005BDC

How to open a web page from my application?

I've been using this line to launch the default browser:

System.Diagnostics.Process.Start("http://www.google.com"); 

Javascript search inside a JSON object

I adapted regex to work with JSON.

First, stringify the JSON object. Then, you need to store the starts and lengths of the matched substrings. For example:

"matched".search("ch") // yields 3

For a JSON string, this works exactly the same (unless you are searching explicitly for commas and curly brackets in which case I'd recommend some prior transform of your JSON object before performing regex (i.e. think :, {, }).

Next, you need to reconstruct the JSON object. The algorithm I authored does this by detecting JSON syntax by recursively going backwards from the match index. For instance, the pseudo code might look as follows:

find the next key preceding the match index, call this theKey
then find the number of all occurrences of this key preceding theKey, call this theNumber
using the number of occurrences of all keys with same name as theKey up to position of theKey, traverse the object until keys named theKey has been discovered theNumber times
return this object called parentChain

With this information, it is possible to use regex to filter a JSON object to return the key, the value, and the parent object chain.

You can see the library and code I authored at http://json.spiritway.co/

How to change UIButton image in Swift

For anyone using Assets.xcassets and Swift 3, it'd be like this (no need for .png)

let buttonDone  = UIButton(type: .Custom)

if let image = UIImage(named: "Done") {
    self.buttonDone.setImage(image, for: .normal)
}

Android Writing Logs to text File

Use slf4android lib.
It's simple implementation of slf4j api using android java.util.logging.*.

Features:

  • logging to file out of the box
  • logging to any other destination by LoggerConfiguration.configuration().addHandlerToLogger
  • shake your device to send logs with screenshot via email
  • really small, it tooks only ~55kB

slf4android is maintained mainly by @miensol.

Read more about slf4android on our blog:

How to call a vue.js function on page load

Beware that when the mounted event is fired on a component, not all Vue components are replaced yet, so the DOM may not be final yet.

To really simulate the DOM onload event, i.e. to fire after the DOM is ready but before the page is drawn, use vm.$nextTick from inside mounted:

mounted: function () {
  this.$nextTick(function () {
    // Will be executed when the DOM is ready
  })
}

How do I declare an array variable in VBA?

Generally, you should declare variables of a specific type, rather than Variant. In this example, the test variable should be of type String.

And, because it's an array, you need to indicate that specifically when you declare the variable. There are two ways of declaring array variables:

  1. If you know the size of the array (the number of elements that it should contain) when you write the program, you can specify that number in parentheses in the declaration:

    Dim test(1) As String   'declares an array with 2 elements that holds strings
    

    This type of array is referred to as a static array, as its size is fixed, or static.

  2. If you do not know the size of the array when you write the application, you can use a dynamic array. A dynamic array is one whose size is not specified in the declaration (Dim statement), but rather is determined later during the execution of the program using the ReDim statement. For example:

    Dim test() As String
    Dim arraySize As Integer
    
    ' Code to do other things, like calculate the size required for the array
    ' ...
    arraySize = 5
    
    ReDim test(arraySize)  'size the array to the value of the arraySize variable
    

RESTful API methods; HEAD & OPTIONS

OPTIONS tells you things such as "What methods are allowed for this resource".

HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned. The availability is only a small part of it.

Using the Jersey client to do a POST operation

If you need to do a file upload, you'll need to use MediaType.MULTIPART_FORM_DATA_TYPE. Looks like MultivaluedMap cannot be used with that so here's a solution with FormDataMultiPart.

InputStream stream = getClass().getClassLoader().getResourceAsStream(fileNameToUpload);

FormDataMultiPart part = new FormDataMultiPart();
part.field("String_key", "String_value");
part.field("fileToUpload", stream, MediaType.TEXT_PLAIN_TYPE);
String response = WebResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(String.class, part);

How to write :hover condition for a:before and a:after?

Write a:hover::before instead of a::before:hover: example.

Get random sample from list while maintaining ordering of items?

random.sample implement it.

>>> random.sample([1, 2, 3, 4, 5],  3)   # Three samples without replacement
[4, 1, 5]

Ternary operators in JavaScript without an "else"

First of all, a ternary expression is not a replacement for an if/else construct - it's an equivalent to an if/else construct that returns a value. That is, an if/else clause is code, a ternary expression is an expression, meaning that it returns a value.

This means several things:

  • use ternary expressions only when you have a variable on the left side of the = that is to be assigned the return value
  • only use ternary expressions when the returned value is to be one of two values (or use nested expressions if that is fitting)
  • each part of the expression (after ? and after : ) should return a value without side effects (the expression x = true returns true as all expressions return the last value, but it also changes x without x having any effect on the returned value)

In short - the 'correct' use of a ternary expression is

var resultofexpression = conditionasboolean ? truepart: falsepart;

Instead of your example condition ? x=true : null ;, where you use a ternary expression to set the value of x, you can use this:

 condition && (x = true);

This is still an expression and might therefore not pass validation, so an even better approach would be

 void(condition && x = true);

The last one will pass validation.

But then again, if the expected value is a boolean, just use the result of the condition expression itself

var x = (condition); // var x = (foo == "bar");

UPDATE

In relation to your sample, this is probably more appropriate:

defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';

Character Limit on Instagram Usernames

Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

Install apps silently, with granted INSTALL_PACKAGES permission

Its possible to do silent install on Android 6 and above. Using the function supplied in the answer by Boris Treukhov, ignore everything else in the post, root is not required either.

Install your app as device admin, you can have full kiosk mode with silent install of updates in the background.

What does the "no version information available" error from linux dynamic linker mean?

Fwiw, I had this problem when running check_nrpe on a system that had the zenoss monitoring system installed. To add to the confusion, it worked fine as root user but not as zenoss user.

I found out that the zenoss user had an LD_LIBRARY_PATH that caused it to use zenoss libraries, which issue these warnings. Ie:

root@monitoring:$ echo $LD_LIBRARY_PATH

su - zenoss
zenoss@monitoring:/root$ echo $LD_LIBRARY_PATH
/usr/local/zenoss/python/lib:/usr/local/zenoss/mysql/lib:/usr/local/zenoss/zenoss/lib:/usr/local/zenoss/common/lib::
zenoss@monitoring:/root$ /usr/lib/nagios/plugins/check_nrpe -H 192.168.61.61 -p 6969 -c check_mq
/usr/lib/nagios/plugins/check_nrpe: /usr/local/zenoss/common/lib/libcrypto.so.0.9.8: no version information available (required by /usr/lib/libssl.so.0.9.8)
(...)
zenoss@monitoring:/root$ LD_LIBRARY_PATH= /usr/lib/nagios/plugins/check_nrpe -H 192.168.61.61 -p 6969 -c check_mq
(...)

So anyway, what I'm trying to say: check your variables like LD_LIBRARY_PATH, LD_PRELOAD etc as well.

Showing all session data at once?

For print session data you do not need to use print_r() function every time .

If you use it then it will be non-readable format.Data will be looks very dirty.

But if you use my function all you have to do is to use p()-Funtion and pass data into it. //create new file into application/cms_helper.php and load helper cms into //autoload or on controller

/*Copy Code for p function from here and paste into cms_helper.php in application/helpers folder */

   //@parram $data-array,$d-if true then die by default it is false
   //@author Your name

    function p($data,$d = false){

          echo "<pre>"; 
             print_r($data);
          echo "</pre>"; 

        if($d == TRUE){
             die();
          } 
      }

Just remember to load cms_helper into your project or controller using $this->load->helper('cms'); use bellow code into your controller or model it will works just GREAT.

 p($this->session->all_userdata()); // it will apply pre to your sesison data and other array as  well

How to run a subprocess with Python, wait for it to exit and get the full stdout as a string?

With Python 3.8 this workes for me. For instance to execute a python script within the venv:

    import subprocess
    import sys
    res = subprocess.run([
              sys.executable,            # venv3.8/bin/python
              'main.py', '--help',], 
            stdout=PIPE, 
            text=True)
    print(res.stdout)

Read CSV file column by column

You should use the excellent OpenCSV for reading and writing CSV files. To adapt your example to use the library it would look like this:

public class ParseCSV {
  public static void main(String[] args) {
    try {
      //csv file containing data
      String strFile = "C:/Users/rsaluja/CMS_Evaluation/Drupal_12_08_27.csv";
      CSVReader reader = new CSVReader(new FileReader(strFile));
      String [] nextLine;
      int lineNumber = 0;
      while ((nextLine = reader.readNext()) != null) {
        lineNumber++;
        System.out.println("Line # " + lineNumber);

        // nextLine[] is an array of values from the line
        System.out.println(nextLine[4] + "etc...");
      }
    }
  }
}

./configure : /bin/sh^M : bad interpreter

You can also do this in Kate.

  1. Open the file
  2. Open the Tools menu
  3. Expand the End Of Line submenu
  4. Select UNIX
  5. Save the file.

Eclipse 3.5 Unable to install plugins

We had tons of issues here, namely with the proxy support. We ended-up using Pulse: http://www.poweredbypulse.com/

Pulse has built-in support for a few plugin, however, you can add third-party plugin and even local jar file quite easily.

Strangely it does not always use the built-in Eclipse feature, so sometimes when Eclipse become difficult ( like in our case for the proxy business ), you can work-around it with Pulse.

Put icon inside input element in a form

I didn't want to change the background of my input text neither it will work with my SVG icon.

What i did is adding negative margin to the icon so it appear inside the input box

and adding same value padding to the input so text won't go under the icon.

<div class="search-input-container">

  <input
    type="text"
    class="search-input"
    style="padding-right : 30px;"
  />

  <img 
    src="@/assets/search-icon.svg" 
    style="margin-left: -30px;"
   />

</div>

*inline-style is for readability consider using classes

Reading RFID with Android phones

First is understanding that RFID is very generic term. NFC is subset of RFID technology. NFC is used for prox card, credit cards, tap and go payment system. Your phones can read and emulate NFC (Apple pay, Google pay, etc.), if they support NFC. NFC is very short distance and low power - which is why you see tap and go type usage.

The more common RFID are the tags you see here and there. They come in a wide ranges of styles, uses and frequency.

HF - high frequency tags are what they use for "chipping" animals - cattle, dogs, cats. Read range is about 12 inches and requires an external antenna that is powered the bigger the antenna the more power it needs and the further it can read.

UFH tags look similar to HF tags but have a read range of several feet.

Also HF tags come single read and multi read. UFH is exclusviely multi read.

Mutiread means when a reader is active, you can litterally read about 1700 tags in under 10 seconds.

But this is a function of the size of the antenna and how much power you can push through the reader.

As to the direct question about Android and RFID - the best way to go is to get an external handheld reader that connects to your mobile device via Bluetooth. Bluetooth libraries exist for all mobile devices - Android, Apple, Windows. From there its just a matter of the manufacturer documentation about how to open a socket to the reader and how to decode the serial information.

The TSL line of readers is very popular because you don't have to deal with reading bytes and all that low level serial jazz that other manufactures do. They have a nice set of commands that are easy to use to control the reader.

Other manufactures are basic in that you open a serial socket and then read the output like you would see in terminal app like PuTTY.

Testing HTML email rendering

If you don't want to use a submission service like Litmus (Litmus is the best, BTW) then you're just going to have to run Outlook 2007 to test your email.

It sounds like you want something a little more automatic (though I'm not sure why), but fortunately Outlook is easy to automate using Visual Basic for Applications (VBA).

You can write a VBA tool that runs from the command line to generate an email, load the email up in Outlook, and even capture a screenshot if you wish. (Presumably this is what the Litmus team does on the backend.)

(BTW, do not attempt to use MS Word to test mail; the renderer is similar but subtle differences in page layout can affect the rendering of your email.)

Android toolbar center title and custom font

A very quick and easy way to set a custom font is to use a custom titleTextAppearance with a fontFamily:

Add to styles.xml:

<style name="ToolbarTitle" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
    <item name="android:textSize">16sp</item>
    <item name="android:textColor">#FF202230</item>
    <item name="android:fontFamily">@font/varela_round_regular</item>
</style>

In your res folder create a font folder (Ex: varela_round_regular.ttf)

Read the official guide to find out more https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html

How do I output the difference between two specific revisions in Subversion?

See svn diff in the manual:

svn diff -r 8979:11390 http://svn.collab.net/repos/svn/trunk/fSupplierModel.php

How to insert an object in an ArrayList at a specific position

Here is the simple arraylist example for insertion at specific index

ArrayList<Integer> str=new ArrayList<Integer>();
    str.add(0);
    str.add(1);
    str.add(2);
    str.add(3); 
    //Result = [0, 1, 2, 3]
    str.add(1, 11);
    str.add(2, 12);
    //Result = [0, 11, 12, 1, 2, 3]

log4net hierarchy and logging levels

Here is some code telling about priority of all log4net levels:

TraceLevel(Level.All); //-2147483648

TraceLevel(Level.Verbose);   //  10 000
TraceLevel(Level.Finest);    //  10 000
    
TraceLevel(Level.Trace);     //  20 000
TraceLevel(Level.Finer);     //  20 000
    
TraceLevel(Level.Debug);     //  30 000
TraceLevel(Level.Fine);      //  30 000
    
TraceLevel(Level.Info);      //  40 000
TraceLevel(Level.Notice);    //  50 000
    
TraceLevel(Level.Warn);      //  60 000
TraceLevel(Level.Error);     //  70 000
TraceLevel(Level.Severe);    //  80 000
TraceLevel(Level.Critical);  //  90 000
TraceLevel(Level.Alert);     // 100 000
TraceLevel(Level.Fatal);     // 110 000
TraceLevel(Level.Emergency); // 120 000
    
TraceLevel(Level.Off); //2147483647


private static void TraceLevel(log4net.Core.Level level)
{
   Debug.WriteLine("{0} = {1}", level, level.Value);
}

Can I pass column name as input parameter in SQL stored Procedure

You can pass the column name but you cannot use it in a sql statemnt like

Select @Columnname From Table

One could build a dynamic sql string and execute it like EXEC (@SQL)

For more information see this answer on dynamic sql.

Dynamic SQL Pros and Cons

How to compare two floating point numbers in Bash?

Using bashj (https://sourceforge.net/projects/bashj/ ), a bash mutant with java support, you just write (and it IS easy to read):

#!/usr/bin/bashj

#!java
static int doubleCompare(double a,double b) {return((a>b) ? 1 : (a<b) ? -1 : 0);}

#!bashj
num1=3.17648e-22
num2=1.5
comp=j.doubleCompare($num1,$num2)
if [ $comp == 0 ] ; then echo "Equal" ; fi
if [ $comp == 1 ] ; then echo "$num1 > $num2" ; fi
if [ $comp == -1 ] ; then echo "$num2 > $num1" ; fi

Of course bashj bash/java hybridation offers much more...

How to install Guest addition in Mac OS as guest and Windows machine as host

Before you start, close VirtualBox! After those manipulations start VB as Administrator!


  1. Run CMD as Administrator
  2. Use lines below one by one:
  • cd "C:\Program Files\Oracle\Virtualbox"
  • VBoxManage setextradata “macOS_Catalina” VBoxInternal2/EfiGraphicsResolution 1920x1080

Screen Resolutions: 1280x720, 1920x1080, 2048x1080, 2560x1440, 3840x2160, 1280x800, 1280x1024, 1440x900, 1600x900

Description:

  • macOS_Catalina - insert your VB machine name.

  • 1920x1080 - put here your Screen Resolution.

Cheers!

How to create a JPA query with LEFT OUTER JOIN

Normally the ON clause comes from the mapping's join columns, but the JPA 2.1 draft allows for additional conditions in a new ON clause.

See,

http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/JPQL#ON

How to convert JSON to string?

JSON.stringify()

Convert a value to JSON, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.

How to auto-remove trailing whitespace in Eclipse?

Do following:

Preferences -> Java -> Editor -> Save Actions

enter image description here

Find text string using jQuery?

Just adding to Tony Miller's answer as this got me 90% towards what I was looking for but still didn't work. Adding .length > 0; to the end of his code got my script working.

 $(function() {
    var foundin = $('*:contains("I am a simple string")').length > 0;
 });

Are there any naming convention guidelines for REST APIs?

I don't think the camel case is the issue in that example, but I imagine a more RESTful naming convention for the above example would be:

api.service.com/helloWorld/userId/x

rather then making userId a query parameter (which is perfectly legal) my example denotes that resource in, IMO, a more RESTful way.

Arrow operator (->) usage in C

struct Node {
    int i;
    int j;
};
struct Node a, *p = &a;

Here the to access the values of i and j we can use the variable a and the pointer p as follows: a.i, (*p).i and p->i are all the same.

Here . is a "Direct Selector" and -> is an "Indirect Selector".

How to disable logging on the standard error stream in Python?

I don't know the logging module very well, but I'm using it in the way that I usually want to disable only debug (or info) messages. You can use Handler.setLevel() to set the logging level to CRITICAL or higher.

Also, you could replace sys.stderr and sys.stdout by a file open for writing. See http://docs.python.org/library/sys.html#sys.stdout. But I wouldn't recommend that.

Retrieve specific commit from a remote Git repository

This works best:

git fetch origin specific_commit
git checkout -b temp FETCH_HEAD

name "temp" whatever you want...this branch might be orphaned though

Android: java.lang.SecurityException: Permission Denial: start Intent

You have to add android:exported="true" in the manifest file in the activity you are trying to start.

From the android:exported documentation:

android:exported
Whether or not the activity can be launched by components of other applications — "true" if it can be, and "false" if not. If "false", the activity can be launched only by components of the same application or applications with the same user ID.

The default value depends on whether the activity contains intent filters. The absence of any filters means that the activity can be invoked only by specifying its exact class name. This implies that the activity is intended only for application-internal use (since others would not know the class name). So in this case, the default value is "false". On the other hand, the presence of at least one filter implies that the activity is intended for external use, so the default value is "true".

This attribute is not the only way to limit an activity's exposure to other applications. You can also use a permission to limit the external entities that can invoke the activity (see the permission attribute).

Changing button text onclick

this can be done easily with a vbs code (as i'm not so familiar with js )

<input type="button" id="btn" Value="Close" onclick="check">
<script Language="VBScript">
sub check
if btn.Value="Close" then btn.Value="Open" 
end sub
</script>

and you're done , however this changes the Name to display only and does not change the function {onclick} , i did some researches on how to do the second one and seem there isnt' something like

btn.onclick = ".."

but i figured out a way using <"span"> tag it goes like this :

<script Language="VBScript">
  Sub function1
  MsgBox "function1"
  span.InnerHTML= "<Input type=""button"" Value=""button2"" onclick=""function2"">"
  End Sub

   Sub function2
  MsgBox "function2"
  span.InnerHTML = "<Input type=""button"" Value=""button1"" onclick=""function1"">"
  End Sub
  </script>
  <body>
  <span id="span" name="span" >
  <input type="button" Value="button1" onclick="function1">
  </span>
  </body>

try it yourself , change the codes in sub function1 and sub function2, basically all you need to know to make it in jscript is the line

span.InnerHTML = "..." 

the rest is your code you wanna execute

hope this helps :D

Set a variable if undefined in JavaScript

var setVariable = (typeof localStorage.getItem('value') !== 'undefined' && localStorage.getItem('value')) || 0;

Get full path of a file with FileUpload Control

This dumps the file in your temp folder with file name, then after that you can call it and not worry about it. Because it will get deleted if it is in your temp folder for an amount of days.

string filename = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Guid.NewGuid().ToString(),".xls"));
                File.WriteAllBytes(filename, FileUploadControl.FileBytes);

How to write both h1 and h2 in the same line?

In many cases,

display:inline;

is enough.

But in some cases, you have to add following:

clear:none;

Error inflating class android.support.v7.widget.Toolbar?

I have solved this Issue by this blog:http://android-developers.blogspot.com/2014/10/appcompat-v21-material-design-for-pre.html

The problem is you use the wrong theme,you can choose theme that like Theme.AppCompat.NoActionBar, in my project,it works.

I hope to help you?

Maven2: Best practice for Enterprise Project (EAR file)

This is a good example of the maven-ear-plugin part.

You can also check the maven archetypes that are available as an example. If you just runt mvn archetype:generate you'll get a list of available archetypes. One of them is

maven-archetype-j2ee-simple

"PKIX path building failed" and "unable to find valid certification path to requested target"

You'll get this error when the certificate is newer than your Java version. Using a newer Java version will solve this.

Pytorch tensor to numpy array

Your question is very poorly worded. Your code (sort of) already does what you want. What exactly are you confused about? x.numpy() answer the original title of your question:

Pytorch tensor to numpy array

you need improve your question starting with your title.

Anyway, just in case this is useful to others. You might need to call detach for your code to work. e.g.

RuntimeError: Can't call numpy() on Variable that requires grad.

So call .detach(). Sample code:

# creating data and running through a nn and saving it

import torch
import torch.nn as nn

from pathlib import Path
from collections import OrderedDict

import numpy as np

path = Path('~/data/tmp/').expanduser()
path.mkdir(parents=True, exist_ok=True)

num_samples = 3
Din, Dout = 1, 1
lb, ub = -1, 1

x = torch.torch.distributions.Uniform(low=lb, high=ub).sample((num_samples, Din))

f = nn.Sequential(OrderedDict([
    ('f1', nn.Linear(Din,Dout)),
    ('out', nn.SELU())
]))
y = f(x)

# save data
y.numpy()
x_np, y_np = x.detach().cpu().numpy(), y.detach().cpu().numpy()
np.savez(path / 'db', x=x_np, y=y_np)

print(x_np)

cpu goes after detach. See: https://discuss.pytorch.org/t/should-it-really-be-necessary-to-do-var-detach-cpu-numpy/35489/5


Also I won't make any comments on the slicking since that is off topic and that should not be the focus of your question. See this:

Understanding slice notation

Error: Segmentation fault (core dumped)

It's worth trying faulthandler to identify the line or the library that is causing the issue as mentioned here https://stackoverflow.com/a/58825725/2160809 and in the comments by Karuhanga

faulthandler.enable()
// bad code goes here

or

$ python3 -q -X faulthandler
>>> /// bad cod goes here

How do you calculate the variance, median, and standard deviation in C++ or Java?

public class Statistics {
    double[] data;
    int size;   

    public Statistics(double[] data) {
        this.data = data;
        size = data.length;
    }   

    double getMean() {
        double sum = 0.0;
        for(double a : data)
            sum += a;
        return sum/size;
    }

    double getVariance() {
        double mean = getMean();
        double temp = 0;
        for(double a :data)
            temp += (a-mean)*(a-mean);
        return temp/(size-1);
    }

    double getStdDev() {
        return Math.sqrt(getVariance());
    }

    public double median() {
       Arrays.sort(data);
       if (data.length % 2 == 0)
          return (data[(data.length / 2) - 1] + data[data.length / 2]) / 2.0;
       return data[data.length / 2];
    }
}

Telnet is not recognized as internal or external command

You have to go to Control Panel>Programs>Turn Windows features on or off. Then, check "Telnet Client" and save the changes. You might have to wait about a few minutes before the change could take effect.

How to make <a href=""> link look like a button?

Tested with Chromium 40 and Firefox 36

<a href="url" style="text-decoration:none">
   <input type="button" value="click me!"/>
</a>

Android: Cancel Async Task

From SDK:

Cancelling a task

A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true.

After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns.

To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)

So your code is right for dialog listener:

uploadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
    public void onCancel(DialogInterface dialog) {
        myTask.cancel(true);
        //finish();
    }
});

Now, as I have mentioned earlier from SDK, you have to check whether the task is cancelled or not, for that you have to check isCancelled() inside the onPreExecute() method.

For example:

if (isCancelled()) 
    break;
else
{
   // do your work here
}

Removing Conda environment

This worked for me:

conda env remove --name tensorflow

VB.NET - If string contains "value1" or "value2"

Interestingly, this solution can break, but a workaround: Looking for my database called KeyWorks.accdb which must exist:

Run this:

Dim strDataPath As String = GetSetting("KeyWorks", "dataPath", "01", "") 'get from registry

If Not strDataPath.Contains("KeyWorks.accdb") Then....etc.

If my database is named KeyWorksBB.accdb, the If statement will find this acceptable and exit the If statement because it did indeed find KeyWorks and accdb.

If I surround the If statement qualifier with single quotes like 'KeyWorks.accdb', it now looks for all the consecutive characters in order and would enter the If block because it did not match.

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

What is the C# version of VB.net's InputDialog?

There isn't one. If you really wanted to use the VB InputBox in C# you can. Just add reference to Microsoft.VisualBasic.dll and you'll find it there.

But I would suggest to not use it. It is ugly and outdated IMO.

MVC 4 - Return error message from Controller - Show in View

Thanks for all the replies.

I was able to solve this by doing the following:

CONTROLLER:

[HttpPost]       
public ActionResult form_edit(FormModels model)
{
  model.error_msg = model.update_content(model);
  return RedirectToAction("Form_edit", "Form", model);
}

public ActionResult form_edit(FormModels model, string searchString,string id)
{
  string test = model.selectedvalue;
  var bal = new FormModels();
  bal.Countries = bal.get_contentdetails(searchString);
  bal.selectedvalue = id;
  bal.dd_text = "content_name";
  bal.dd_value = "content_id";

  test = model.error_msg;
  ViewBag.head = "Heading";

  if (model.error_msg != null)
  {
    ModelState.AddModelError("error_msg", test);
  }

  model.error_msg = "";
  return View(bal);
}   

VIEW:

@using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
  <table>
    <tr>
      <td>
        @ViewBag.error
        @Html.ValidationMessage("error_msg")
      </td>
    </tr>
    <tr>
      <th>
        @Html.DisplayNameFor(model => model.content_name)
        @Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
      </th>
    </tr>
  </table>
}

Turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server

Define a behavior in your .config file:

<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="debug">
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    ...
  </system.serviceModel>
</configuration>

Then apply the behavior to your service along these lines:

<configuration>
  <system.serviceModel>
    ...
    <services>
      <service name="MyServiceName" behaviorConfiguration="debug" />
    </services>
  </system.serviceModel>
</configuration>

You can also set it programmatically. See this question.

How to resolve git status "Unmerged paths:"?

Another way of dealing with this situation if your files ARE already checked in, and your files have been merged (but not committed, so the merge conflicts are inserted into the file) is to run:

git reset

This will switch to HEAD, and tell git to forget any merge conflicts, and leave the working directory as is. Then you can edit the files in question (search for the "Updated upstream" notices). Once you've dealt with the conflicts, you can run

git add -p

which will allow you to interactively select which changes you want to add to the index. Once the index looks good (git diff --cached), you can commit, and then

git reset --hard

to destroy all the unwanted changes in your working directory.

Get name of current class?

I think, it should be like this:

    class foo():
        input = get_input(__qualname__)

URL Encoding using C#

You should encode only the user name or other part of the URL that could be invalid. URL encoding a URL can lead to problems since something like this:

string url = HttpUtility.UrlEncode("http://www.google.com/search?q=Example");

Will yield

http%3a%2f%2fwww.google.com%2fsearch%3fq%3dExample

This is obviously not going to work well. Instead, you should encode ONLY the value of the key/value pair in the query string, like this:

string url = "http://www.google.com/search?q=" + HttpUtility.UrlEncode("Example");

Hopefully that helps. Also, as teedyay mentioned, you'll still need to make sure illegal file-name characters are removed or else the file system won't like the path.

Modifying a subset of rows in a pandas dataframe

Starting from pandas 0.20 ix is deprecated. The right way is to use df.loc

here is a working example

>>> import pandas as pd 
>>> import numpy as np 
>>> df = pd.DataFrame({"A":[0,1,0], "B":[2,0,5]}, columns=list('AB'))
>>> df.loc[df.A == 0, 'B'] = np.nan
>>> df
   A   B
0  0 NaN
1  1   0
2  0 NaN
>>> 

Explanation:

As explained in the doc here, .loc is primarily label based, but may also be used with a boolean array.

So, what we are doing above is applying df.loc[row_index, column_index] by:

  • Exploiting the fact that loc can take a boolean array as a mask that tells pandas which subset of rows we want to change in row_index
  • Exploiting the fact loc is also label based to select the column using the label 'B' in the column_index

We can use logical, condition or any operation that returns a series of booleans to construct the array of booleans. In the above example, we want any rows that contain a 0, for that we can use df.A == 0, as you can see in the example below, this returns a series of booleans.

>>> df = pd.DataFrame({"A":[0,1,0], "B":[2,0,5]}, columns=list('AB'))
>>> df 
   A  B
0  0  2
1  1  0
2  0  5
>>> df.A == 0 
0     True
1    False
2     True
Name: A, dtype: bool
>>> 

Then, we use the above array of booleans to select and modify the necessary rows:

>>> df.loc[df.A == 0, 'B'] = np.nan
>>> df
   A   B
0  0 NaN
1  1   0
2  0 NaN

For more information check the advanced indexing documentation here.

How to trim whitespace from a Bash variable?

I've always done it with sed

  var=`hg st -R "$path" | sed -e 's/  *$//'`

If there is a more elegant solution, I hope somebody posts it.

Vertical Menu in Bootstrap

here is vertical menu base on Bootstrap http://www.okvee.net/articles/okvee-bootstrap-sidebar-menu it is also support responsive design.

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

Change your .\SQLEXPRESS,and add your SQL express name only and it works for me

 <add name="BlogDbContext" connectionString="data source=your name here; initial catalog=CodeFirstDemo; integrated security=True" providerName="System.Data.SqlClient"/>

invalid operands of types int and double to binary 'operator%'

Because % is only defined for integer types. That's the modulus operator.

5.6.2 of the standard:

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

As Oli pointed out, you can use fmod(). Don't forget to include math.h.

Regex number between 1 and 100

between 0 and 100

/^(\d{1,2}|100)$/

or between 1 and 100

/^([1-9]{1,2}|100)$/

React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

Sometime you API backend could not respect the contract, and send plain text (ie. Proxy error: Could not proxy request ..., or <html><body>NOT FOUND</body></html>).

In this case, you will need to handle both cases: 1) a valid json response error, or 2) text payload as fallback (when response payload is not a valid json).

I would suggest this to handle both cases:

  // parse response as json, or else as txt
  static consumeResponseBodyAs(response, jsonConsumer, txtConsumer) {
    (async () => {
      var responseString = await response.text();
      try{
        if (responseString && typeof responseString === "string"){
         var responseParsed = JSON.parse(responseString);
         if (Api.debug) {
            console.log("RESPONSE(Json)", responseParsed);
         }
         return jsonConsumer(responseParsed);
        }
      } catch(error) {
        // text is not a valid json so we will consume as text
      }
      if (Api.debug) {
        console.log("RESPONSE(Txt)", responseString);
      }
      return txtConsumer(responseString);
    })();
  }

then it become more easy to tune the rest handler:

class Api {
  static debug = true;

  static contribute(entryToAdd) {
    return new Promise((resolve, reject) => {
      fetch('/api/contributions',
        { method: 'POST',
          headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
          body: JSON.stringify(entryToAdd) })
      .catch(reject);
      .then(response => Api.consumeResponseBodyAs(response,
          (json) => {
            if (!response.ok) {
              // valid json: reject will use error.details or error.message or http status
              reject((json && json.details) || (json && json.message) || response.status);
            } else {
              resolve(json);
            }
          },
          (txt) => reject(txt)// not json: reject with text payload
        )
      );
    });
  }

Check if key exists in JSON object using jQuery

No need of JQuery simply you can do

if(yourObject['email']){
 // what if this property exists.
}

as with any value for email will return you true, if there is no such property or that property value is null or undefined will result to false

How can I convert String to Int?

While I agree on using the TryParse method, a lot of people dislike the use of out parameter (myself included). With tuple support having been added to C#, an alternative is to create an extension method that will limit the number of times you use out to a single instance:

public static class StringExtensions
{
    public static (int result, bool canParse) TryParse(this string s)
    {
        int res;
        var valid = int.TryParse(s, out res);
        return (result: res, canParse: valid);
    }
}

(Source: C# how to convert a string to int)

How do I get the current date in Cocoa

+ (NSString *)displayCurrentTimeWithAMPM 
{
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setDateFormat:@"h:mm aa"];

    NSString *dateTime = [NSString stringWithFormat:@"%@",[outputFormatter stringFromDate:[NSDate date]]];

    return dateTime;
}

return 3:33 AM

How to get value by class name in JavaScript or jquery?

Try this:

$(document).ready(function(){
    var yourArray = [];
    $("span.HOEnZb").find("div").each(function(){
        if(($.trim($(this).text()).length>0)){
         yourArray.push($(this).text());
        }
    });
});

DEMO

Writing to a new file if it doesn't exist, and appending to a file if it does

Just open it in 'a' mode:

a   Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file.

with open(filename, 'a') as f:
    f.write(...)

To see whether you're writing to a new file, check the stream position. If it's zero, either the file was empty or it is a new file.

with open('somefile.txt', 'a') as f:
    if f.tell() == 0:
        print('a new file or the file was empty')
        f.write('The header\n')
    else:
        print('file existed, appending')
    f.write('Some data\n')

If you're still using Python 2, to work around the bug, either add f.seek(0, os.SEEK_END) right after open or use io.open instead.

What is the default Precision and Scale for a Number in Oracle?

Oracle stores numbers in the following way: 1 byte for power, 1 byte for the first significand digit (that is one before the separator), the rest for the other digits.

By digits here Oracle means centesimal digits (i. e. base 100)

SQL> INSERT INTO t_numtest VALUES (LPAD('9', 125, '9'))
  2  /

1 row inserted

SQL> INSERT INTO t_numtest VALUES (LPAD('7', 125, '7'))
  2  /

1 row inserted

SQL> INSERT INTO t_numtest VALUES (LPAD('9', 126, '9'))
  2  /

INSERT INTO t_numtest VALUES (LPAD('9', 126, '9'))

ORA-01426: numeric overflow

SQL> SELECT DUMP(num) FROM t_numtest;

DUMP(NUM)
--------------------------------------------------------------------------------
Typ=2 Len=2: 255,11
Typ=2 Len=21: 255,8,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,79

As we can see, the maximal number here is 7.(7) * 10^124, and he have 19 centesimal digits for precision, or 38 decimal digits.

jQuery's jquery-1.10.2.min.map is triggering a 404 (Not Found)

After following the instructions in the other answers, I needed to strip the version from the map file for this to work for me.

Example: Rename

jquery-1.9.1.min.map

to

jquery.min.map

Creating a UICollectionView programmatically

colection view exam

    #import "CollectionViewController.h"
#import "BuyViewController.h"
#import "CollectionViewCell.h"

@interface CollectionViewController ()
{
    NSArray *mobiles;
    NSArray  *costumes;
    NSArray *shoes;
    NSInteger selectpath;
    NSArray *mobilerate;
    NSArray *costumerate;
    NSArray *shoerate;
}
@end

@implementation CollectionViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = self.receivename;
    mobiles = [[NSArray alloc]initWithObjects:@"7.jpg",@"6.jpg",@"5.jpg", nil];
    costumes = [[NSArray alloc]initWithObjects:@"shirt.jpg",@"costume2.jpg",@"costume1.jpg", nil];
    shoes = [[NSArray alloc]initWithObjects:@"shoe.jpg",@"shoe1.jpg",@"shoe2.jpg", nil];
    mobilerate = [[NSArray alloc]initWithObjects:@"10000",@"11000",@"13000",nil];
    costumerate = [[NSArray alloc]initWithObjects:@"699",@"999",@"899", nil];
    shoerate = [[NSArray alloc]initWithObjects:@"599",@"499",@"300", nil];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 3;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellId = @"cell";
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];

    UIImageView *collectionImg = (UIImageView *)[cell viewWithTag:100];

    if ([self.receivename isEqualToString:@"Mobiles"])
    {
        collectionImg.image = [UIImage imageNamed:[mobiles objectAtIndex:indexPath.row]];
    }
    else if ([self.receivename isEqualToString:@"Costumes"])
    {
        collectionImg.image = [UIImage imageNamed:[costumes objectAtIndex:indexPath.row]];
    }
    else
    {
        collectionImg.image = [UIImage imageNamed:[shoes objectAtIndex:indexPath.row]];
    }
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{
    selectpath = indexPath.row;
    [self performSegueWithIdentifier:@"buynow" sender:self];
}

    // In a storyboard-based application, you will often want to do a little
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"buynow"])
    {
        BuyViewController *obj = segue.destinationViewController;
        if ([self.receivename isEqualToString:@"Mobiles"])
        {
            obj.reciveimg = [mobiles objectAtIndex:selectpath];
            obj.labelrecive = [mobilerate objectAtIndex:selectpath];

        }
        else if ([self.receivename isEqualToString:@"Costumes"])
        {
            obj.reciveimg = [costumes objectAtIndex:selectpath];
            obj.labelrecive = [costumerate objectAtIndex:selectpath];
        }
        else
        {
            obj.reciveimg = [shoes objectAtIndex:selectpath];
            obj.labelrecive = [shoerate objectAtIndex:selectpath];
        }
        //     Get the new view controller using [segue destinationViewController].
        //     Pass the selected object to the new view controller.
    }
}

@end

.h file

@interface CollectionViewController :
UIViewController<UICollectionViewDelegate,UICollectionViewDataSource>
@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong,nonatomic) NSString *receiveimg;
@property (strong,nonatomic) NSString *receivecostume;
@property (strong,nonatomic)NSString *receivename;

@end

What's the fastest way of checking if a point is inside a polygon in python

You can consider shapely:

from shapely.geometry import Point
from shapely.geometry.polygon import Polygon

point = Point(0.5, 0.5)
polygon = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])
print(polygon.contains(point))

From the methods you've mentioned I've only used the second, path.contains_points, and it works fine. In any case depending on the precision you need for your test I would suggest creating a numpy bool grid with all nodes inside the polygon to be True (False if not). If you are going to make a test for a lot of points this might be faster (although notice this relies you are making a test within a "pixel" tolerance):

from matplotlib import path
import matplotlib.pyplot as plt
import numpy as np

first = -3
size  = (3-first)/100
xv,yv = np.meshgrid(np.linspace(-3,3,100),np.linspace(-3,3,100))
p = path.Path([(0,0), (0, 1), (1, 1), (1, 0)])  # square with legs length 1 and bottom left corner at the origin
flags = p.contains_points(np.hstack((xv.flatten()[:,np.newaxis],yv.flatten()[:,np.newaxis])))
grid = np.zeros((101,101),dtype='bool')
grid[((xv.flatten()-first)/size).astype('int'),((yv.flatten()-first)/size).astype('int')] = flags

xi,yi = np.random.randint(-300,300,100)/100,np.random.randint(-300,300,100)/100
vflag = grid[((xi-first)/size).astype('int'),((yi-first)/size).astype('int')]
plt.imshow(grid.T,origin='lower',interpolation='nearest',cmap='binary')
plt.scatter(((xi-first)/size).astype('int'),((yi-first)/size).astype('int'),c=vflag,cmap='Greens',s=90)
plt.show()

, the results is this:

point inside polygon within pixel tolerance

Socket.IO handling disconnect event

You can also, if you like use socket id to manage your player list like this.

io.on('connection', function(socket){
  socket.on('disconnect', function() {
    console.log("disconnect")
    for(var i = 0; i < onlineplayers.length; i++ ){
      if(onlineplayers[i].socket === socket.id){
        console.log(onlineplayers[i].code + " just disconnected")
        onlineplayers.splice(i, 1)
      }
    }
    io.emit('players', onlineplayers)
  })

  socket.on('lobby_join', function(player) {
    if(player.available === false) return
    var exists = false
    for(var i = 0; i < onlineplayers.length; i++ ){
      if(onlineplayers[i].code === player.code){
        exists = true
      }
    }
    if(exists === false){
      onlineplayers.push({
        code: player.code,
        socket:socket.id
      })
    }
    io.emit('players', onlineplayers)
  })

  socket.on('lobby_leave', function(player) {
    var exists = false
    for(var i = 0; i < onlineplayers.length; i++ ){
      if(onlineplayers[i].code === player.code){
        onlineplayers.splice(i, 1)
      }
    }
    io.emit('players', onlineplayers)
  })
})

Java - using System.getProperty("user.dir") to get the home directory

way of getting home directory of current user is

String currentUsersHomeDir = System.getProperty("user.home");

and to append path separator

String otherFolder = currentUsersHomeDir + File.separator + "other";

File.separator

The system-dependent default name-separator character, represented as a string for convenience. This string contains a single character, namely separatorChar.

How to make an embedded video not autoplay

I had the same problem and came across this post. Nothing worked. After randomly playing around, I found that <embed ........ play="false"> stopped it from playing automatically. I now have the problem that I can't get a controller to appear, so can't start the movie! :S

Replace all non-alphanumeric characters in a string

Regex to the rescue!

import re

s = re.sub('[^0-9a-zA-Z]+', '*', s)

Example:

>>> re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld')
'h*ell*o*w*orld'

Conda environments not showing up in Jupyter Notebook

First you need to activate your environment .

pip install ipykernel

Next you can add your virtual environment to Jupyter by typing:

python -m ipykernel install --name = my_env

JavaScript and Threads

With the HTML5 "side-specs" no need to hack javascript anymore with setTimeout(), setInterval(), etc.

HTML5 & Friends introduces the javascript Web Workers specification. It is an API for running scripts asynchronously and independently.

Links to the specification and a tutorial.

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

sudo apt-get -y install python-software-properties && \
sudo apt-get -y install software-properties-common && \
sudo apt-get -y install gcc make build-essential libssl-dev libffi-dev python-dev

You need the libssl-dev and libffi-dev if especially you are trying to install python's cryptography libraries or python libs that depend on it(eg ansible)

JavaScript: changing the value of onclick with or without jQuery

One gotcha with Jquery is that the click function do not acknowledge the hand coded onclick from the html.

So, you pretty much have to choose. Set up all your handlers in the init function or all of them in html.

The click event in JQuery is the click function $("myelt").click (function ....).

ReferenceError: fetch is not defined

It seems fetch support URL scheme with "http" or "https" for CORS request.

Install node fetch library npm install node-fetch, read the file and parse to json.

const fs = require('fs')
const readJson = filename => {
  return new Promise((resolve, reject) => {
    if (filename.toLowerCase().endsWith(".json")) {
      fs.readFile(filename, (err, data) => {
        if (err) {
          reject(err)
          return
        }
        resolve(JSON.parse(data))
      })
    }
    else {
      reject(new Error("Invalid filetype, <*.json> required."))
      return
    }
  })
}

// usage
const filename = "../data.json"
readJson(filename).then(data => console.log(data)).catch(err => console.log(err.message))

Multi-line strings in PHP

Not sure how it stacks up performance-wise, but for places where it doesn't really matter, I like this format because I can be sure it is using \r\n (CRLF) and not whatever format my PHP file happens to be saved in.

$text="line1\r\n" .
      "line2\r\n" .
      "line3\r\n";

It also lets me indent however I want.

Disabling the button after once click

If when you set disabled="disabled" immediately after the user clicks the button, and the form doesn't submit because of that, you could try two things:

//First choice [given myForm = your form]:
myInputButton.disabled = "disabled";
myForm.submit()

//Second choice:
setTimeout(disableFunction, 1);  
//so the form will submit and then almost instantly, the button will be disabled  

Although I honestly bet there will be a better way to do this, than that.

Conversion hex string into ascii in bash command line

This worked for me.

$ echo 54657374696e672031203220330 | xxd -r -p
Testing 1 2 3$

-r tells it to convert hex to ascii as opposed to its normal mode of doing the opposite

-p tells it to use a plain format.

Accessing constructor of an anonymous class

That is not possible, but you can add an anonymous initializer like this:

final int anInt = ...;
Object a = new Class1()
{
  {
    System.out.println(anInt);
  }

  void someNewMethod() {
  }
};

Don't forget final on declarations of local variables or parameters used by the anonymous class, as i did it for anInt.

Python - PIP install trouble shooting - PermissionError: [WinError 5] Access is denied

Even you run from Administrator, it may not solve the issue if the pip is installed inside another userspace. This is because Administrator doesn't own another's userspace directory, thus he can't see (go inside) the inside of the directory that is owned by somebody. Below is an exact solution.

python -m pip install -U pip --user //In Windows 

Note: You should provide --user option

pip install -U pip --user //Linux, and MacOS

How to write DataFrame to postgres table?

For Python 2.7 and Pandas 0.24.2 and using Psycopg2

Psycopg2 Connection Module

def dbConnect (db_parm, username_parm, host_parm, pw_parm):
    # Parse in connection information
    credentials = {'host': host_parm, 'database': db_parm, 'user': username_parm, 'password': pw_parm}
    conn = psycopg2.connect(**credentials)
    conn.autocommit = True  # auto-commit each entry to the database
    conn.cursor_factory = RealDictCursor
    cur = conn.cursor()
    print ("Connected Successfully to DB: " + str(db_parm) + "@" + str(host_parm))
    return conn, cur

Connect to the database

conn, cur = dbConnect(databaseName, dbUser, dbHost, dbPwd)

Assuming dataframe to be present already as df

output = io.BytesIO() # For Python3 use StringIO
df.to_csv(output, sep='\t', header=True, index=False)
output.seek(0) # Required for rewinding the String object
copy_query = "COPY mem_info FROM STDOUT csv DELIMITER '\t' NULL ''  ESCAPE '\\' HEADER "  # Replace your table name in place of mem_info
cur.copy_expert(copy_query, output)
conn.commit()

python numpy machine epsilon

Another easy way to get epsilon is:

In [1]: 7./3 - 4./3 -1
Out[1]: 2.220446049250313e-16

How do I set vertical space between list items?

HTML

<ul>
   <li>A</li>
   <li>B</li>
   <li>C</li>
   <li>D</li>
   <li>E</li>
</ul>

CSS

li:not(:last-child) {
    margin-bottom: 5px;
}

EDIT: If you don't use the special case for the last li element your list will have a small spacing afterwards which you can see here: http://jsfiddle.net/wQYw7/

Now compare that with my solution: http://jsfiddle.net/wQYw7/1/

Sure this doesn't work in older browsers but you can easily use js extensions which will enable this for older browsers.

How to create a stacked bar chart for my DataFrame using seaborn?

You could use pandas plot as @Bharath suggest:

import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)

Output:

enter image description here

Updated:

from matplotlib.colors import ListedColormap df.set_index('App')\ .reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\ .T.plot(kind='bar', stacked=True, colormap=ListedColormap(sns.color_palette("GnBu", 10)), figsize=(12,6))

Updated Pandas 0.21.0+ reindex_axis is deprecated, use reindex

from matplotlib.colors import ListedColormap

df.set_index('App')\
  .reindex(df.set_index('App').sum().sort_values().index, axis=1)\
  .T.plot(kind='bar', stacked=True,
          colormap=ListedColormap(sns.color_palette("GnBu", 10)), 
          figsize=(12,6))

Output:

enter image description here

How to set different colors in HTML in one statement?

Use the span tag

<style>
    .redText
    {
        color:red;
    }
    .blackText
    {
        color:black;
        font-weight:bold;
    }
</style>

<span class="redText">My Name is:</span>&nbsp;<span class="blackText">Tintincute</span>

It's also a good idea to avoid inline styling. Use a custom CSS class instead.

How can I get the current user directory?

May be this will be a good solution: taking in account whether this is Vista/Win7 or XP and without using environment variables:

string path = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)).FullName;
if ( Environment.OSVersion.Version.Major >= 6 ) {
    path = Directory.GetParent(path).ToString();
}

Though using the environment variable is much more clear.

How can I find the location of origin/master in git, and how do I change it?

I thought my laptop was the origin…

That’s kind of nonsensical: origin refers to the default remote repository – the one you usually fetch/pull other people’s changes from.

How can I:

  1. git remote -v will show you what origin is; origin/master is your “bookmark” for the last known state of the master branch of the origin repository, and your own master is a tracking branch for origin/master. This is all as it should be.

  2. You don’t. At least it makes no sense for a repository to be the default remote repository for itself.

  3. It isn’t. It’s merely telling you that you have made so-and-so many commits locally which aren’t in the remote repository (according to the last known state of that repository).

Getting the PublicKeyToken of .Net assemblies

An alternate method would be if you have decompiler, just look it up in there, they usually provide the public key. I have looked at .Net Reflector, Telerik Just Decompile and ILSpy just decompile they seem to have the public key token displayed.

Bash command line and input limit

There is a buffer limit of something like 1024. The read will simply hang mid paste or input. To solve this use the -e option.

http://linuxcommand.org/lc3_man_pages/readh.html

-e use Readline to obtain the line in an interactive shell

Change your read to read -e and annoying line input hang goes away.

Adding a legend to PyPlot in Matplotlib in the simplest manner possible

You can add a custom legend documentation

first = [1, 2, 4, 5, 4]
second = [3, 4, 2, 2, 3]
plt.plot(first, 'g--', second, 'r--')
plt.legend(['First List', 'Second List'], loc='upper left')
plt.show()

enter image description here

How can I increase the JVM memory?

If you are using Eclipse then you can do this by specifying the required size for the particular application in its Run Configuration's VM Arguments as EX: -Xms128m -Xmx512m

Or if you want all applications running from your eclipse to have the same specified size then you can specify this in the eclipse.ini file which is present in your Eclipse home directory.

To get the size of the JVM during Runtime you can use Runtime.totalMemory() which returns the total amount of memory in the Java virtual machine, measured in bytes.

How to capture multiple repeated groups?

You actually have one capture group that will match multiple times. Not multiple capture groups.

javascript (js) solution:

let string = "HI,THERE,TOM";
let myRegexp = /([A-Z]+),?/g;       //modify as you like
let match = myRegexp.exec(string);  //js function, output described below
while(match!=null){                 //loops through matches
    console.log(match[1]);          //do whatever you want with each match
    match = myRegexp.exec(bob);     //find next match
}

Output:

HI
THERE
TOM

Syntax:

// matched text: match[0]
// match start: match.index
// capturing group n: match[n]

As you can see, this will work for any number of matches.

find -mtime files older than 1 hour

What about -mmin?

find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
    -exec rm -f {} \;

From man find:

-mmin n
        File's data was last modified n minutes ago.

Also, make sure to test this first!

... -exec echo rm -f '{}' \;
          ^^^^ Add the 'echo' so you just see the commands that are going to get
               run instead of actual trying them first.

How to click a href link using Selenium

Use an explicit wait for the element like this:

WebDriverWait wait1 = new WebDriverWait(driver, 500);
wait1.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("path of element"))).click();

A better way to check if a path exists or not in PowerShell

if (Test-Path C:\DockerVol\SelfCertSSL) {
    write-host "Folder already exists."
} else {
   New-Item -Path "C:\DockerVol\" -Name "SelfCertSSL" -ItemType "directory"
}

Using Oracle to_date function for date string with milliseconds

You can try this format SS.FF for milliseconds:

to_timestamp(table_1.date_col,'DD-Mon-RR HH24:MI:SS.FF')

For more details:
https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions193.htm

Remove empty strings from a list of strings

Keep in mind that if you want to keep the white spaces within a string, you may remove them unintentionally using some approaches. If you have this list

['hello world', ' ', '', 'hello'] what you may want ['hello world','hello']

first trim the list to convert any type of white space to empty string:

space_to_empty = [x.strip() for x in _text_list]

then remove empty string from them list

space_clean_list = [x for x in space_to_empty if x]

Facebook share link - can you customize the message body text?

Like @Ardee said you sharer.php uses data from the meta tags, the Dialog API accepts parameters. Facebook have removed the ability to use the message parameter but you can use the quote parameter which can be useful in a lot of cases e.g.

enter image description here

https://www.facebook.com/dialog/share?
app_id=[your-app-id]
&display=popup
&title=This+is+the+title+parameter
&description=This+is+the+description+parameter
&quote=This+is+the+quote+parameter
&caption=This+is+the+caption+parameter
&href=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2F
&redirect_uri=https%3A%2F%2Fwww.[url-in-your-accepted-list].com

Just have to create an app id:

https://developers.facebook.com/docs/apps/register

Then make sure the redirect url domain is listed in the accepted domains for that app.

Stream file using ASP.NET MVC FileContentResult in a browser with a name?

This might be helpful for whoever else faces this problem. I finally figured out a solution. Turns out, even if we use the inline for "content-disposition" and specify a file name, the browsers still do not use the file name. Instead browsers try and interpret the file name based on the Path/URL.

You can read further on this URL: Securly download file inside browser with correct filename

This gave me an idea, I just created my URL route that would convert the URL and end it with the name of the file I wanted to give the file. So for e.g. my original controller call just consisted of passing the Order Id of the Order being printed. I was expecting the file name to be of the format Order{0}.pdf where {0} is the Order Id. Similarly for quotes, I wanted Quote{0}.pdf.

In my controller, I just went ahead and added an additional parameter to accept the file name. I passed the filename as a parameter in the URL.Action method.

I then created a new route that would map that URL to the format: http://localhost/ShoppingCart/PrintQuote/1054/Quote1054.pdf


routes.MapRoute("", "{controller}/{action}/{orderId}/{fileName}",
                new { controller = "ShoppingCart", action = "PrintQuote" }
                , new string[] { "x.x.x.Controllers" }
            );

This pretty much solved my issue. Hoping this helps someone!

Cheerz, Anup

What are .tpl files? PHP, web design

In this specific case it is Smarty, but it could also be Jinja2 templates. They usually also have a .tpl extension.

Adding content to a linear layout dynamically?

I found more accurate way to adding views like linear layouts in kotlin (Pass parent layout in inflate() and false)

val parentLayout = view.findViewById<LinearLayout>(R.id.llRecipientParent)
val childView = layoutInflater.inflate(R.layout.layout_recipient, parentLayout, false)
parentLayout.addView(childView)

Button Center CSS

The problem is with the following CSS line on .nav_button:

margin: 0 auto;

That would only work if you had one button, that's why they're off-centered when there are more than one nav_button divs.

If you want all your buttons centered nest the nav_buttons in another div:

<div class="nav">
    <div class="centerButtons">
        <div class="nav_button">
            <div class="b_left"></div>
            <div class="b_middle">Home</div>
            <div class="b_right"></div>
        </div>
        <div class="nav_button">
            <div class="b_left"></div>
            <div class="b_middle">Contact Us</div>
            <div class="b_right"></div>
        </div>
    </div>
</div>

And style it this way:

.nav{
    margin-top:167px;
    width:1024px;
    height:34px;
}

/* Centers the div that nests the nav_buttons */
.centerButtons {
    margin: 0 auto;
    float: left;
} 

.nav_button{
    height:34px;
    margin-right:10px;
    float: left;
}

Convert integer value to matching Java Enum

This is what I use:

public enum Quality {ENOUGH,BETTER,BEST;
                     private static final int amount = EnumSet.allOf(Quality.class).size();
                     private static Quality[] val = new Quality[amount];
                     static{ for(Quality q:EnumSet.allOf(Quality.class)){ val[q.ordinal()]=q; } }
                     public static Quality fromInt(int i) { return val[i]; }
                     public Quality next() { return fromInt((ordinal()+1)%amount); }
                    }

AngularJS. How to call controller function from outside of controller component

I use to work with $http, when a want to get some information from a resource I do the following:

angular.module('services.value', [])

.service('Value', function($http, $q) {

var URL = "http://localhost:8080/myWeb/rest/";

var valid = false;

return {
    isValid: valid,
    getIsValid: function(callback){
        return $http.get(URL + email+'/'+password, {cache: false})
                    .success(function(data){
            if(data === 'true'){ valid = true; }
        }).then(callback);
    }}
    });

And the code in the controller:

angular.module('controllers.value', ['services.value'])

.controller('ValueController', function($scope, Value) {
    $scope.obtainValue = function(){
        Value.getIsValid(function(){$scope.printValue();});
    }

    $scope.printValue = function(){
        console.log("Do it, and value is " Value.isValid);
    }
}

I send to the service what function have to call in the controller

jquery clone div and append it after specific div

This works great if a straight copy is in order. If the situation calls for creating new objects from templates, I usually wrap the template div in a hidden storage div and use jquery's html() in conjunction with clone() applying the following technique:

<style>
#element-storage {
    display: none;
    top: 0;
    right: 0;
    position: fixed;
    width: 0;
    height: 0;
}
</style>

<script>
$("#new-div").append($("#template").clone().html(function(index, oldHTML){ 
    // .. code to modify template, e.g. below:
    var newHTML = "";
    newHTML = oldHTML.replace("[firstname]", "Tom");
    newHTML = newHTML.replace("[lastname]", "Smith");
    // newHTML = newHTML.replace(/[Example Replace String]/g, "Replacement"); // regex for global replace
    return newHTML;
}));
</script>

<div id="element-storage">
  <div id="template">
    <p>Hello [firstname] [lastname]</p>
  </div>
</div>

<div id="new-div">

</div>

Android Fragment onClick button Method

The others have already said that methods in onClick are searched in activities, not fragments. Nevertheless, if you really want it, it is possible.

Basically, each view has a tag (probably null). We set the root view's tag to the fragment that inflated that view. Then, it is easy to search the view parents and retrieve the fragment containing the clicked button. Now, we find out the method name and use reflection to call the same method from the retrieved fragment. Easy!

in a class that extends Fragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_id, container, false);

    OnClickFragments.registerTagFragment(rootView, this); // <========== !!!!!

    return rootView;
}

public void onButtonSomething(View v) {
    Log.d("~~~","~~~ MyFragment.onButtonSomething");
    // whatever
}

all activities are derived from the same ButtonHandlingActivity:

public class PageListActivity extends ButtonHandlingActivity

ButtonHandlingActivity.java:

public class ButtonHandlingActivity extends Activity {

    public void onButtonSomething(View v) {
        OnClickFragments.invokeFragmentButtonHandlerNoExc(v);
//or, if you want to handle exceptions:
//      try {
//          OnClickFragments.invokeFragmentButtonHandler(v);
//      } catch ...
    }

}

It has to define methods for all xml onClick handlers.

com/example/customandroid/OnClickFragments.java:

package com.example.customandroid;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.app.Fragment;
import android.view.View;

public abstract class OnClickFragments {
    public static class FragmentHolder {
        Fragment fragment;
        public FragmentHolder(Fragment fragment) {
            this.fragment = fragment;
        }
    }
    public static Fragment getTagFragment(View view) {
        for (View v = view; v != null; v = (v.getParent() instanceof View) ? (View)v.getParent() : null) {
            Object tag = v.getTag();
            if (tag != null && tag instanceof FragmentHolder) {
                return ((FragmentHolder)tag).fragment;
            }
        }
        return null;
    }
    public static String getCallingMethodName(int callsAbove) {
        Exception e = new Exception();
        e.fillInStackTrace();
        String methodName = e.getStackTrace()[callsAbove+1].getMethodName();
        return methodName;
    }
    public static void invokeFragmentButtonHandler(View v, int callsAbove) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
        String methodName = getCallingMethodName(callsAbove+1);
        Fragment f = OnClickFragments.getTagFragment(v);
        Method m = f.getClass().getMethod(methodName, new Class[] { View.class });
        m.invoke(f, v);
    }
    public static void invokeFragmentButtonHandler(View v) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
        invokeFragmentButtonHandler(v,1);
    }
    public static void invokeFragmentButtonHandlerNoExc(View v) {
        try {
            invokeFragmentButtonHandler(v,1);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    public static void registerTagFragment(View rootView, Fragment fragment) {
        rootView.setTag(new FragmentHolder(fragment));
    }
}

And the next adventure will be proguard obfuscation...

PS

It is of course up to you to design your application so that the data live in the Model rather than in Activities or Fragments (which are Controllers from the MVC, Model-View-Controller point of view). The View is what you define via xml, plus the custom view classes (if you define them, most people just reuse what already is). A rule of thumb: if some data definitely must survive the screen turn, they belong to Model.

Is there a GUI design app for the Tkinter / grid geometry?

Apart from the options already given in other answers, there's a current more active, recent and open-source project called pygubu.

This is the first description by the author taken from the github repository:

Pygubu is a RAD tool to enable quick & easy development of user interfaces for the python tkinter module.

The user interfaces designed are saved as XML, and by using the pygubu builder these can be loaded by applications dynamically as needed. Pygubu is inspired by Glade.


Pygubu hello world program is an introductory video explaining how to create a first project using Pygubu.

The following in an image of interface of the last version of pygubu designer on a OS X Yosemite 10.10.2:

enter image description here

I would definitely give it a try, and contribute to its development.

SQL - How to find the highest number in a column?

In PHP:

$sql = mysql_query("select id from customers order by id desc");
$rs = mysql_fetch_array($sql);
if ( !$rs ) { $newid = 1; } else { $newid = $rs[newid]+1; }

thus $newid = 23 if last record in column id was 22.

How to completely uninstall Visual Studio 2010?

Best way I have used is to mount the VS 2010 Image or insert the Installation disc and run the uninstall option, really works well

How to display (print) vector in Matlab?

I prefer the following, which is cleaner:

x = [1, 2, 3];
g=sprintf('%d ', x);
fprintf('Answer: %s\n', g)

which outputs

Answer: 1 2 3

Saving binary data as file using JavaScript from a browser

This is possible if the browser supports the download property in anchor elements.

var sampleBytes = new Int8Array(4096);

var saveByteArray = (function () {
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    return function (data, name) {
        var blob = new Blob(data, {type: "octet/stream"}),
            url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = name;
        a.click();
        window.URL.revokeObjectURL(url);
    };
}());

saveByteArray([sampleBytes], 'example.txt');


JSFiddle: http://jsfiddle.net/VB59f/2

About the Full Screen And No Titlebar from manifest

To set your App or any individual activity display in Full Screen mode, insert the code

<application 
    android:icon="@drawable/icon" 
    android:label="@string/app_name" 
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen">

in AndroidManifest.xml, under application or activity tab.

OraOLEDB.Oracle provider is not registered on the local machine

If you are getting this in a C# projet, check if you are running in 64-bit or 32-bit mode with the following code:

        if (IntPtr.Size == 4)
        {
            Console.WriteLine("This is 32-Bit!");
        }
        else if (IntPtr.Size == 8)
        {
            Console.WriteLine("This is 64 Bit!");
        }

If you find that you are running in 64-Bit mode, you may want to try switching to 32-Bit (or vice versa). You can follow this guide to force your application to run as 64 or 32 bit (X64 and X86 respectively). You have to make sure that Platform Target in your project properties is not set to Any CPU and that it is explicitley set.

enter image description here

Switching that option from Any CPU to X86 resolved my error and I was able to connect to the Oracle provider.

How to use JavaScript regex over multiple lines?

[.\n] does not work because . has no special meaning inside of [], it just means a literal .. (.|\n) would be a way to specify "any character, including a newline". If you want to match all newlines, you would need to add \r as well to include Windows and classic Mac OS style line endings: (.|[\r\n]).

That turns out to be somewhat cumbersome, as well as slow, (see KrisWebDev's answer for details), so a better approach would be to match all whitespace characters and all non-whitespace characters, with [\s\S], which will match everything, and is faster and simpler.

In general, you shouldn't try to use a regexp to match the actual HTML tags. See, for instance, these questions for more information on why.

Instead, try actually searching the DOM for the tag you need (using jQuery makes this easier, but you can always do document.getElementsByTagName("pre") with the standard DOM), and then search the text content of those results with a regexp if you need to match against the contents.

Difference between DOM parentNode and parentElement

there is one more difference, but only in internet explorer. It occurs when you mix HTML and SVG. if the parent is the 'other' of those two, then .parentNode gives the parent, while .parentElement gives undefined.

Why does one use dependency injection?

The main reason to use DI is that you want to put the responsibility of the knowledge of the implementation where the knowledge is there. The idea of DI is very much inline with encapsulation and design by interface. If the front end asks from the back end for some data, then is it unimportant for the front end how the back end resolves that question. That is up to the requesthandler.

That is already common in OOP for a long time. Many times creating code pieces like:

I_Dosomething x = new Impl_Dosomething();

The drawback is that the implementation class is still hardcoded, hence has the front end the knowledge which implementation is used. DI takes the design by interface one step further, that the only thing the front end needs to know is the knowledge of the interface. In between the DYI and DI is the pattern of a service locator, because the front end has to provide a key (present in the registry of the service locator) to lets its request become resolved. Service locator example:

I_Dosomething x = ServiceLocator.returnDoing(String pKey);

DI example:

I_Dosomething x = DIContainer.returnThat();

One of the requirements of DI is that the container must be able to find out which class is the implementation of which interface. Hence does a DI container require strongly typed design and only one implementation for each interface at the same time. If you need more implementations of an interface at the same time (like a calculator), you need the service locator or factory design pattern.

D(b)I: Dependency Injection and Design by Interface. This restriction is not a very big practical problem though. The benefit of using D(b)I is that it serves communication between the client and the provider. An interface is a perspective on an object or a set of behaviours. The latter is crucial here.

I prefer the administration of service contracts together with D(b)I in coding. They should go together. The use of D(b)I as a technical solution without organizational administration of service contracts is not very beneficial in my point of view, because DI is then just an extra layer of encapsulation. But when you can use it together with organizational administration you can really make use of the organizing principle D(b)I offers. It can help you in the long run to structure communication with the client and other technical departments in topics as testing, versioning and the development of alternatives. When you have an implicit interface as in a hardcoded class, then is it much less communicable over time then when you make it explicit using D(b)I. It all boils down to maintenance, which is over time and not at a time. :-)

how to set default method argument values?

If your arguments are the same type you could use varargs:

public int something(int... args) {
    int a = 0;
    int b = 0;
    if (args.length > 0) {
      a = args[0];
    }
    if (args.length > 1) {
      b = args[1];
    }
    return a + b
}

but this way you lose the semantics of the individual arguments, or

have a method overloaded which relays the call to the parametered version

public int something() {
  return something(1, 2);
}

or if the method is part of some kind of initialization procedure, you could use the builder pattern instead:

class FoodBuilder {
   int saltAmount;
   int meatAmount;
   FoodBuilder setSaltAmount(int saltAmount) {
       this.saltAmount = saltAmount;
       return this;
   }
   FoodBuilder setMeatAmount(int meatAmount) {
       this.meatAmount = meatAmount;
       return this;
   }
   Food build() {
       return new Food(saltAmount, meatAmount);
   }
}

Food f = new FoodBuilder().setSaltAmount(10).build();
Food f2 = new FoodBuilder().setSaltAmount(10).setMeatAmount(5).build();

Then work with the Food object

int doSomething(Food f) {
    return f.getSaltAmount() + f.getMeatAmount();
}

The builder pattern allows you to add/remove parameters later on and you don't need to create new overloaded methods for them.

Can I define a class name on paragraph using Markdown?

If you just need a selector for Javascript purposes (like I did), you might just want to use a href attribute instead of a class or id:

Just do this:

<a href="#foo">Link</a>

Markdown will not ignore or remove the href attribute like it does with classes and ids.

So in your Javascript or jQuery you can then do:

$('a[href$="foo"]').click(function(event) {

    ... do your thing ...

    event.preventDefault();
});

At least this works in my version of Markdown...

NameError: name 'reduce' is not defined in Python

Or if you use the six library

from six.moves import reduce

CodeIgniter - File upload required validation

I found a solution that works exactly how I want.

I changed

$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
$this->form_validation->set_rules('userfile', 'Document', 'required');

To

$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
if (empty($_FILES['userfile']['name']))
{
    $this->form_validation->set_rules('userfile', 'Document', 'required');
}

What is the difference between ndarray and array in numpy?

numpy.array is a function that returns a numpy.ndarray. There is no object type numpy.array.

Detect the Internet connection is offline?

The HTML5 Application Cache API specifies navigator.onLine, which is currently available in the IE8 betas, WebKit (eg. Safari) nightlies, and is already supported in Firefox 3

What's the best way of scraping data from a website?

Yes you can do it yourself. It is just a matter of grabbing the sources of the page and parsing them the way you want.

There are various possibilities. A good combo is using python-requests (built on top of urllib2, it is urllib.request in Python3) and BeautifulSoup4, which has its methods to select elements and also permits CSS selectors:

import requests
from BeautifulSoup4 import BeautifulSoup as bs
request = requests.get("http://foo.bar")
soup = bs(request.text) 
some_elements = soup.find_all("div", class_="myCssClass")

Some will prefer xpath parsing or jquery-like pyquery, lxml or something else.

When the data you want is produced by some JavaScript, the above won't work. You either need python-ghost or Selenium. I prefer the latter combined with PhantomJS, much lighter and simpler to install, and easy to use:

from selenium import webdriver
client = webdriver.PhantomJS()
client.get("http://foo")
soup = bs(client.page_source)

I would advice to start your own solution. You'll understand Scrapy's benefits doing so.

ps: take a look at scrapely: https://github.com/scrapy/scrapely

pps: take a look at Portia, to start extracting information visually, without programming knowledge: https://github.com/scrapinghub/portia

What is the difference between a Shared Project and a Class Library in Visual Studio 2015?

I found some more information from this blog.

  • In a Class Library, when code is compiled, assemblies (dlls) are generated for each library. But with Shared Project it will not contain any header information so when you have a Shared Project reference it will be compiled as part of the parent application. There will not be separate dlls created.
  • In class library you are only allowed to write C# code while shared project can have any thing like C# code files, XAML files or JavaScript files etc.

try/catch with InputMismatchException creates infinite loop

As the bError = false statement is never reached in the try block, and the statement is struck to the input taken, it keeps printing the error in infinite loop.

Try using it this way by using hasNextInt()

catch (Exception e) {
            System.out.println("Error!");
           input.hasNextInt();         
        }

Or try using nextLine() coupled with Integer.parseInt() for taking input....

Scanner scan = new Scanner(System.in);

int num1 = Integer.parseInt(scan.nextLine());
int num2 = Integer.parseInt(scan.nextLine());

How to use support FileProvider for sharing content to other apps?

I want to share something that blocked us for a couple of days: the fileprovider code MUST be inserted between the application tags, not after it. It may be trivial, but it's never specified, and I thought that I could have helped someone! (thanks again to piolo94)

python how to "negate" value : if true return false, if false return true

Use the not boolean operator:

nyval = not myval

not returns a boolean value (True or False):

>>> not 1
False
>>> not 0
True

If you must have an integer, cast it back:

nyval = int(not myval)

However, the python bool type is a subclass of int, so this may not be needed:

>>> int(not 0)
1
>>> int(not 1)
0
>>> not 0 == 1
True
>>> not 1 == 0
True

What does "Table does not support optimize, doing recreate + analyze instead" mean?

Best option is create new table with same properties

CREATE TABLE <NEW.NAME.TABLE> LIKE <TABLE.CRASHED>;
INSERT INTO <NEW.NAME.TABLE> SELECT * FROM <TABLE.CRASHED>;

Rename NEW.NAME.TABLE and TABLE.CRASH

RENAME TABLE <TABLE.CRASHED> TO <TABLE.CRASHED.BACKUP>;
RENAME TABLE <NEW.NAME.TABLE> TO <TABLE.CRASHED>;

After work well, delete

DROP TABLE <TABLE.CRASHED.BACKUP>;

How to print a double with two decimals in Android?

use this one:

DecimalFormat form = new DecimalFormat("0.00");
etToll.setText(form.format(tvTotalAmount) );

Note: Data must be in decimal format (tvTotalAmount)

Jupyter Notebook not saving: '_xsrf' argument missing from post

I was able to solve it by clicking on the "Kernel" drop down menu and choosing "Interrupt."

Search an Oracle database for tables with specific column names?

The data you want is in the "cols" meta-data table:

SELECT * FROM COLS WHERE COLUMN_NAME = 'id'

This one will give you a list of tables that have all of the columns you want:

select distinct
  C1.TABLE_NAME
from
  cols c1
  inner join
  cols c2
  on C1.TABLE_NAME = C2.TABLE_NAME
  inner join
  cols c3
  on C2.TABLE_NAME = C3.TABLE_NAME
  inner join
  cols c4
  on C3.TABLE_NAME = C4.TABLE_NAME  
  inner join
  tab t
  on T.TNAME = C1.TABLE_NAME
where T.TABTYPE = 'TABLE' --could be 'VIEW' if you wanted
  and upper(C1.COLUMN_NAME) like upper('%id%')
  and upper(C2.COLUMN_NAME) like upper('%fname%')
  and upper(C3.COLUMN_NAME) like upper('%lname%')
  and upper(C4.COLUMN_NAME) like upper('%address%')  

To do this in a different schema, just specify the schema in front of the table, as in

SELECT * FROM SCHEMA1.COLS WHERE COLUMN_NAME LIKE '%ID%';

If you want to combine the searches of many schemas into one output result, then you could do this:

SELECT DISTINCT
  'SCHEMA1' AS SCHEMA_NAME
 ,TABLE_NAME
FROM SCHEMA1.COLS
WHERE COLUMN_NAME LIKE '%ID%'
UNION
SELECT DISTINCT
  'SCHEMA2' AS SCHEMA_NAME
 ,TABLE_NAME
FROM SCHEMA2.COLS
WHERE COLUMN_NAME LIKE '%ID%'

Export data from Chrome developer tool

To get this in excel or csv format- right click the folder and select "copy response"- paste to excel and use text to columns.

git commit error: pathspec 'commit' did not match any file(s) known to git

In my case, this error was due to special characters what I was considering double quotes as I copied the command from a web page.

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

I tried all of the above, nothing worked for me. Then I changed tomcat port numbers both HTTP/1.1 and Tomcat admin port and it got solved.

I see other solutions above worked for the people but it is worth to try this one if any of the above doesn't work.

Thanks everyone!

JavaScript Array Push key value

You have to use bracket notation:

var obj = {};
obj[a[i]] = 0;
x.push(obj);

The result will be:

x = [{left: 0}, {top: 0}];

Maybe instead of an array of objects, you just want one object with two properties:

var x = {};

and

x[a[i]] = 0;

This will result in x = {left: 0, top: 0}.

Creating a UIImage from a UIColor to use as a background image for UIButton

Xamarin.iOS solution

 public UIImage CreateImageFromColor()
 {
     var imageSize = new CGSize(30, 30);
     var imageSizeRectF = new CGRect(0, 0, 30, 30);
     UIGraphics.BeginImageContextWithOptions(imageSize, false, 0);
     var context = UIGraphics.GetCurrentContext();
     var red = new CGColor(255, 0, 0);
     context.SetFillColor(red);
     context.FillRect(imageSizeRectF);
     var image = UIGraphics.GetImageFromCurrentImageContext();
     UIGraphics.EndImageContext();
     return image;
 }

How to redirect output of an entire shell script within the script itself?

Addressing the question as updated.

#...part of script without redirection...

{
    #...part of script with redirection...
} > file1 2>file2 # ...and others as appropriate...

#...residue of script without redirection...

The braces '{ ... }' provide a unit of I/O redirection. The braces must appear where a command could appear - simplistically, at the start of a line or after a semi-colon. (Yes, that can be made more precise; if you want to quibble, let me know.)

You are right that you can preserve the original stdout and stderr with the redirections you showed, but it is usually simpler for the people who have to maintain the script later to understand what's going on if you scope the redirected code as shown above.

The relevant sections of the Bash manual are Grouping Commands and I/O Redirection. The relevant sections of the POSIX shell specification are Compound Commands and I/O Redirection. Bash has some extra notations, but is otherwise similar to the POSIX shell specification.

How do I define the name of image built with docker-compose

According to 3.9 version of Docker compose, you can use image: myapp:tag to specify name and tag.

version: "3.9"
services:
  webapp:
    build:
      context: .
      dockerfile: Dockerfile
    image: webapp:tag

Reference: https://docs.docker.com/compose/compose-file/compose-file-v3/

Javascript Equivalent to PHP Explode()

You don't need to split. You can use indexOf and substr:

str = str.substr(str.indexOf(':')+1);

But the equivalent to explode would be split.

jQuery Loop through each div

$('div.target').each(function() {
   /* Measure the width of each image. */
   var test = $(this).find('.scrolling img').width();

   /* Find out how many images there are. */
   var testimg = $(this).find('.scrolling img').length;

   /* Do the maths. */
   var final = (test* testimg)*1.2;

   /* Apply the maths to the CSS. */
   $(this).find('scrolling').width(final); 
});

Here you loop through all your div's with class target and you do the calculations. Within this loop you can simply use $(this) to indicate the currently selected <div> tag.

Show/Hide Multiple Divs with Jquery

If they fall into logical groups, I would probably go with the class approach already listed here.

Many people seem to forget that you can actually select several items by id in the same jQuery selector, as well:

$("#div1, #div2, #div3").show();

Where 'div1', 'div2', and 'div3' are all id attributes on various divs you want to show at once.

How do I mock a REST template exchange?

The RestTemplate instance has to be a real object. It should work if you create a real instance of RestTemplate and make it @Spy.

@Spy
private RestTemplate restTemplate = new RestTemplate();

How do I create a link using javascript?

<html>
  <head></head>
  <body>
    <script>
      var a = document.createElement('a');
      var linkText = document.createTextNode("my title text");
      a.appendChild(linkText);
      a.title = "my title text";
      a.href = "http://example.com";
      document.body.appendChild(a);
    </script>
  </body>
</html>

How to fix: Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

  1. run cmd

  2. drag and drop Aspnet_regiis.exe into the command prompt from:

    C:\Windows\Microsoft.NET\Framework64\v2.0.50727\
    
  3. type -i (for example Aspnet_regiis.exe -i)

  4. hit enter

  5. wait until the process completes

Good luck!

What is the best way to delete a component with CLI

From app.module.ts:

  • erase import line for the specific component;
  • erase its declaration from @NgModule;

Then delete the folder of the component you want to delete and its included files (.component.ts, .component.html, .component.css and .component.spec.ts).

Done.

-

I read people saying about erasing it from main.ts. You were not supposed to import it from there in the first place as it already imports AppModule, and AppModule is the one importing all the components you created.

Easiest way to detect Internet connection on iOS?

Replacement for Apple's Reachability re-written in Swift with closures, inspired by tonymillion: https://github.com/ashleymills/Reachability.swift

  1. Drop the file Reachability.swift into your project. Alternatively, use CocoaPods or Carthage - See the Installation section of the project's README.

  2. Get notifications about network connectivity:

    //declare this property where it won't go out of scope relative to your listener
    let reachability = Reachability()!
    
    reachability.whenReachable = { reachability in
        if reachability.isReachableViaWiFi {
            print("Reachable via WiFi")
        } else {
            print("Reachable via Cellular")
        }
    }
    
    reachability.whenUnreachable = { _ in
        print("Not reachable")
    }
    
    do {
        try reachability.startNotifier()
    } catch {
        print("Unable to start notifier")
    }
    

    and for stopping notifications

    reachability.stopNotifier()
    

The response content cannot be parsed because the Internet Explorer engine is not available, or

In your invoke web request just use the parameter -UseBasicParsing

e.g. in your script (line 2) you should use:

$rss = Invoke-WebRequest -Uri $url -UseBasicParsing

According to the documentation, this parameter is necessary on systems where IE isn't installed or configured:

Uses the response object for HTML content without Document Object Model (DOM) parsing. This parameter is required when Internet Explorer is not installed on the computers, such as on a Server Core installation of a Windows Server operating system.

Remove a data connection from an Excel 2010 spreadsheet in compatibility mode

I had many connections I couldn't delete but didn't want to delete them all. So, I extended Dang Thanh and Richard Ho 's solution so it would prompt user to decide which connections to delete.

To delete some but not all connections in a Workbook:

Public Function deleteConnections()

    Dim xlBook As Workbook
    Dim cn As WorkbookConnection
    Dim Result As Variant

    Set xlBook = ActiveWorkbook

    For Each cn In xlBook.Connections

        Dim strMsg As String
        strMsg = "Would you like to delete: " & vbNewLine & cn.Name
        Result = MsgBox(strMsg, vbYesNo)

        If Result = vbYes Then
            cn.Delete
        End If

    Next cn

End Function

Cannot enqueue Handshake after invoking quit

You can use debug: false,

Example: //mysql connection

var dbcon1 = mysql.createConnection({
      host: "localhost",
      user: "root",
      password: "",
      database: "node5",
      debug: false,
    });

How to verify static void method has been called with power mockito

Thou the above answer is widely accepted and well documented, I found some of the reason to post my answer here :-

    doNothing().when(InternalUtils.class); //This is the preferred way
                                           //to mock static void methods.
    InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());

Here, I dont understand why we are calling InternalUtils.sendEmail ourself. I will explain in my code why we don't need to do that.

mockStatic(Internalutils.class);

So, we have mocked the class which is fine. Now, lets have a look how we need to verify the sendEmail(/..../) method.

@PrepareForTest({InternalService.InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest {

    @Mock
    private InternalService.Order order;

    private InternalService internalService;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        internalService = new InternalService();
    }

    @Test
    public void processOrder() throws Exception {

        Mockito.when(order.isSuccessful()).thenReturn(true);
        PowerMockito.mockStatic(InternalService.InternalUtils.class);

        internalService.processOrder(order);

        PowerMockito.verifyStatic(times(1));
        InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());
    }

}

These two lines is where the magic is, First line tells the PowerMockito framework that it needs to verify the class it statically mocked. But which method it need to verify ?? Second line tells which method it needs to verify.

PowerMockito.verifyStatic(times(1));
InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());

This is code of my class, sendEmail api twice.

public class InternalService {

    public void processOrder(Order order) {
        if (order.isSuccessful()) {
            InternalUtils.sendEmail("", new String[1], "", "");
            InternalUtils.sendEmail("", new String[1], "", "");
        }
    }

    public static class InternalUtils{

        public static void sendEmail(String from, String[]  to, String msg, String body){

        }

    }

    public class Order{

        public boolean isSuccessful(){
            return true;
        }

    }

}

As it is calling twice you just need to change the verify(times(2))... that's all.

Generating CSV file for Excel, how to have a newline inside a value

The way we do it (we use VB.Net) is to enclose the text with new lines in Chr(34) which is the char representing the double quotes and replace all CR-LF characters for LF.

ant warning: "'includeantruntime' was not set"

As @Daniel Kutik mentioned, presetdef is a good option. Especially if one is working on a project with many build.xml files which one cannot, or prefers not to, edit (e.g., those from third-parties.)

To use presetdef, add these lines in your top-level build.xml file:

  <presetdef name="javac">
    <javac includeantruntime="false" />
  </presetdef>

Now all subsequent javac tasks will essentially inherit includeantruntime="false". If your projects do actually need ant runtime libraries, you can either add them explicitly to your build files OR set includeantruntime="true". The latter will also get rid of warnings.

Subsequent javac tasks can still explicitly change this if desired, for example:

<javac destdir="out" includeantruntime="true">
  <src path="foo.java" />
  <src path="bar.java" />
</javac>

I'd recommend against using ANT_OPTS. It works, but it defeats the purpose of the warning. The warning tells one that one's build might behave differently on another system. Using ANT_OPTS makes this even more likely because now every system needs to use ANT_OPTS in the same way. Also, ANT_OPTS will apply globally, suppressing warnings willy-nilly in all your projects

Get Country of IP Address with PHP

$country_code = trim(file_get_contents("http://ipinfo.io/{$ip_address}/country"))

will get you the country code.

Javascript array value is undefined ... how do I test for that

predQuery[preId]=='undefined'

You're testing against the string 'undefined'; you've confused this test with the typeof test which would return a string. You probably mean to be testing against the special value undefined:

predQuery[preId]===undefined

Note the strict-equality operator to avoid the generally-unwanted match null==undefined.

However there are two ways you can get an undefined value: either preId isn't a member of predQuery, or it is a member but has a value set to the special undefined value. Often, you only want to check whether it's present or not; in that case the in operator is more appropriate:

!(preId in predQuery)

Java LinkedHashMap get first or last entry

One more way to get first and last entry of a LinkedHashMap is to use toArray() method of Set interface.

But I think iterating over the entries in the entry set and getting the first and last entry is a better approach.

The usage of array methods leads to warning of the form " ...needs unchecked conversion to conform to ..." which cannot be fixed [but can be only be suppressed by using the annotation @SuppressWarnings("unchecked")].

Here is a small example to demonstrate the usage of toArray() method:

    public static void main(final String[] args) {
        final Map<Integer,String> orderMap = new LinkedHashMap<Integer,String>();
        orderMap.put(6, "Six");
        orderMap.put(7, "Seven");
        orderMap.put(3, "Three");
        orderMap.put(100, "Hundered");
        orderMap.put(10, "Ten");

        final Set<Entry<Integer, String>> mapValues = orderMap.entrySet();
        final int maplength = mapValues.size();
        final Entry<Integer,String>[] test = new Entry[maplength];
        mapValues.toArray(test);

        System.out.print("First Key:"+test[0].getKey());
        System.out.println(" First Value:"+test[0].getValue());

        System.out.print("Last Key:"+test[maplength-1].getKey());
        System.out.println(" Last Value:"+test[maplength-1].getValue());
    }

    // the output geneated is :
    First Key:6 First Value:Six
    Last Key:10 Last Value:Ten

How to iterate over a column vector in Matlab?

with many functions in matlab, you don't need to iterate at all.

for example, to multiply by it's position in the list:

m = [1:numel(list)]';
elm = list.*m;

vectorized algorithms in matlab are in general much faster.

Error message "Strict standards: Only variables should be passed by reference"

The second snippet doesn't work either and that's why.

array_shift is a modifier function, that changes its argument. Therefore it expects its parameter to be a reference, and you cannot reference something that is not a variable. See Rasmus' explanations here: Strict standards: Only variables should be passed by reference

What is the difference between up-casting and down-casting with respect to class variable

I know this question asked quite long time ago but for the new users of this question. Please read this article where contains complete description on upcasting, downcasting and use of instanceof operator

  • There's no need to upcast manually, it happens on its own:

    Mammal m = (Mammal)new Cat(); equals to Mammal m = new Cat();

  • But downcasting must always be done manually:

    Cat c1 = new Cat();      
    Animal a = c1;      //automatic upcasting to Animal
    Cat c2 = (Cat) a;    //manual downcasting back to a Cat
    

Why is that so, that upcasting is automatical, but downcasting must be manual? Well, you see, upcasting can never fail. But if you have a group of different Animals and want to downcast them all to a Cat, then there's a chance, that some of these Animals are actually Dogs, and process fails, by throwing ClassCastException. This is where is should introduce an useful feature called "instanceof", which tests if an object is instance of some Class.

 Cat c1 = new Cat();         
    Animal a = c1;       //upcasting to Animal
    if(a instanceof Cat){ // testing if the Animal is a Cat
        System.out.println("It's a Cat! Now i can safely downcast it to a Cat, without a fear of failure.");        
        Cat c2 = (Cat)a;
    }

For more information please read this article

on change event for file input element

The OnChange event is a good choice. But if a user select the same image, the event will not be triggered because the current value is the same as the previous.

The image is the same with a width changed, for example, and it should be uploaded to the server.

To prevent this problem you could to use the following code:

$(document).ready(function(){
    $("input[type=file]").click(function(){
        $(this).val("");
    });

    $("input[type=file]").change(function(){
        alert($(this).val());
    });
});

Show history of a file?

The main question for me would be, what are you actually trying to find out? Are you trying to find out, when a certain set of changes was introduced in that file?

You can use git blame for this, it will anotate each line with a SHA1 and a date when it was changed. git blame can also tell you when a certain line was deleted or where it was moved if you are interested in that.

If you are trying to find out, when a certain bug was introduced, git bisect is a very powerfull tool. git bisect will do a binary search on your history. You can use git bisect start to start bisecting, then git bisect bad to mark a commit where the bug is present and git bisect good to mark a commit which does not have the bug. git will checkout a commit between the two and ask you if it is good or bad. You can usually find the faulty commit within a few steps.

Since I have used git, I hardly ever found the need to manually look through patch histories to find something, since most often git offers me a way to actually look for the information I need.

If you try to think less of how to do a certain workflow, but more in what information you need, you will probably many workflows which (in my opinion) are much more simple and faster.

jQuery $(".class").click(); - multiple elements, click event once

I just had the same problem. In my case PHP code generated few times the same jQuery code and that was the multiple trigger.

<a href="#popraw" class="report" rel="884(PHP MULTIPLE GENERATER NUMBERS)">Popraw / Zglos</a>

(PHP MULTIPLE GENERATER NUMBERS generated also the same code multiple times)

<script type="text/javascript">
$('.report').click(function(){...});
</script>

My solution was to separate script in another php file and load that file ONE TIME.

How can I read numeric strings in Excel cells as string (not numbers)?

It looks like this can't be done in the current version of POI, based on the fact that this bug:

https://issues.apache.org/bugzilla/show_bug.cgi?id=46136

is still outstanding.

Is there a way to create key-value pairs in Bash script?

For persistent key/value storage, you can use kv-bash, a pure bash implementation of key/value database available at https://github.com/damphat/kv-bash

Usage

git clone https://github.com/damphat/kv-bash
source kv-bash/kv-bash

Try create some permanent variables

kvset myName  xyz
kvset myEmail [email protected]

#read the varible
kvget myEmail

#you can also use in another script with $(kvget keyname)
echo $(kvget myEmail)

How to change Navigation Bar color in iOS 7?

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.navigationController.navigationBar.barTintColor = [UIColor blueColor];
}

Send value of submit button when form gets posted

Use this instead:

<input id='tea-submit' type='submit' name = 'submit'    value = 'Tea'>
<input id='coffee-submit' type='submit' name = 'submit' value = 'Coffee'>

Redirecting to a page after submitting form in HTML

For anyone else having the same problem, I figured it out myself.

_x000D_
_x000D_
    <html>_x000D_
      <body>_x000D_
        <form target="_blank" action="https://website.com/action.php" method="POST">_x000D_
          <input type="hidden" name="fullname" value="Sam" />_x000D_
          <input type="hidden" name="city" value="Dubai&#32;" />_x000D_
          <input onclick="window.location.href = 'https://website.com/my-account';" type="submit" value="Submit request" />_x000D_
        </form>_x000D_
      </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

All I had to do was add the target="_blank" attribute to inline on form to open the response in a new page and redirect the other page using onclick on the submit button.

jQuery - Click event on <tr> elements with in a table and getting <td> element values

Try jQuery's delegate() function, like so:

$(document).ready(function(){
    $("div.custList table").delegate('tr', 'click', function() {
        alert("You clicked my <tr>!");
        //get <td> element values here!!??
    });
});

A delegate works in the same way as live() except that live() cannot be applied to chained items, whereas delegate() allows you to specify an element within an element to act on.

Search all of Git history for a string?

git rev-list --all | (
    while read revision; do
        git grep -F 'password' $revision
    done
)

Incorrect string value: '\xF0\x9F\x8E\xB6\xF0\x9F...' MySQL

I was finally able to figure out the issue. I had to change some settings in mysql configuration my.ini This article helped a lot http://mathiasbynens.be/notes/mysql-utf8mb4#character-sets

First i changed the character set in my.ini to utf8mb4 Next i ran the following commands in mysql client

SET NAMES utf8mb4; 
ALTER DATABASE dreams_twitter CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci;

Use the following command to check that the changes are made

SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name LIKE 'collation%';

How to implement a read only property

C# 6.0 adds readonly auto properties

public object MyProperty { get; }

So when you don't need to support older compilers you can have a truly readonly property with code that's just as concise as a readonly field.


Versioning:
I think it doesn't make much difference if you are only interested in source compatibility.
Using a property is better for binary compatibility since you can replace it by a property which has a setter without breaking compiled code depending on your library.

Convention:
You are following the convention. In cases like this where the differences between the two possibilities are relatively minor following the convention is better. One case where it might come back to bite you is reflection based code. It might only accept properties and not fields, for example a property editor/viewer.

Serialization
Changing from field to property will probably break a lot of serializers. And AFAIK XmlSerializer does only serialize public properties and not public fields.

Using an Autoproperty
Another common Variation is using an autoproperty with a private setter. While this is short and a property it doesn't enforce the readonlyness. So I prefer the other ones.

Readonly field is selfdocumenting
There is one advantage of the field though:
It makes it clear at a glance at the public interface that it's actually immutable (barring reflection). Whereas in case of a property you can only see that you cannot change it, so you'd have to refer to the documentation or implementation.

But to be honest I use the first one quite often in application code since I'm lazy. In libraries I'm typically more thorough and follow the convention.

What's the CMake syntax to set and use variables?

When writing CMake scripts there is a lot you need to know about the syntax and how to use variables in CMake.

The Syntax

Strings using set():

  • set(MyString "Some Text")
  • set(MyStringWithVar "Some other Text: ${MyString}")
  • set(MyStringWithQuot "Some quote: \"${MyStringWithVar}\"")

Or with string():

  • string(APPEND MyStringWithContent " ${MyString}")

Lists using set():

  • set(MyList "a" "b" "c")
  • set(MyList ${MyList} "d")

Or better with list():

  • list(APPEND MyList "a" "b" "c")
  • list(APPEND MyList "d")

Lists of File Names:

  • set(MySourcesList "File.name" "File with Space.name")
  • list(APPEND MySourcesList "File.name" "File with Space.name")
  • add_excutable(MyExeTarget ${MySourcesList})

The Documentation

The Scope or "What value does my variable have?"

First there are the "Normal Variables" and things you need to know about their scope:

  • Normal variables are visible to the CMakeLists.txt they are set in and everything called from there (add_subdirectory(), include(), macro() and function()).
  • The add_subdirectory() and function() commands are special, because they open-up their own scope.
    • Meaning variables set(...) there are only visible there and they make a copy of all normal variables of the scope level they are called from (called parent scope).
    • So if you are in a sub-directory or a function you can modify an already existing variable in the parent scope with set(... PARENT_SCOPE)
    • You can make use of this e.g. in functions by passing the variable name as a function parameter. An example would be function(xyz _resultVar) is setting set(${_resultVar} 1 PARENT_SCOPE)
  • On the other hand everything you set in include() or macro() scripts will modify variables directly in the scope of where they are called from.

Second there is the "Global Variables Cache". Things you need to know about the Cache:

  • If no normal variable with the given name is defined in the current scope, CMake will look for a matching Cache entry.
  • Cache values are stored in the CMakeCache.txt file in your binary output directory.
  • The values in the Cache can be modified in CMake's GUI application before they are generated. Therefore they - in comparison to normal variables - have a type and a docstring. I normally don't use the GUI so I use set(... CACHE INTERNAL "") to set my global and persistant values.

    Please note that the INTERNAL cache variable type does imply FORCE

  • In a CMake script you can only change existing Cache entries if you use the set(... CACHE ... FORCE) syntax. This behavior is made use of e.g. by CMake itself, because it normally does not force Cache entries itself and therefore you can pre-define it with another value.

  • You can use the command line to set entries in the Cache with the syntax cmake -D var:type=value, just cmake -D var=value or with cmake -C CMakeInitialCache.cmake.
  • You can unset entries in the Cache with unset(... CACHE).

The Cache is global and you can set them virtually anywhere in your CMake scripts. But I would recommend you think twice about where to use Cache variables (they are global and they are persistant). I normally prefer the set_property(GLOBAL PROPERTY ...) and set_property(GLOBAL APPEND PROPERTY ...) syntax to define my own non-persistant global variables.

Variable Pitfalls and "How to debug variable changes?"

To avoid pitfalls you should know the following about variables:

  • Local variables do hide cached variables if both have the same name
  • The find_... commands - if successful - do write their results as cached variables "so that no call will search again"
  • Lists in CMake are just strings with semicolons delimiters and therefore the quotation-marks are important
    • set(MyVar a b c) is "a;b;c" and set(MyVar "a b c") is "a b c"
    • The recommendation is that you always use quotation marks with the one exception when you want to give a list as list
    • Generally prefer the list() command for handling lists
  • The whole scope issue described above. Especially it's recommended to use functions() instead of macros() because you don't want your local variables to show up in the parent scope.
  • A lot of variables used by CMake are set with the project() and enable_language() calls. So it could get important to set some variables before those commands are used.
  • Environment variables may differ from where CMake generated the make environment and when the the make files are put to use.
    • A change in an environment variable does not re-trigger the generation process.
    • Especially a generated IDE environment may differ from your command line, so it's recommended to transfer your environment variables into something that is cached.

Sometimes only debugging variables helps. The following may help you:

  • Simply use old printf debugging style by using the message() command. There also some ready to use modules shipped with CMake itself: CMakePrintHelpers.cmake, CMakePrintSystemInformation.cmake
  • Look into CMakeCache.txt file in your binary output directory. This file is even generated if the actual generation of your make environment fails.
  • Use variable_watch() to see where your variables are read/written/removed.
  • Look into the directory properties CACHE_VARIABLES and VARIABLES
  • Call cmake --trace ... to see the CMake's complete parsing process. That's sort of the last reserve, because it generates a lot of output.

Special Syntax

  • Environment Variables
    • You can can read $ENV{...} and write set(ENV{...} ...) environment variables
  • Generator Expressions
    • Generator expressions $<...> are only evaluated when CMake's generator writes the make environment (it comparison to normal variables that are replaced "in-place" by the parser)
    • Very handy e.g. in compiler/linker command lines and in multi-configuration environments
  • References
    • With ${${...}} you can give variable names in a variable and reference its content.
    • Often used when giving a variable name as function/macro parameter.
  • Constant Values (see if() command)
    • With if(MyVariable) you can directly check a variable for true/false (no need here for the enclosing ${...})
    • True if the constant is 1, ON, YES, TRUE, Y, or a non-zero number.
    • False if the constant is 0, OFF, NO, FALSE, N, IGNORE, NOTFOUND, the empty string, or ends in the suffix -NOTFOUND.
    • This syntax is often use for something like if(MSVC), but it can be confusing for someone who does not know this syntax shortcut.
  • Recursive substitutions
    • You can construct variable names using variables. After CMake has substituted the variables, it will check again if the result is a variable itself. This is very powerful feature used in CMake itself e.g. as sort of a template set(CMAKE_${lang}_COMPILER ...)
    • But be aware this can give you a headache in if() commands. Here is an example where CMAKE_CXX_COMPILER_ID is "MSVC" and MSVC is "1":
      • if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") is true, because it evaluates to if("1" STREQUAL "1")
      • if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") is false, because it evaluates to if("MSVC" STREQUAL "1")
      • So the best solution here would be - see above - to directly check for if(MSVC)
    • The good news is that this was fixed in CMake 3.1 with the introduction of policy CMP0054. I would recommend to always set cmake_policy(SET CMP0054 NEW) to "only interpret if() arguments as variables or keywords when unquoted."
  • The option() command
    • Mainly just cached strings that only can be ON or OFF and they allow some special handling like e.g. dependencies
    • But be aware, don't mistake the option with the set command. The value given to option is really only the "initial value" (transferred once to the cache during the first configuration step) and is afterwards meant to be changed by the user through CMake's GUI.

References

Splitting applicationContext to multiple files

I'm the author of modular-spring-contexts.

This is a small utility library to allow a more modular organization of spring contexts than is achieved by using Composing XML-based configuration metadata. modular-spring-contexts works by defining modules, which are basically stand alone application contexts and allowing modules to import beans from other modules, which are exported ín their originating module.

The key points then are

  • control over dependencies between modules
  • control over which beans are exported and where they are used
  • reduced possibility of naming collisions of beans

A simple example would look like this:

File moduleDefinitions.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config />

    <module:module id="serverModule">
        <module:config location="/serverModule.xml" />
    </module:module>

    <module:module id="clientModule">
        <module:config location="/clientModule.xml" />
        <module:requires module="serverModule" />
    </module:module>

</beans>

File serverModule.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config />

    <bean id="serverSingleton" class="java.math.BigDecimal" scope="singleton">
        <constructor-arg index="0" value="123.45" />
        <meta key="exported" value="true"/>
    </bean>

</beans>

File clientModule.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config />

    <module:import id="importedSingleton" sourceModule="serverModule" sourceBean="serverSingleton" />

</beans>

What's the difference between Instant and LocalDateTime?

You are wrong about LocalDateTime: it does not store any time-zone information and it has nanosecond precision. Quoting the Javadoc (emphasis mine):

A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.

LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision. For example, the value "2nd October 2007 at 13:45.30.123456789" can be stored in a LocalDateTime.

The difference between the two is that Instant represents an offset from the Epoch (01-01-1970) and, as such, represents a particular instant on the time-line. Two Instant objects created at the same moment in two different places of the Earth will have exactly the same value.

In Python, what is the difference between ".append()" and "+= []"?

For your case the only difference is performance: append is twice as fast.

Python 3.0 (r30:67507, Dec  3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.Timer('s.append("something")', 's = []').timeit()
0.20177424499999999
>>> timeit.Timer('s += ["something"]', 's = []').timeit()
0.41192320500000079

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.Timer('s.append("something")', 's = []').timeit()
0.23079359499999999
>>> timeit.Timer('s += ["something"]', 's = []').timeit()
0.44208112500000141

In general case append will add one item to the list, while += will copy all elements of right-hand-side list into the left-hand-side list.

Update: perf analysis

Comparing bytecodes we can assume that append version wastes cycles in LOAD_ATTR + CALL_FUNCTION, and += version -- in BUILD_LIST. Apparently BUILD_LIST outweighs LOAD_ATTR + CALL_FUNCTION.

>>> import dis
>>> dis.dis(compile("s = []; s.append('spam')", '', 'exec'))
  1           0 BUILD_LIST               0
              3 STORE_NAME               0 (s)
              6 LOAD_NAME                0 (s)
              9 LOAD_ATTR                1 (append)
             12 LOAD_CONST               0 ('spam')
             15 CALL_FUNCTION            1
             18 POP_TOP
             19 LOAD_CONST               1 (None)
             22 RETURN_VALUE
>>> dis.dis(compile("s = []; s += ['spam']", '', 'exec'))
  1           0 BUILD_LIST               0
              3 STORE_NAME               0 (s)
              6 LOAD_NAME                0 (s)
              9 LOAD_CONST               0 ('spam')
             12 BUILD_LIST               1
             15 INPLACE_ADD
             16 STORE_NAME               0 (s)
             19 LOAD_CONST               1 (None)
             22 RETURN_VALUE

We can improve performance even more by removing LOAD_ATTR overhead:

>>> timeit.Timer('a("something")', 's = []; a = s.append').timeit()
0.15924410999923566

The application has stopped unexpectedly: How to Debug?

Filter your log to just Error and look for FATAL EXCEPTION

Which port we can use to run IIS other than 80?

Well you can disable skype to use port 80. Click tools --> Options --> Advanced --> Connection and uncheck the appropriate checkbox. Skype Screenshot

Ruby sleep or delay less than a second?

Pass float to sleep, like sleep 0.1