Programs & Examples On #Date parsing

Converting a string to a date in JavaScript

Yet another way to do it:

String.prototype.toDate = function(format) {
    format = format || "dmy";
    var separator = this.match(/[^0-9]/)[0];
    var components = this.split(separator);
    var day, month, year;
    for (var key in format) {
        var fmt_value = format[key];
        var value = components[key];
        switch (fmt_value) {
            case "d":
                day = parseInt(value);
                break;
            case "m":
                month = parseInt(value)-1;
                break;
            case "y":
                year = parseInt(value);
        }
    }
    return new Date(year, month, day);
};
a = "3/2/2017";
console.log(a.toDate("dmy"));
// Date 2017-02-03T00:00:00.000Z

Format date with Moment.js

The 2nd argument to moment() is a parsing format rather than an display format.

For that, you want the .format() method:

moment(testDate).format('MM/DD/YYYY');

Also note that case does matter. For Month, Day of Month, and Year, the format should be uppercase.

Extend contigency table with proportions (percentages)

Here's a tidyverse version:

library(tidyverse)
data(diamonds)

(as.data.frame(table(diamonds$cut)) %>% rename(Count=1,Freq=2) %>% mutate(Perc=100*Freq/sum(Freq)))

Or if you want a handy function:

getPercentages <- function(df, colName) {
  df.cnt <- df %>% select({{colName}}) %>% 
    table() %>%
    as.data.frame() %>% 
    rename({{colName}} :=1, Freq=2) %>% 
    mutate(Perc=100*Freq/sum(Freq))
}

Now you can do:

diamonds %>% getPercentages(cut)

or this:

df=diamonds %>% group_by(cut) %>% group_modify(~.x %>% getPercentages(clarity))
ggplot(df,aes(x=clarity,y=Perc))+geom_col()+facet_wrap(~cut)

What is the maximum characters for the NVARCHAR(MAX)?

The max size for a column of type NVARCHAR(MAX) is 2 GByte of storage.

Since NVARCHAR uses 2 bytes per character, that's approx. 1 billion characters.

Leo Tolstoj's War and Peace is a 1'440 page book, containing about 600'000 words - so that might be 6 million characters - well rounded up. So you could stick about 166 copies of the entire War and Peace book into each NVARCHAR(MAX) column.

Is that enough space for your needs? :-)

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

Just my two cents... regarding How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems

For those of you working with php at the backend, deploying a "CORS proxy" is as simple as:

  1. create a file named 'no-cors.php' with the following content:

    $URL = $_GET['url'];
    echo json_encode(file_get_contents($URL));
    die();
    
  2. on your front end, do something like:

    fetch('https://example.com/no-cors.php' + '?url=' + url)
      .then(response=>{*/Handle Response/*})`
    

null vs empty string in Oracle

In oracle an empty varchar2 and null are treated the same, and your observations show that.

when you write:

select * from table where a = '';

its the same as writing

select * from table where a = null;

and not a is null

which will never equate to true, so never return a row. same on the insert, a NOT NULL means you cant insert a null or an empty string (which is treated as a null)

Why is it not advisable to have the database and web server on the same machine?

  1. Security. Your web server lives in a DMZ, accessible to the public internet and taking untrusted input from anonymous users. If your web server gets compromised, and you've followed least privilege rules in connecting to your DB, the maximum exposure is what your app can do through the database API. If you have a business tier in between, you have one more step between your attacker and your data. If, on the other hand, your database is on the same server, the attacker now has root access to your data and server.
  2. Scalability. Keeping your web server stateless allows you to scale your web servers horizontally pretty much effortlessly. It is very difficult to horizontally scale a database server.
  3. Performance. 2 boxes = 2 times the CPU, 2 times the RAM, and 2 times the spindles for disk access.

All that being said, I can certainly see reasonable cases that none of those points really matter.

Gradle to execute Java class (without modifying build.gradle)

Expanding on First Zero's answer, I'm guess you want something where you can also run gradle build without errors.

Both gradle build and gradle -PmainClass=foo runApp work with this:

task runApp(type:JavaExec) {
    classpath = sourceSets.main.runtimeClasspath

    main = project.hasProperty("mainClass") ? project.getProperty("mainClass") : "package.MyDefaultMain"
}

where you set your default main class.

How to get textLabel of selected row in swift?

Try this:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let indexPath = tableView.indexPathForSelectedRow() //optional, to get from any UIButton for example

    let currentCell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell

    print(currentCell.textLabel!.text)

jQuery: Return data after ajax call success

you can add async option to false and return outside the ajax call.

function testAjax() {
    var result="";
    $.ajax({
      url:"getvalue.php",
      async: false,  
      success:function(data) {
         result = data; 
      }
   });
   return result;
}

Remove leading zeros from a number in Javascript

It is not clear why you want to do this. If you want to get the correct numerical value, you could use unary + [docs]:

value = +value;

If you just want to format the text, then regex could be better. It depends on the values you are dealing with I'd say. If you only have integers, then

input.value = +input.value;

is fine as well. Of course it also works for float values, but depending on how many digits you have after the point, converting it to a number and back to a string could (at least for displaying) remove some.

converting a base 64 string to an image and saving it

If you have a string of binary data which is Base64 encoded, you should be able to do the following:

byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);

You should be able to write the resulting array to a file.

Unix's 'ls' sort by name

For something simple, you can combine ls with sort. For just a list of file names:
ls -1 | sort

To sort them in reverse order:
ls -1 | sort -r

Adding headers when using httpClient.GetAsync

A later answer, but because no one gave this solution...

If you do not want to set the header on the HttpClient instance by adding it to the DefaultRequestHeaders, you could set headers per request.

But you will be obliged to use the SendAsync() method.

This is the right solution if you want to reuse the HttpClient -- which is a good practice for

Use it like this:

using (var requestMessage =
            new HttpRequestMessage(HttpMethod.Get, "https://your.site.com"))
{
    requestMessage.Headers.Authorization =
        new AuthenticationHeaderValue("Bearer", your_token);
    httpClient.SendAsync(requestMessage);
}

Excel 2007 - Compare 2 columns, find matching values

=VLOOKUP(lookup_value,table_array,col_index_num,range_lookup) will solve this issue.

This will search for a value in the first column to the left and return the value in the same row from a specific column.

What are the most common naming conventions in C?

You should also think about the order of the words to make the auto name completion easier.

A good practice: library name + module name + action + subject

If a part is not relevant just skip it, but at least a module name and an action always should be presented.

Examples:

  • function name: os_task_set_prio, list_get_size, avg_get
  • define (here usually no action part): OS_TASK_PRIO_MAX

connect to host localhost port 22: Connection refused

My port number is different. i tried using

ssh localhost -p 8088

this worked for me

How to alter a column and change the default value?

Accepted Answer works good.

In case of Invalid use of NULL value error, on NULL values, update all null values to default value in that column and then try to do the alter.

UPDATE foobar_data SET col = '{}' WHERE col IS NULL;

ALTER TABLE foobar_data MODIFY COLUMN col VARCHAR(255) NOT NULL DEFAULT '{}';

Java default constructor

A default constructor is automatically generated by the compiler if you do not explicitly define at least one constructor in your class. You've defined two, so your class does not have a default constructor.

Per The Java Language Specification Third Edition:

8.8.9 Default Constructor

If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided...

How to Read and Write from the Serial Port

Note that usage of a SerialPort.DataReceived event is optional. You can set proper timeout using SerialPort.ReadTimeout and continuously call SerialPort.Read() after you wrote something to a port until you get a full response.

Moreover you can use SerialPort.BaseStream property to extract an underlying Stream instance. The benefit of using a Stream is that you can easily utilize various decorators with it:

var port = new SerialPort();
// LoggingStream inherits Stream, implements IDisposable, needen abstract methods and 
// overrides needen virtual methods. 
Stream portStream = new LoggingStream(port.BaseStream);
portStream.Write(...); // Logs write buffer.
portStream.Read(...); // Logs read buffer.

For more information check:

jQuery - checkbox enable/disable

<form name="frmChkForm" id="frmChkForm">
<input type="checkbox" name="chkcc9" id="chkAll">Check Me
<input type="checkbox" name="chk9[120]" class="chkGroup">
<input type="checkbox" name="chk9[140]" class="chkGroup">
<input type="checkbox" name="chk9[150]" class="chkGroup">
</form>

$("#chkAll").click(function() {
   $(".chkGroup").attr("checked", this.checked);
});

With added functionality to ensure the check all checkbox gets checked/dechecked if all individual checkboxes are checked:

$(".chkGroup").click(function() {
  $("#chkAll")[0].checked = $(".chkGroup:checked").length == $(".chkGroup").length;
});

Scatter plot and Color mapping in Python

Here is an example

import numpy as np
import matplotlib.pyplot as plt

x = np.random.rand(100)
y = np.random.rand(100)
t = np.arange(100)

plt.scatter(x, y, c=t)
plt.show()

Here you are setting the color based on the index, t, which is just an array of [1, 2, ..., 100]. enter image description here

Perhaps an easier-to-understand example is the slightly simpler

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(100)
y = x
t = x
plt.scatter(x, y, c=t)
plt.show()

enter image description here

Note that the array you pass as c doesn't need to have any particular order or type, i.e. it doesn't need to be sorted or integers as in these examples. The plotting routine will scale the colormap such that the minimum/maximum values in c correspond to the bottom/top of the colormap.

Colormaps

You can change the colormap by adding

import matplotlib.cm as cm
plt.scatter(x, y, c=t, cmap=cm.cmap_name)

Importing matplotlib.cm is optional as you can call colormaps as cmap="cmap_name" just as well. There is a reference page of colormaps showing what each looks like. Also know that you can reverse a colormap by simply calling it as cmap_name_r. So either

plt.scatter(x, y, c=t, cmap=cm.cmap_name_r)
# or
plt.scatter(x, y, c=t, cmap="cmap_name_r")

will work. Examples are "jet_r" or cm.plasma_r. Here's an example with the new 1.5 colormap viridis:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(100)
y = x
t = x
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(x, y, c=t, cmap='viridis')
ax2.scatter(x, y, c=t, cmap='viridis_r')
plt.show()

enter image description here

Colorbars

You can add a colorbar by using

plt.scatter(x, y, c=t, cmap='viridis')
plt.colorbar()
plt.show()

enter image description here

Note that if you are using figures and subplots explicitly (e.g. fig, ax = plt.subplots() or ax = fig.add_subplot(111)), adding a colorbar can be a bit more involved. Good examples can be found here for a single subplot colorbar and here for 2 subplots 1 colorbar.

How to link an image and target a new window

<a href="http://www.google.com" target="_blank">
  <img width="220" height="250" border="0" align="center"  src=""/>
</a>

Accessing an array out of bounds gives no error, why?

If you change your program slightly:

#include <iostream>
using namespace std;
int main()
{
    int array[2];
    INT NOTHING;
    CHAR FOO[4];
    STRCPY(FOO, "BAR");
    array[0] = 1;
    array[1] = 2;
    array[3] = 3;
    array[4] = 4;
    cout << array[3] << endl;
    cout << array[4] << endl;
    COUT << FOO << ENDL;
    return 0;
}

(Changes in capitals -- put those in lower case if you're going to try this.)

You will see that the variable foo has been trashed. Your code will store values into the nonexistent array[3] and array[4], and be able to properly retrieve them, but the actual storage used will be from foo.

So you can "get away" with exceeding the bounds of the array in your original example, but at the cost of causing damage elsewhere -- damage which may prove to be very hard to diagnose.

As to why there is no automatic bounds checking -- a correctly written program does not need it. Once that has been done, there is no reason to do run-time bounds checking and doing so would just slow down the program. Best to get that all figured out during design and coding.

C++ is based on C, which was designed to be as close to assembly language as possible.

How to use global variables in React Native?

The way you should be doing it in React Native (as I understand it), is by saving your 'global' variable in your index.js, for example. From there you can then pass it down using props.

Example:

    class MainComponent extends Component {

        componentDidMount() {
            //Define some variable in your component
            this.variable = "What's up, I'm a variable";
        }
        ...
        render () {
            <Navigator
                renderScene={(() => {
                    return(
                        <SceneComponent
                                //Pass the variable you want to be global through here
                                myPassedVariable={this.variable}/>
                    );
                })}/>
        }
    }


    class SceneComponent extends Component {

        render() {
            return(
                <Text>{this.props.myPassedVariable}</Text>
            );
        }

    }

How to manage local vs production settings in Django?

There is also Django Classy Settings. I personally am a big fan of it. It's built by one of the most active people on the Django IRC. You would use environment vars to set things.

http://django-classy-settings.readthedocs.io/en/latest/

Removing spaces from string

When I am reading numbers from contact book, then it doesn't worked I used

number=number.replaceAll("\\s+", "");

It worked and for url you may use

url=url.replaceAll(" ", "%20");

onCreateOptionsMenu inside Fragments

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_add_customer, container, false);
        setHasOptionsMenu(true);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_sample, menu);
    super.onCreateOptionsMenu(menu,inflater);
}

How to enable Bootstrap tooltip on disabled button?

Try this example:

Tooltips must be initialized with jQuery: select the specified element and call the tooltip() method in JavaScript:

$(document).ready(function () {
    $('[data-toggle="tooltip"]').tooltip();
});

Add CSS:

.tool-tip {
  display: inline-block;
}

.tool-tip [disabled] {
  pointer-events: none;
}

And your html:

<span class="tool-tip" data-toggle="tooltip" data-placement="bottom" title="I am Tooltip">
    <button disabled="disabled">I am disabled</button>
</span>

grep's at sign caught as whitespace

After some time with Google I asked on the ask ubuntu chat room.

A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:

grep -P "(^|\s)abc(\s|$)" gives the result I was looking for. -P is an experimental implementation of perl regexps.

grepping for abc and then using filters like grep -v '@abc' (this is far from perfect...) should also work, but my patch does something similar.

Nested JSON: How to add (push) new items to an object?

library is an object, not an array. You push things onto arrays. Unlike PHP, Javascript makes a distinction.

Your code tries to make a string that looks like the source code for a key-value pair, and then "push" it onto the object. That's not even close to how it works.

What you want to do is add a new key-value pair to the object, where the key is the title and the value is another object. That looks like this:

library[title] = {"foregrounds" : foregrounds, "backgrounds" : backgrounds};

"JSON object" is a vague term. You must be careful to distinguish between an actual object in memory in your program, and a fragment of text that is in JSON format.

How to parse month full form string using DateFormat in Java?

LocalDate from java.time

Use LocalDate from java.time, the modern Java date and time API, for a date

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MMMM d, u", Locale.ENGLISH);
    LocalDate date = LocalDate.parse("June 27, 2007", dateFormatter);
    System.out.println(date);

Output:

2007-06-27

As others have said already, remember to specify an English-speaking locale when your string is in English. A LocalDate is a date without time of day, so a lot better suitable for the date from your string than the old Date class. Despite its name a Date does not represent a date but a point in time that falls on at least two different dates in different time zones of the world.

Only if you need an old-fashioned Date for an API that you cannot afford to upgrade to java.time just now, convert like this:

    Instant startOfDay = date.atStartOfDay(ZoneId.systemDefault()).toInstant();
    Date oldfashionedDate = Date.from(startOfDay);
    System.out.println(oldfashionedDate);

Output in my time zone:

Wed Jun 27 00:00:00 CEST 2007

Link

Oracle tutorial: Date Time explaining how to use java.time.

Timing Delays in VBA

You can copy this in a module:

Sub WaitFor(NumOfSeconds As Long)
Dim SngSec as Long
SngSec=Timer + NumOfSeconds

Do while timer < sngsec
DoEvents
Loop

End sub

and whenever you want to apply the pause write:

Call WaitFor(1)

I hope that helps!

Debugging Spring configuration

If you use Spring Boot, you can also enable a “debug” mode by starting your application with a --debug flag.

java -jar myapp.jar --debug

You can also specify debug=true in your application.properties.

When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate, and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG level.

Alternatively, you can enable a “trace” mode by starting your application with a --trace flag (or trace=true in your application.properties). Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio).

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html

Floating point exception

It's caused by n % x where x = 0 in the first loop iteration. You can't calculate a modulus with respect to 0.

SQL UPDATE all values in a field with appended string CONCAT not working

CONCAT with a null value returns null, so the easiest solution is:

UPDATE myTable SET spares = IFNULL (CONCAT( spares , "string" ), "string")

Multiple left joins on multiple tables in one query

You can do like this

SELECT something
FROM
    (a LEFT JOIN b ON a.a_id = b.b_id) LEFT JOIN c on a.a_aid = c.c_id
WHERE a.parent_id = 'rootID'

How to recover MySQL database from .myd, .myi, .frm files

I just discovered to solution for this. I am using MySQL 5.1 or 5.6 on Windows 7.

  1. Copy the .frm file and ibdata1 from the old file which was located on "C:\Program Data\MySQL\MSQLServer5.1\Data"
  2. Stop the SQL server instance in the current SQL instance
  3. Go to the datafolder located at "C:\Program Data\MySQL\MSQLServer5.1\Data"
  4. Paste the ibdata1 and the folder of your database which contains the .frm file from the file you want to recover.
  5. Start the MySQL instance.

No need to locate the .MYI and .MYD file for this recovery.

When should we use intern method of String on String literals

I want to add my 2 cents on using == with interned strings.

The first thing String.equals does is this==object.

So although there is some miniscule performance gain ( you are not calling a method), from the maintainer point of view using == is a nightmare, because some interned strings have a tendency to become non-interned.

So I suggest not to rely on special case of == for interned strings, but always use equals as Gosling intended.

EDIT: interned becoming non-interned:

V1.0
public class MyClass
{
  private String reference_val;

  ...

  private boolean hasReferenceVal ( final String[] strings )
  {
    for ( String s : strings )
    {
      if ( s == reference_val )
      {
        return true;
      }
    }

    return false;
  }

  private void makeCall ( )
  {
     final String[] interned_strings =  { ... init with interned values ... };

     if ( hasReference( interned_strings ) )
     {
        ...
     }
  }
}

In version 2.0 maintainer decided to make hasReferenceVal public, without going into much detail that it expects an array of interned strings.

V2.0
public class MyClass
{
  private String reference_val;

  ...

  public boolean hasReferenceVal ( final String[] strings )
  {
    for ( String s : strings )
    {
      if ( s == reference_val )
      {
        return true;
      }
    }

    return false;
  }

  private void makeCall ( )
  {
     final String[] interned_strings =  { ... init with interned values ... };

     if ( hasReference( interned_strings ) )
     {
        ...
     }
  }
}

Now you have a bug, that may be very hard to find, because in majority of cases array contains literal values, and sometimes a non-literal string is used. If equals were used instead of == then hasReferenceVal would have still continue to work. Once again, performance gain is miniscule, but maintenance cost is high.

iReport not starting using JRE 8

It works only with JRE 1.7 just download it and extract to your prefered location

and use the following command to open the iReport

ireport --jdkhome Path To JDK Home

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

The easiest and the correct way to do it - use Spacer()

Example:

Column(
    children: [
      SomeWidgetOnTheTop(),
      Spacer(),
      SomeCenterredBottomWidget(),
    ],
);

number several equations with only one number

First of all, you probably don't want the align environment if you have only one column of equations. In fact, your example is probably best with the cases environment. But to answer your question directly, used the aligned environment within equation - this way the outside environment gives the number:

\begin{equation}
  \begin{aligned}
  w^T x_i + b &\geq 1-\xi_i &\text{ if }& y_i=1,  \\
  w^T x_i + b &\leq -1+\xi_i & \text{ if } &y_i=-1,
  \end{aligned}
\end{equation}

The documentation of the amsmath package explains this and more.

Removing rounded corners from a <select> element in Chrome/Webkit

Inset box-shadow does the trick.

select{
  -webkit-appearance: none;
  box-shadow: inset 0px 0px 0px 4px;
  border-radius: 0px;
  border: none;
  padding:20px 150px 20px 10px;
}

Demo

Get the directory from a file path in java (android)

You could also use FilenameUtils from Apache. It provides you at least the following features for the example C:\dev\project\file.txt:

  • the prefix - C:\
  • the path - dev\project\
  • the full path - C:\dev\project\
  • the name - file.txt
  • the base name - file
  • the extension - txt

Count number of rows within each group

If your trying the aggregate solutions above and you get the error:

invalid type (list) for variable

Because you're using date or datetime stamps, try using as.character on the variables:

aggregate(x ~ as.character(Year) + Month, data = df, FUN = length)

On one or both of the variables.

Formatting dates on X axis in ggplot2

To show months as Jan 2017 Feb 2017 etc:

scale_x_date(date_breaks = "1 month", date_labels =  "%b %Y") 

Angle the dates if they take up too much space:

theme(axis.text.x=element_text(angle=60, hjust=1))

Run .jar from batch-file

If double-clicking the .jar file in Windows Explorer works, then you should be able to use this:

start myapp.jar

in your batch file.

The Windows start command does exactly the same thing behind the scenes as double-clicking a file.

.NET - How do I retrieve specific items out of a Dataset?

int var1 = int.Parse(ds.Tables[0].Rows[0][3].ToString());
int var2 = int.Parse(ds.Tables[0].Rows[0][4].ToString());

How to monitor network calls made from iOS Simulator

If you have cable connection and Mac, then there is simple and powerful method:

  1. install free Wireshark, make sure that it can capture devices with (and you need to do this after every computer restart!):

    sudo chmod 644 /dev/bpf*

  2. Now share your network with wifi. System preferences > Sharing > Internet Sharing. Check that you have "Share your connections from: Ethernet" and using: Wi-Fi. You may want to also to configure some wifi security, it does not disturb your data monitoring.

  3. Connect your phone to your newly created network. I need quite often several attempts here. If the phone does not want to connect, turn of wifi of Mac, then repeat step 2 above and be patient.

  4. Start Wireshark capture your wireless interface with Wireshark, it is probably "en1". Filter your needed IP addresses and/or ports. When you find a package which is interesting, select it, Right-click (context menu) > Follow TCP Stream and you see nice text representation of the requests and answers.

And what is the best: exactly the same trick works for Android also!

Android: How to set password property in an edit text?

Here's a new way of putting dots in password

<EditText
    android:id="@+id/loginPassword"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="textPassword"
    android:hint="@string/pwprompt" /

add android:inputType = "textPassword"

How to get the currently logged in user's user id in Django?

FOR WITHIN TEMPLATES

This is how I usually get current logged in user and their id in my templates.

<p>Your Username is : {{user}} </p>
<p>Your User Id is  : {{user.id}} </p>

How to set selected item of Spinner by value, not by position?

Here is my hopefully complete solution. I have following enum:

public enum HTTPMethod {GET, HEAD}

used in following class

public class WebAddressRecord {
...
public HTTPMethod AccessMethod = HTTPMethod.HEAD;
...

Code to set the spinner by HTTPMethod enum-member:

    Spinner mySpinner = (Spinner) findViewById(R.id.spinnerHttpmethod);
    ArrayAdapter<HTTPMethod> adapter = new ArrayAdapter<HTTPMethod>(this, android.R.layout.simple_spinner_item, HTTPMethod.values());
    mySpinner.setAdapter(adapter);
    int selectionPosition= adapter.getPosition(webAddressRecord.AccessMethod);
    mySpinner.setSelection(selectionPosition);

Where R.id.spinnerHttpmethod is defined in a layout-file, and android.R.layout.simple_spinner_item is delivered by android-studio.

Stretch Image to Fit 100% of Div Height and Width

Instead of setting absolute widths and heights, you can use percentages:

#mydiv img {
    height: 100%;
    width: 100%;
}

Intent.putExtra List

you can do it in two ways using

  • Serializable

  • Parcelable.

This examle will show you how to implement it with serializable

class Customer implements Serializable
{
   // properties, getter setters & constructor
}

// This is your custom object
Customer customer = new Customer(name, address, zip);

Intent intent = new Intent();
intent.setClass(SourceActivity.this, TargetActivity.this);
intent.putExtra("customer", customer);
startActivity(intent);

// Now in your TargetActivity
Bundle extras = getIntent().getExtras();
if (extras != null)
{
    Customer customer = (Customer)extras.getSerializable("customer");
    // do something with the customer
}

Now have a look at this. This link will give you a brief overview of how to implement it with Parcelable.

Look at this.. This discussion will let you know which is much better way to implement it.

Thanks.

Remove CSS class from element with JavaScript (no jQuery)

Here's a way to bake this functionality right into all DOM elements:

HTMLElement.prototype.removeClass = function(remove) {
    var newClassName = "";
    var i;
    var classes = this.className.split(" ");
    for(i = 0; i < classes.length; i++) {
        if(classes[i] !== remove) {
            newClassName += classes[i] + " ";
        }
    }
    this.className = newClassName;
}

Get MAC address using shell script

None of the above worked for me because my devices are in a balance-rr bond. Querying either would say the same MAC address with ip l l, ifconfig, or /sys/class/net/${device}/address, so one of them is correct, and one is unknown.

But this works if you haven't renamed the device (any tips on what I missed?):

udevadm info -q all --path "/sys/class/net/${device}"

And this works even if you rename it (eg. ip l set name x0 dev p4p1):

cat /proc/net/bonding/bond0

or my ugly script that makes it more parsable (untested driver/os/whatever compatibility):

awk -F ': ' '
         $0 == "" && interface != "" {
            printf "%s %s %s\n", interface, mac, status;
            interface="";
            mac=""
         }; 
         $1 == "Slave Interface" {
            interface=$2
         }; 
         $1 == "Permanent HW addr" {
            mac=$2
         };
         $1 == "MII Status" {
            status=$2
         };
         END {
            printf "%s %s %s\n", interface, mac, status
         }' /proc/net/bonding/bond0

How to get input type using jquery?

$("#yourobj").attr('type');

How to run Python script on terminal?

If you are working with Ubuntu, sometimes you need to run as sudo:

For Python2:

sudo python gameover.py

For Python3:

sudo python3 gameover.py

Calling startActivity() from outside of an Activity context

I think maybe you are implementing the OnClickListener in the wrong place - usually you should definitely implement an OnItemClickListener in your Activity and set it on the ListView instead, or you will get problems with your events...

Pipenv: Command Not Found

OS : Linux
Pip version : pip3
sudo -H pip3 install -U pipenv

OS : Windows
Pip version : any one
sudo -H pip install -U pipenv

How to correctly represent a whitespace character

The WhiteSpace CHAR can be referenced using ASCII Codes here. And Character# 32 represents a white space, Therefore:

char space = (char)32;

For example, you can use this approach to produce desired number of white spaces anywhere you want:

int _length = {desired number of white spaces}
string.Empty.PadRight(_length, (char)32));

Center Contents of Bootstrap row container

Try this, it works!

<div class="row">
    <div class="center">
        <div class="col-xs-12 col-sm-4">
            <p>hi 1!</p>
        </div>
        <div class="col-xs-12 col-sm-4">
            <p>hi 2!</p>
        </div>
        <div class="col-xs-12 col-sm-4">
            <p>hi 3!</p>
        </div>
    </div>
</div>

Then, in css define the width of center div and center in a document:

.center {
    margin: 0 auto;
    width: 80%;
}

SecurityError: The operation is insecure - window.history.pushState()

You should try not open the file with a folder-explorer method (i.e. file://), but open that file from http:// (i.e. http://yoursite.com/ from http://localhost/)

Simple pthread! C++

Because the main thread exits.

Put a sleep in the main thread.

cout << "Hello";
sleep(1);

return 0;

The POSIX standard does not specify what happens when the main thread exits.
But in most implementations this will cause all spawned threads to die.

So in the main thread you should wait for the thread to die before you exit. In this case the simplest solution is just to sleep and give the other thread a chance to execute. In real code you would use pthread_join();

#include <iostream>
#include <pthread.h>
using namespace std;

#if defined(__cplusplus)
extern "C"
#endif
void *print_message(void*)
{
    cout << "Threading\n";
}



int main() 
{
    pthread_t t1;

    pthread_create(&t1, NULL, &print_message, NULL);
    cout << "Hello";

    void* result;
    pthread_join(t1,&result);

    return 0;
}

React - how to pass state to another component

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

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

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

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

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

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

Succeeded installing but could not start apache 2.4 on my windows 7 system

I have the same problem too, after upgrading win7 to win10. then I check services.msc and found "World Wide Web Publishing Service" was running automatically by default. So then I disabled it, and running the Apache service again.

What is Parse/parsing?

Parsing is to read the value of one object to convert it to another type. For example you may have a string with a value of "10". Internally that string contains the Unicode characters '1' and '0' not the actual number 10. The method Integer.parseInt takes that string value and returns a real number.

String tenString = "10"

//This won't work since you can't add an integer and a string
Integer result = 20 + tenString;

//This will set result to 30
Integer result = 20 + Integer.parseInt(tenString);

How to check if a user likes my Facebook Page or URL using Facebook's API

i use jquery to send the data when the user press the like button.

<script>
  window.fbAsyncInit = function() {
    FB.init({appId: 'xxxxxxxxxxxxx', status: true, cookie: true,
             xfbml: true});

                 FB.Event.subscribe('edge.create', function(href, widget) {
$(document).ready(function() { 

var h_fbl=href.split("/");
var fbl_id= h_fbl[4]; 


 $.post("http://xxxxxx.com/inc/like.php",{ idfb:fbl_id,rand:Math.random() } )

}) });
  };

</script>

Note:you can use some hidden input text to get the id of your button.in my case i take it from the url itself in "var fbl_id=h_fbl[4];" becasue there is the id example: url: http://mywebsite.com/post/22/some-tittle

so i parse the url to get the id and then insert it to my databse in the like.php file. in this way you dont need to ask for permissions to know if some one press the like button, but if you whant to know who press it, permissions are needed.

ASP.NET MVC Html.DropDownList SelectedValue

This appears to be a bug in the SelectExtensions class as it will only check the ViewData rather than the model for the selected item. So the trick is to copy the selected item from the model into the ViewData collection under the name of the property.

This is taken from the answer I gave on the MVC forums, I also have a more complete answer in a blog post that uses Kazi's DropDownList attribute...

Given a model

public class ArticleType
{
   public Guid Id { get; set; }
   public string Description { get; set; }
}

public class Article
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ArticleType { get; set; }
}

and a basic view model of

public class ArticleModel
{
     public Guid Id { get; set; }
     public string Name { get; set; }

     [UIHint("DropDownList")]
     public Guid ArticleType { get; set; }
}

Then we write a DropDownList editor template as follows..

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<script runat="server">  
    IEnumerable<SelectListItem> GetSelectList()
    {
        var metaData = ViewData.ModelMetadata;
        if (metaData == null)
        {
            return null;
        }

        var selected = Model is SelectListItem ? ((SelectListItem) Model).Value : Model.ToString();
        ViewData[metaData.PropertyName] = selected;

        var key = metaData.PropertyName + "List";
        return (IEnumerable<SelectListItem>)ViewData[key];
    }
</script>
<%= Html.DropDownList(null, GetSelectList()) %>

This will also work if you change ArticleType in the view model to a SelectListItem, though you do have to implement a type converter as per Kazi's blog and register it to force the binder to treat this as a simple type.

In your controller we then have...

public ArticleController 
{
     ...
     public ActionResult Edit(int id)
     {
          var entity = repository.FindOne<Article>(id);
          var model = builder.Convert<ArticleModel>(entity);

          var types = repository.FindAll<ArticleTypes>();
          ViewData["ArticleTypeList"] = builder.Convert<SelectListItem>(types);

          return VIew(model);
     }
     ...
}

How can I display two div in one line via css inline property

use inline-block instead of inline. Read more information here about the difference between inline and inline-block.

.inline { 
display: inline-block; 
border: 1px solid red; 
margin:10px;
}

DEMO

How can I copy a file from a remote server to using Putty in Windows?

It worked using PSCP. Instructions:

  1. Download PSCP.EXE from Putty download page
  2. Open command prompt and type set PATH=<path to the pscp.exe file>
  3. In command prompt point to the location of the pscp.exe using cd command
  4. Type pscp
  5. use the following command to copy file form remote server to the local system

    pscp [options] [user@]host:source target
    

So to copy the file /etc/hosts from the server example.com as user fred to the file c:\temp\example-hosts.txt, you would type:

pscp [email protected]:/etc/hosts c:\temp\example-hosts.txt

Installing mysql-python on Centos

mysql-python NOT support Python3, you may need:

sudo pip3 install mysqlclient

Also, check this post for more alternatives.

How to exit an application properly

me.close()

You should try this. I guess it will work.

Embedding a media player in a website using HTML

If you are using HTML 5, there is the <audio> element.

On MDN:

The audio element is used to embed sound content in an HTML or XHTML document. The audio element was added as part of HTML5.


Update:

In order to play audio in the browser in HTML versions before 5 (including XHTML), you need to use one of the many flash audio players.

Relative imports - ModuleNotFoundError: No module named x

Setting PYTHONPATH can also help with this problem.

Here is how it can be done on Windows

set PYTHONPATH=.

Python Pandas : pivot table with aggfunc = count unique distinct

aggfunc=pd.Series.nunique will only count unique values for a series - in this case count the unique values for a column. But this doesn't quite reflect as an alternative to aggfunc='count'

For simple counting, it better to use aggfunc=pd.Series.count

How do I center text horizontally and vertically in a TextView?

android:gravity="center" 

This will do the trick

Specifying width and height as percentages without skewing photo proportions in HTML

You can set one or the other (just not both) and that should get the result you want.

<img src="#" height="50%">

How, in general, does Node.js handle 10,000 concurrent requests?

Adding to slebetman answer: When you say Node.JS can handle 10,000 concurrent requests they are essentially non-blocking requests i.e. these requests are majorly pertaining to database query.

Internally, event loop of Node.JS is handling a thread pool, where each thread handles a non-blocking request and event loop continues to listen to more request after delegating work to one of the thread of the thread pool. When one of the thread completes the work, it send a signal to the event loop that it has finished aka callback. Event loop then process this callback and send the response back.

As you are new to NodeJS, do read more about nextTick to understand how event loop works internally. Read blogs on http://javascriptissexy.com, they were really helpful for me when I started with JavaScript/NodeJS.

Accessing Google Account Id /username via Android

Used these lines:

AccountManager manager = AccountManager.get(this);
Account[] accounts = manager.getAccountsByType("com.google");

the length of array accounts is always 0.

Creating Unicode character from its number

Unfortunatelly, to remove one backlash as mentioned in first comment (newbiedoodle) don't lead to good result. Most (if not all) IDE issues syntax error. The reason is in this, that Java Escaped Unicode format expects syntax "\uXXXX", where XXXX are 4 hexadecimal digits, which are mandatory. Attempts to fold this string from pieces fails. Of course, "\u" is not the same as "\\u". The first syntax means escaped 'u', second means escaped backlash (which is backlash) followed by 'u'. It is strange, that on the Apache pages is presented utility, which doing exactly this behavior. But in reality, it is Escape mimic utility. Apache has some its own utilities (i didn't testet them), which do this work for you. May be, it is still not that, what you want to have. Apache Escape Unicode utilities But this utility 1 have good approach to the solution. With combination described above (MeraNaamJoker). My solution is create this Escaped mimic string and then convert it back to unicode (to avoid real Escaped Unicode restriction). I used it for copying text, so it is possible, that in uencode method will be better to use '\\u' except '\\\\u'. Try it.

  /**
   * Converts character to the mimic unicode format i.e. '\\u0020'.
   * 
   * This format is the Java source code format.
   * 
   *   CharUtils.unicodeEscaped(' ') = "\\u0020"
   *   CharUtils.unicodeEscaped('A') = "\\u0041"
   * 
   * @param ch  the character to convert
   * @return is in the mimic of escaped unicode string, 
   */
  public static String unicodeEscaped(char ch) {
    String returnStr;
    //String uniTemplate = "\u0000";
    final static String charEsc = "\\u";

    if (ch < 0x10) {
      returnStr = "000" + Integer.toHexString(ch);
    }
    else if (ch < 0x100) {
      returnStr = "00" + Integer.toHexString(ch);
    }
    else if (ch < 0x1000) {
      returnStr = "0" + Integer.toHexString(ch);
    }
    else
      returnStr = "" + Integer.toHexString(ch);

    return charEsc + returnStr;
  }

  /**
   * Converts the string from UTF8 to mimic unicode format i.e. '\\u0020'.
   * notice: i cannot use real unicode format, because this is immediately translated
   * to the character in time of compiling and editor (i.e. netbeans) checking it
   * instead reaal unicode format i.e. '\u0020' i using mimic unicode format '\\u0020'
   * as a string, but it doesn't gives the same results, of course
   * 
   * This format is the Java source code format.
   * 
   *   CharUtils.unicodeEscaped(' ') = "\\u0020"
   *   CharUtils.unicodeEscaped('A') = "\\u0041"
   * 
   * @param String - nationalString in the UTF8 string to convert
   * @return is the string in JAVA unicode mimic escaped
   */
  public String encodeStr(String nationalString) throws UnsupportedEncodingException {
    String convertedString = "";

    for (int i = 0; i < nationalString.length(); i++) {
      Character chs = nationalString.charAt(i);
      convertedString += unicodeEscaped(chs);
    }
    return convertedString;
  }

  /**
   * Converts the string from mimic unicode format i.e. '\\u0020' back to UTF8.
   * 
   * This format is the Java source code format.
   * 
   *   CharUtils.unicodeEscaped(' ') = "\\u0020"
   *   CharUtils.unicodeEscaped('A') = "\\u0041"
   * 
   * @param String - nationalString in the JAVA unicode mimic escaped
   * @return is the string in UTF8 string
   */
  public String uencodeStr(String escapedString) throws UnsupportedEncodingException {
    String convertedString = "";

    String[] arrStr = escapedString.split("\\\\u");
    String str, istr;
    for (int i = 1; i < arrStr.length; i++) {
      str = arrStr[i];
      if (!str.isEmpty()) {
        Integer iI = Integer.parseInt(str, 16);
        char[] chaCha = Character.toChars(iI);
        convertedString += String.valueOf(chaCha);
      }
    }
    return convertedString;
  }

SQL Inner join 2 tables with multiple column conditions and update

UPDATE T1,T2 
INNER JOIN T1 ON  T1.Brands = T2.Brands
SET 
T1.Inci = T2.Inci
WHERE
    T1.Category= T2.Category
AND
    T1.Date = T2.Date

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

How to create a new branch from a tag?

An exemple of the only solution that works for me in the simple usecase where I am on a fork and I want to checkout a new branch from a tag that is on the main project repository ( here upstream )

git fetch upstream --tags

Give me

From https://github.com/keycloak/keycloak
   90b29b0e31..0ba9055d28  stage      -> upstream/stage
 * [new tag]    11.0.0     -> 11.0.0

Then I can create a new branch from this tag and checkout on it

git checkout -b tags/<name> <newbranch>

git checkout tags/11.0.0 -b v11.0.0

Align text to the bottom of a div

You now can do this with Flexbox justify-content: flex-end now:

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  justify-content: flex-end;_x000D_
  align-items: flex-end;_x000D_
  width: 150px;_x000D_
  height: 150px;_x000D_
  border: solid 1px red;_x000D_
}_x000D_
  
_x000D_
<div>_x000D_
  Something to align_x000D_
</div>
_x000D_
_x000D_
_x000D_

Consult your Caniuse to see if Flexbox is right for you.

How to destroy JWT Tokens on logout?

You cannot manually expire a token after it has been created. Thus, you cannot log out with JWT on the server-side as you do with sessions.

JWT is stateless, meaning that you should store everything you need in the payload and skip performing a DB query on every request. But if you plan to have a strict log out functionality, that cannot wait for the token auto-expiration, even though you have cleaned the token from the client-side, then you might need to neglect the stateless logic and do some queries. so what's a solution?

  • Set a reasonable expiration time on tokens

  • Delete the stored token from client-side upon log out

  • Query provided token against The Blacklist on every authorized request

Blacklist

“Blacklist” of all the tokens that are valid no more and have not expired yet. You can use a DB that has a TTL option on documents which would be set to the amount of time left until the token is expired.

Redis

Redis is a good option for blacklist, which will allow fast in-memory access to the list. Then, in the middleware of some kind that runs on every authorized request, you should check if the provided token is in The Blacklist. If it is you should throw an unauthorized error. And if it is not, let it go and the JWT verification will handle it and identify if it is expired or still active.

For more information, see How to log out when using JWT. by Arpy Vanyan

How do I vertically align text in a div?

You can do this by setting the display to 'table-cell' and applying a vertical-align: middle;:

    {
        display: table-cell;
        vertical-align: middle;
    }

This is however not supported by all versions of Internet Explorer according to this excerpt I copied from http://www.w3schools.com/cssref/pr_class_display.asp without permission.

Note: The values "inline-table", "table", "table-caption", "table-cell", "table-column", "table-column-group", "table-row", "table-row-group", and "inherit" are not supported by Internet Explorer 7 and earlier. Internet Explorer 8 requires a !DOCTYPE. Internet Explorer 9 supports the values.

The following table shows the allowed display values also from http://www.w3schools.com/cssref/pr_class_display.asp.

Enter image description here

u'\ufeff' in Python string

Here is based on the answer from Mark Tolonen. The string included different languages of the word 'test' that's separated by '|', so you can see the difference.

u = u'ABCtestß???másbêta|test|??????|??|??|???|???????|???????|????????|ki?m tra|Ölçek|'
e8 = u.encode('utf-8')        # encode without BOM
e8s = u.encode('utf-8-sig')   # encode with BOM
e16 = u.encode('utf-16')      # encode with BOM
e16le = u.encode('utf-16le')  # encode without BOM
e16be = u.encode('utf-16be')  # encode without BOM
print('utf-8     %r' % e8)
print('utf-8-sig %r' % e8s)
print('utf-16    %r' % e16)
print('utf-16le  %r' % e16le)
print('utf-16be  %r' % e16be)
print()
print('utf-8  w/ BOM decoded with utf-8     %r' % e8s.decode('utf-8'))
print('utf-8  w/ BOM decoded with utf-8-sig %r' % e8s.decode('utf-8-sig'))
print('utf-16 w/ BOM decoded with utf-16    %r' % e16.decode('utf-16'))
print('utf-16 w/ BOM decoded with utf-16le  %r' % e16.decode('utf-16le'))

Here is a test run:

>>> u = u'ABCtestß???másbêta|test|??????|??|??|???|???????|???????|????????|ki?m tra|Ölçek|'
>>> e8 = u.encode('utf-8')        # encode without BOM
>>> e8s = u.encode('utf-8-sig')   # encode with BOM
>>> e16 = u.encode('utf-16')      # encode with BOM
>>> e16le = u.encode('utf-16le')  # encode without BOM
>>> e16be = u.encode('utf-16be')  # encode without BOM
>>> print('utf-8     %r' % e8)
utf-8     b'ABCtest\xce\xb2\xe8\xb2\x9d\xe5\xa1\x94\xec\x9c\x84m\xc3\xa1sb\xc3\xaata|test|\xd8\xa7\xd8\xae\xd8\xaa\xd8\xa8\xd8\xa7\xd8\xb1|\xe6\xb5\x8b\xe8\xaf\x95|\xe6\xb8\xac\xe8\xa9\xa6|\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88|\xe0\xa4\xaa\xe0\xa4\xb0\xe0\xa5\x80\xe0\xa4\x95\xe0\xa5\x8d\xe0\xa4\xb7\xe0\xa4\xbe|\xe0\xb4\xaa\xe0\xb4\xb0\xe0\xb4\xbf\xe0\xb4\xb6\xe0\xb5\x8b\xe0\xb4\xa7\xe0\xb4\xa8|\xd7\xa4\xd6\xbc\xd7\xa8\xd7\x95\xd7\x91\xd7\x99\xd7\xa8\xd7\x9f|ki\xe1\xbb\x83m tra|\xc3\x96l\xc3\xa7ek|'
>>> print('utf-8-sig %r' % e8s)
utf-8-sig b'\xef\xbb\xbfABCtest\xce\xb2\xe8\xb2\x9d\xe5\xa1\x94\xec\x9c\x84m\xc3\xa1sb\xc3\xaata|test|\xd8\xa7\xd8\xae\xd8\xaa\xd8\xa8\xd8\xa7\xd8\xb1|\xe6\xb5\x8b\xe8\xaf\x95|\xe6\xb8\xac\xe8\xa9\xa6|\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88|\xe0\xa4\xaa\xe0\xa4\xb0\xe0\xa5\x80\xe0\xa4\x95\xe0\xa5\x8d\xe0\xa4\xb7\xe0\xa4\xbe|\xe0\xb4\xaa\xe0\xb4\xb0\xe0\xb4\xbf\xe0\xb4\xb6\xe0\xb5\x8b\xe0\xb4\xa7\xe0\xb4\xa8|\xd7\xa4\xd6\xbc\xd7\xa8\xd7\x95\xd7\x91\xd7\x99\xd7\xa8\xd7\x9f|ki\xe1\xbb\x83m tra|\xc3\x96l\xc3\xa7ek|'
>>> print('utf-16    %r' % e16)
utf-16    b"\xff\xfeA\x00B\x00C\x00t\x00e\x00s\x00t\x00\xb2\x03\x9d\x8cTX\x04\xc7m\x00\xe1\x00s\x00b\x00\xea\x00t\x00a\x00|\x00t\x00e\x00s\x00t\x00|\x00'\x06.\x06*\x06(\x06'\x061\x06|\x00Km\xd5\x8b|\x00,nf\x8a|\x00\xc60\xb90\xc80|\x00*\t0\t@\t\x15\tM\t7\t>\t|\x00*\r0\r?\r6\rK\r'\r(\r|\x00\xe4\x05\xbc\x05\xe8\x05\xd5\x05\xd1\x05\xd9\x05\xe8\x05\xdf\x05|\x00k\x00i\x00\xc3\x1em\x00 \x00t\x00r\x00a\x00|\x00\xd6\x00l\x00\xe7\x00e\x00k\x00|\x00"
>>> print('utf-16le  %r' % e16le)
utf-16le  b"A\x00B\x00C\x00t\x00e\x00s\x00t\x00\xb2\x03\x9d\x8cTX\x04\xc7m\x00\xe1\x00s\x00b\x00\xea\x00t\x00a\x00|\x00t\x00e\x00s\x00t\x00|\x00'\x06.\x06*\x06(\x06'\x061\x06|\x00Km\xd5\x8b|\x00,nf\x8a|\x00\xc60\xb90\xc80|\x00*\t0\t@\t\x15\tM\t7\t>\t|\x00*\r0\r?\r6\rK\r'\r(\r|\x00\xe4\x05\xbc\x05\xe8\x05\xd5\x05\xd1\x05\xd9\x05\xe8\x05\xdf\x05|\x00k\x00i\x00\xc3\x1em\x00 \x00t\x00r\x00a\x00|\x00\xd6\x00l\x00\xe7\x00e\x00k\x00|\x00"
>>> print('utf-16be  %r' % e16be)
utf-16be  b"\x00A\x00B\x00C\x00t\x00e\x00s\x00t\x03\xb2\x8c\x9dXT\xc7\x04\x00m\x00\xe1\x00s\x00b\x00\xea\x00t\x00a\x00|\x00t\x00e\x00s\x00t\x00|\x06'\x06.\x06*\x06(\x06'\x061\x00|mK\x8b\xd5\x00|n,\x8af\x00|0\xc60\xb90\xc8\x00|\t*\t0\t@\t\x15\tM\t7\t>\x00|\r*\r0\r?\r6\rK\r'\r(\x00|\x05\xe4\x05\xbc\x05\xe8\x05\xd5\x05\xd1\x05\xd9\x05\xe8\x05\xdf\x00|\x00k\x00i\x1e\xc3\x00m\x00 \x00t\x00r\x00a\x00|\x00\xd6\x00l\x00\xe7\x00e\x00k\x00|"
>>> print()

>>> print('utf-8  w/ BOM decoded with utf-8     %r' % e8s.decode('utf-8'))
utf-8  w/ BOM decoded with utf-8     '\ufeffABCtestß???másbêta|test|??????|??|??|???|???????|???????|????????|ki?m tra|Ölçek|'
>>> print('utf-8  w/ BOM decoded with utf-8-sig %r' % e8s.decode('utf-8-sig'))
utf-8  w/ BOM decoded with utf-8-sig 'ABCtestß???másbêta|test|??????|??|??|???|???????|???????|????????|ki?m tra|Ölçek|'
>>> print('utf-16 w/ BOM decoded with utf-16    %r' % e16.decode('utf-16'))
utf-16 w/ BOM decoded with utf-16    'ABCtestß???másbêta|test|??????|??|??|???|???????|???????|????????|ki?m tra|Ölçek|'
>>> print('utf-16 w/ BOM decoded with utf-16le  %r' % e16.decode('utf-16le'))
utf-16 w/ BOM decoded with utf-16le  '\ufeffABCtestß???másbêta|test|??????|??|??|???|???????|???????|????????|ki?m tra|Ölçek|'

It's worth to know that only both utf-8-sig and utf-16 get back the original string after both encode and decode.

What is 'PermSize' in Java?

lace to store your loaded class definition and metadata. If a large code-base project is loaded, the insufficient Perm Gen size will cause the popular Java.Lang.OutOfMemoryError: PermGen.

Regex for empty string or white space

Had similar problem, was looking for white spaces in a string, solution:

  • To search for 1 space:

    var regex = /^.+\s.+$/ ;
    

    example: "user last_name"

  • To search for multiple spaces:

    var regex = /^.+\s.+$/g ;
    

    example: "user last name"

Simple way to count character occurrences in a string

Since you're scanning the whole string anyway you can build a full character count and do any number of lookups, all for the same big-Oh cost (n):

public static Map<Character,Integer> getCharFreq(String s) {
  Map<Character,Integer> charFreq = new HashMap<Character,Integer>();
  if (s != null) {
    for (Character c : s.toCharArray()) {
      Integer count = charFreq.get(c);
      int newCount = (count==null ? 1 : count+1);
      charFreq.put(c, newCount);
    }
  }
  return charFreq;
}

// ...
String s = "abdsd3$asda$asasdd$sadas";
Map counts = getCharFreq(s);
counts.get('$'); // => 3
counts.get('a'); // => 7
counts.get('s'); // => 6

How do I perform a JAVA callback between classes?

I don't know if this is what you are looking for, but you can achieve this by passing a callback to the child class.

first define a generic callback:

public interface ITypedCallback<T> {
    void execute(T type);
}

create a new ITypedCallback instance on ServerConnections instantiation:

public Server(int _address) {
    serverConnectionHandler = new ServerConnections(new ITypedCallback<Socket>() {
        @Override
        public void execute(Socket socket) {
            // do something with your socket here
        }
    });
}

call the execute methode on the callback object.

public class ServerConnections implements Runnable {

    private ITypedCallback<Socket> callback;

    public ServerConnections(ITypedCallback<Socket> _callback) {
        callback = _callback;
    }

    @Override
    public void run() {   
        try {
            mainSocket = new ServerSocket(serverPort);
            while (true) {
                callback.execute(mainSocket.accept());
            }
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

btw: I didn't check if it's 100% correct, directly coded it here.

String.Format not work in TypeScript

I solved it like this;

1.Created a function

export function FormatString(str: string, ...val: string[]) {
  for (let index = 0; index < val.length; index++) {
    str = str.replace(`{${index}}`, val[index]);
  }
  return str;
}

2.Used it like the following;

FormatString("{0} is {1} {2}", "This", "formatting", "hack");

convert string to number node.js

You do not have to install something.

parseInt(req.params.year, 10);

should work properly.

console.log(typeof parseInt(req.params.year)); // returns 'number'

What is your output, if you use parseInt? is it still a string?

Why is Spring's ApplicationContext.getBean considered bad?

One of the reasons is testability. Say you have this class:

interface HttpLoader {
    String load(String url);
}
interface StringOutput {
    void print(String txt);
}
@Component
class MyBean {
    @Autowired
    MyBean(HttpLoader loader, StringOutput out) {
        out.print(loader.load("http://stackoverflow.com"));
    }
}

How can you test this bean? E.g. like this:

class MyBeanTest {
    public void creatingMyBean_writesStackoverflowPageToOutput() {
        // setup
        String stackOverflowHtml = "dummy";
        StringBuilder result = new StringBuilder();

        // execution
        new MyBean(Collections.singletonMap("https://stackoverflow.com", stackOverflowHtml)::get, result::append);

        // evaluation
        assertEquals(result.toString(), stackOverflowHtml);
    }
}

Easy, right?

While you still depend on Spring (due to the annotations) you can remove you dependency on spring without changing any code (only the annotation definitions) and the test developer does not need to know anything about how spring works (maybe he should anyway, but it allows to review and test the code separately from what spring does).

It is still possible to do the same when using the ApplicationContext. However then you need to mock ApplicationContext which is a huge interface. You either need a dummy implementation or you can use a mocking framework such as Mockito:

@Component
class MyBean {
    @Autowired
    MyBean(ApplicationContext context) {
        HttpLoader loader = context.getBean(HttpLoader.class);
        StringOutput out = context.getBean(StringOutput.class);

        out.print(loader.load("http://stackoverflow.com"));
    }
}
class MyBeanTest {
    public void creatingMyBean_writesStackoverflowPageToOutput() {
        // setup
        String stackOverflowHtml = "dummy";
        StringBuilder result = new StringBuilder();
        ApplicationContext context = Mockito.mock(ApplicationContext.class);
        Mockito.when(context.getBean(HttpLoader.class))
            .thenReturn(Collections.singletonMap("https://stackoverflow.com", stackOverflowHtml)::get);
        Mockito.when(context.getBean(StringOutput.class)).thenReturn(result::append);

        // execution
        new MyBean(context);

        // evaluation
        assertEquals(result.toString(), stackOverflowHtml);
    }
}

This is quite a possibility, but I think most people would agree that the first option is more elegant and makes the test simpler.

The only option that is really a problem is this one:

@Component
class MyBean {
    @Autowired
    MyBean(StringOutput out) {
        out.print(new HttpLoader().load("http://stackoverflow.com"));
    }
}

Testing this requires huge efforts or your bean is going to attempt to connect to stackoverflow on each test. And as soon as you have a network failure (or the admins at stackoverflow block you due to excessive access rate) you will have randomly failing tests.

So as a conclusion I would not say that using the ApplicationContext directly is automatically wrong and should be avoided at all costs. However if there are better options (and there are in most cases), then use the better options.

Good Patterns For VBA Error Handling

I use a piece of code that i developed myself and it is pretty good for my codes:

In the beginning of the function or sub, I define:

On error Goto ErrorCatcher:

and then, I handle the possible errors

ErrorCatcher:
Select Case Err.Number

Case 0 'exit the code when no error was raised
    On Error GoTo 0
    Exit Function
Case 1 'Error on definition of object
    'do stuff
Case... 'little description here
    'do stuff
Case Else
    Debug.Print "###ERROR"
    Debug.Print "   • Number  :", Err.Number
    Debug.Print "   • Descrip :", Err.Description
    Debug.Print "   • Source  :", Err.Source
    Debug.Print "   • HelpCont:", Err.HelpContext
    Debug.Print "   • LastDLL :", Err.LastDllError
    Stop
    Err.Clear
    Resume
End Select

Creating threads - Task.Factory.StartNew vs new Thread()

There is a big difference. Tasks are scheduled on the ThreadPool and could even be executed synchronous if appropiate.

If you have a long running background work you should specify this by using the correct Task Option.

You should prefer Task Parallel Library over explicit thread handling, as it is more optimized. Also you have more features like Continuation.

How to set a hidden value in Razor

There is a Hidden helper alongside HiddenFor which lets you set the value.

@Html.Hidden("RequiredProperty", "default")

EDIT Based on the edit you've made to the question, you could do this, but I believe you're moving into territory where it will be cheaper and more effective, in the long run, to fight for making the code change. As has been said, even by yourself, the controller or view model should be setting the default.

This code:

<ul>
@{
        var stacks = new System.Diagnostics.StackTrace().GetFrames();
        foreach (var frame in stacks)
        {
            <li>@frame.GetMethod().Name - @frame.GetMethod().DeclaringType</li>
        }
}
</ul>

Will give output like this:

Execute - ASP._Page_Views_ViewDirectoryX__SubView_cshtml
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
ExecutePageHierarchy - System.Web.Mvc.WebViewPage
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
RenderView - System.Web.Mvc.RazorView
Render - System.Web.Mvc.BuildManagerCompiledView
RenderPartialInternal - System.Web.Mvc.HtmlHelper
RenderPartial - System.Web.Mvc.Html.RenderPartialExtensions
Execute - ASP._Page_Views_ViewDirectoryY__MainView_cshtml

So assuming the MVC framework will always go through the same stack, you can grab var frame = stacks[8]; and use the declaring type to determine who your parent view is, and then use that determination to set (or not) the default value. You could also walk the stack instead of directly grabbing [8] which would be safer but even less efficient.

Git error when trying to push -- pre-receive hook declined

In my case I got this message because the branch was marked as 'Protected' in GitLab.

Javascript change date into format of (dd/mm/yyyy)

Some JavaScript engines can parse that format directly, which makes the task pretty easy:

_x000D_
_x000D_
function convertDate(inputFormat) {_x000D_
  function pad(s) { return (s < 10) ? '0' + s : s; }_x000D_
  var d = new Date(inputFormat)_x000D_
  return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')_x000D_
}_x000D_
_x000D_
console.log(convertDate('Mon Nov 19 13:29:40 2012')) // => "19/11/2012"
_x000D_
_x000D_
_x000D_

Should I use SVN or Git?

I have used SVN for a long time, but whenever I used Git, I felt that Git is much powerful, lightweight, and although a little bit of learning curve involved but is better than SVN.

What I have noted is that each SVN project, as it grows, becomes a very big size project unless it is exported. Where as, GIT project (along with Git data) is very light weight in size.

In SVN, I've dealt with developers from novice to experts, and the novices and intermediates seem to introduce File conflicts if they copy one folder from another SVN project in order to re-use it. Whereas, I think in Git, you just copy the folder and it works, because Git doesn't introduce .git folders in all its subfolders (as SVN does).

After dealing alot with SVN since long time, I'm finally thinking to move my developers and me to Git, since it is easy to collaborate and merge work, as well as one great advantage is that a local copy's changes can be committed as much desired, and then finally pushed to the branch on server in one go, unlike SVN (where we have to commit the changes from time to time in the repository on server).

Anyone who can help me decide if I should really go with Git?

what does -zxvf mean in tar -zxvf <filename>?

  • z means (un)z_ip.
  • x means ex_tract files from the archive.
  • v means print the filenames v_erbosely.
  • f means the following argument is a f_ilename.

For more details, see tar's man page.

How to Get a Sublist in C#

You want List::GetRange(firstIndex, count). See http://msdn.microsoft.com/en-us/library/21k0e39c.aspx

// I have a List called list
List sublist = list.GetRange(5, 5); // (gets elements 5,6,7,8,9)
List anotherSublist = list.GetRange(0, 4); // gets elements 0,1,2,3)

Is that what you're after?

If you're looking to delete the sublist items from the original list, you can then do:

// list is our original list
// sublist is our (newly created) sublist built from GetRange()
foreach (Type t in sublist)
{
    list.Remove(t);
}

Tracking changes in Windows registry

Process Monitor allows you to monitor file and registry activity of various processes.

Best tool for inspecting PDF files?

The object viewer in Acrobat is good but Windjack Solution's PDF Canopener allows better inspection with an eyedropper for selecting objects on page. Also permits modifications to be made to PDF.

http://www.windjack.com/products/pdfcanopener.html

Changing SqlConnection timeout

You could always add it to your Connection String:

connect timeout=180;

Is there a way to specify which pytest tests to run from a file?

According to the doc about Run tests by node ids

since you have all node ids in foo.txt, just run

pytest `cat foo.txt | tr '\n' ' '`

this is same with below command (with file content in the question)

pytest tests_directory/foo.py::test_001 tests_directory/bar.py::test_some_other_test

deleting rows in numpy array

This is similar to your original approach, and will use less space than unutbu's answer, but I suspect it will be slower.

>>> import numpy as np
>>> p = np.array([[1.5, 0], [1.4,1.5], [1.6, 0], [1.7, 1.8]])
>>> p
array([[ 1.5,  0. ],
       [ 1.4,  1.5],
       [ 1.6,  0. ],
       [ 1.7,  1.8]])
>>> nz = (p == 0).sum(1)
>>> q = p[nz == 0, :]
>>> q
array([[ 1.4,  1.5],
       [ 1.7,  1.8]])

By the way, your line p.delete() doesn't work for me - ndarrays don't have a .delete attribute.

#1071 - Specified key was too long; max key length is 1000 bytes

I have just made bypass this error by just changing the values of the "length" in the original database to the total of around "1000" by changing its structure, and then exporting the same, to the server. :)

What does `dword ptr` mean?

It is a 32bit declaration. If you type at the top of an assembly file the statement [bits 32], then you don't need to type DWORD PTR. So for example:

[bits 32]
.
.
and  [ebp-4], 0

Is there a way to make npm install (the command) to work behind proxy?

There has been many answers above for this question, but none of those worked for me. All of them mentioned to add http:// prefix. So I added it too. All failed.

It finally works after I accidentally removed http:// prefix. Final config is like this:

npm config set registry http://registry.npmjs.org/
npm config set http-proxy ip:port
npm config set https-proxy ip:port
npm config set proxy ip:port
npm set strict-ssl false

I don't know the logic behind this, but it worked. If none of answers above works for you, maybe you can have a try on this way. Hope this one is useful.

How to apply border radius in IE8 and below IE8 browsers?

HTML:

<div id="myElement">Rounded Corner Box</div>

CSS:

#myElement {
    background: #EEE;
    padding: 2em;
    -moz-border-radius: 1em;
    -webkit-border-radius: 1em;
    border-radius: 1em;
    behavior: url(PIE.htc);
    border: 1px solid red;

}

PIE.htc file can be downloaded from http://www.css3pie.com

MySQL Update Inner Join tables query

Try this:

UPDATE business AS b
INNER JOIN business_geocode AS g ON b.business_id = g.business_id
SET b.mapx = g.latitude,
  b.mapy = g.longitude
WHERE  (b.mapx = '' or b.mapx = 0) and
  g.latitude > 0

Update:

Since you said the query yielded a syntax error, I created some tables that I could test it against and confirmed that there is no syntax error in my query:

mysql> create table business (business_id int unsigned primary key auto_increment, mapx varchar(255), mapy varchar(255)) engine=innodb;
Query OK, 0 rows affected (0.01 sec)

mysql> create table business_geocode (business_geocode_id int unsigned primary key auto_increment, business_id int unsigned not null, latitude varchar(255) not null, longitude varchar(255) not null, foreign key (business_id) references business(business_id)) engine=innodb;
Query OK, 0 rows affected (0.01 sec)

mysql> UPDATE business AS b
    -> INNER JOIN business_geocode AS g ON b.business_id = g.business_id
    -> SET b.mapx = g.latitude,
    ->   b.mapy = g.longitude
    -> WHERE  (b.mapx = '' or b.mapx = 0) and
    ->   g.latitude > 0;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0  Changed: 0  Warnings: 0

See? No syntax error. I tested against MySQL 5.5.8.

Detect if the device is iPhone X

SWIFT 4/5 reusable extension with iPhone 12 support

    extension UIDevice {
    
    enum `Type` {
        case iPhone_5_5S_5C_SE1
        case iPhone_6_6S_7_8_SE2
        case iPhone_6_6S_7_8_PLUS
        case iPhone_X_XS_12mini
        case iPhone_XR_11
        case iPhone_XS_11Pro_Max
        case iPhone_12_Pro
        case iPhone_12_Pro_Max
    }
    
    var hasHomeButton: Bool {
        switch type {
        case . iPhone_X_XS_12mini, . iPhone_XR_11, .iPhone_XS_11Pro_Max, . iPhone_XS_11Pro_Max, .iPhone_12_Pro, .iPhone_12_Pro_Max:
            return false
        default:
            return true
        }
    }
    
    var type: Type {
        if UI_USER_INTERFACE_IDIOM() == .phone {
        switch UIScreen.main.nativeBounds.height {
        case 1136:
            return .iPhone_5_5S_5C_SE1
        case 1334:
            return .iPhone_6_6S_7_8_SE2
        case 1920, 2208:
            return .iPhone_6_6S_7_8_PLUS
        case 2436:
            return .iPhone_X_XS_12mini
        case 2532:
            return .iPhone_12_Pro
        case 2688:
            return .iPhone_XS_11Pro_Max
        case 2778:
            return .iPhone_12_Pro_Max
        case 1792:
            return .iPhone_XR_11
        default:
            assertionFailure("Unknown phone device detected!")
            return .iPhone_6_6S_7_8_SE2
        }
    } else {
        assertionFailure("Unknown idiom device detected!")
        return .iPhone_6_6S_7_8_SE2
    }
   }
}

How can you use php in a javascript function

In the above given code

assign the php value to javascript variable.

<html>
<?php
 $num = 1;
 echo $num;
?>
  <input type = "button" name = "lol" value = "Click to increment" onclick = "Inc()">
  <br>
  <script>
   var numeric = <?php echo $num; ?>"; //assigns value of the $num to javascript var             numeric 
  function Inc()
   {
     numeric = eVal(numeric) + 1;
     alert("Increamented value: "+numeric);
   }
  </script>
</html>

One thing in combination of PHP and Javsacript is you can not assign javascript value to PHP value. You can assign PHP value to javascript variable.

Remove by _id in MongoDB console

Very close. This will work:

db.test_users.deleteOne( {"_id": ObjectId("4d512b45cc9374271b02ec4f")});

i.e. you don't need a new for the ObjectId.

Also, note that in some drivers/tools, remove() is now deprecated and deleteOne or deleteMany should be used instead.

Google Chrome redirecting localhost to https

Tried everything mentioned (browser preferences, hsts, etc.) but nothing worked for me.

I solved it by adding a trailing .localhost to the host aliases.

Like this:

127.0.0.1    myproject.localhost
127.0.0.1    dev.project.localhost

Rounding float in Ruby

For ruby 1.8.7 you could add the following to your code:

class Float
    alias oldround:round
    def round(precision = nil)
        if precision.nil?
            return self
        else
            return ((self * 10**precision).oldround.to_f) / (10**precision)
        end 
    end 
end

Determining Referer in PHP

There is no reliable way to check this. It's really under client's hand to tell you where it came from. You could imagine to use cookie or sessions informations put only on some pages of your website, but doing so your would break user experience with bookmarks.

C Programming: How to read the whole file contents into a buffer

A portable solution could use getc.

#include <stdio.h>

char buffer[MAX_FILE_SIZE];
size_t i;

for (i = 0; i < MAX_FILE_SIZE; ++i)
{
    int c = getc(fp);

    if (c == EOF)
    {
        buffer[i] = 0x00;
        break;
    }

    buffer[i] = c;
}

If you don't want to have a MAX_FILE_SIZE macro or if it is a big number (such that buffer would be to big to fit on the stack), use dynamic allocation.

What does Java option -Xmx stand for?

C:\java -X

    -Xmixed           mixed mode execution (default)
    -Xint             interpreted mode execution only
    -Xbootclasspath:<directories and zip/jar files separated by ;>
                      set search path for bootstrap classes and resources
    -Xbootclasspath/a:<directories and zip/jar files separated by ;>
                      append to end of bootstrap class path
    -Xbootclasspath/p:<directories and zip/jar files separated by ;>
                      prepend in front of bootstrap class path
    -Xnoclassgc       disable class garbage collection
    -Xincgc           enable incremental garbage collection
    -Xloggc:<file>    log GC status to a file with time stamps
    -Xbatch           disable background compilation
    -Xms<size>        set initial Java heap size
    -Xmx<size>        set maximum Java heap size
    -Xss<size>        set java thread stack size
    -Xprof            output cpu profiling data
    -Xfuture          enable strictest checks, anticipating future default
    -Xrs              reduce use of OS signals by Java/VM (see documentation)
    -Xcheck:jni       perform additional checks for JNI functions
    -Xshare:off       do not attempt to use shared class data
    -Xshare:auto      use shared class data if possible (default)
    -Xshare:on        require using shared class data, otherwise fail.

The -X options are non-standard and subject to change without notice.

What's the difference between "app.render" and "res.render" in express.js?

Here are some differences:

  1. You can call app.render on root level and res.render only inside a route/middleware.

  2. app.render always returns the html in the callback function, whereas res.render does so only when you've specified the callback function as your third parameter. If you call res.render without the third parameter/callback function the rendered html is sent to the client with a status code of 200.

    Take a look at the following examples.

    • app.render

      app.render('index', {title: 'res vs app render'}, function(err, html) {
          console.log(html)
      });
      
      // logs the following string (from default index.jade)
      <!DOCTYPE html><html><head><title>res vs app render</title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>res vs app render</h1><p>Welcome to res vs app render</p></body></html>
      
    • res.render without third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'})
      })
      
      // also renders index.jade but sends it to the client 
      // with status 200 and content-type text/html on GET /render
      
    • res.render with third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'}, function(err, html) {
              console.log(html);
              res.send('done');
          })
      })
      
      // logs the same as app.render and sends "done" to the client instead 
      // of the content of index.jade
      
  3. res.render uses app.render internally to render template files.

  4. You can use the render functions to create html emails. Depending on your structure of your app, you might not always have acces to the app object.

    For example inside an external route:

    app.js

    var routes = require('routes');
    
    app.get('/mail', function(req, res) {
        // app object is available -> app.render
    })
    
    app.get('/sendmail', routes.sendmail);
    

    routes.js

    exports.sendmail = function(req, res) {
        // can't use app.render -> therefore res.render
    }
    

Using regular expressions to do mass replace in Notepad++ and Vim

In notepad++

Search

(<option value="\w\w">)\w+">(.+)

Replace with

\1\2

Ansible: How to delete files and folders inside a directory?

Isn't it that simple ... tested working ..

eg.

---
- hosts: localhost
  vars:
     cleandir: /var/lib/cloud/
  tasks:
   - shell: ls -a -I '.' -I '..' {{ cleandir }}
     register: ls2del
     ignore_errors: yes
   - name: Cleanup {{ cleandir }}
     file:
       path: "{{ cleandir }}{{ item }}"
       state: absent
     with_items: "{{ ls2del.stdout_lines }}"

How to measure time in milliseconds using ANSI C?

The best precision you can possibly get is through the use of the x86-only "rdtsc" instruction, which can provide clock-level resolution (ne must of course take into account the cost of the rdtsc call itself, which can be measured easily on application startup).

The main catch here is measuring the number of clocks per second, which shouldn't be too hard.

-didSelectRowAtIndexPath: not being called

This was probably only in my case, but I had reloaded some files from a backup and things were not working, including this. After doing a full clean (Product > Clean or Shift + Command + K) it worked. Probably something got messed up in a precompiled header. Chances are that's not the problem for you, but it's worth a shot.

How to run server written in js with Node.js

Just try

node server

from cmd prompt in that directory

Enabling/installing GD extension? --without-gd

if you are on a Debian based server (such as Ubuntu) you can run the following command:

apt-get install php-gd

Then once it is complete run:

/etc/init.d/apache2 restart

This will restart your server and enable GD in PHP.

If you are on another type of system you will need to use something else (like yum install) or compile directly into PHP.

Excel tab sheet names vs. Visual Basic sheet names

In the Excel object model a Worksheet has 2 different name properties:

Worksheet.Name
Worksheet.CodeName

the Name property is read/write and contains the name that appears on the sheet tab. It is user and VBA changeable

the CodeName property is read-only

You can reference a particular sheet as Worksheets("Fred").Range("A1") where Fred is the .Name property or as Sheet1.Range("A1") where Sheet1 is the codename of the worksheet.

Read Numeric Data from a Text File in C++

you could read and write to a seperately like others. But if you want to write into the same one, you could try with this:

#include <iostream>
#include <fstream>

using namespace std;

int main() {

    double data[size of your data];

    std::ifstream input("file.txt");

    for (int i = 0; i < size of your data; i++) {
        input >> data[i];
        std::cout<< data[i]<<std::endl;
        }

}

What does (function($) {})(jQuery); mean?

Firstly, a code block that looks like (function(){})() is merely a function that is executed in place. Let's break it down a little.

1. (
2.    function(){}
3. )
4. ()

Line 2 is a plain function, wrapped in parenthesis to tell the runtime to return the function to the parent scope, once it's returned the function is executed using line 4, maybe reading through these steps will help

1. function(){ .. }
2. (1)
3. 2()

You can see that 1 is the declaration, 2 is returning the function and 3 is just executing the function.

An example of how it would be used.

(function(doc){

   doc.location = '/';

})(document);//This is passed into the function above

As for the other questions about the plugins:

Type 1: This is not a actually a plugin, it's an object passed as a function, as plugins tend to be functions.

Type 2: This is again not a plugin as it does not extend the $.fn object. It's just an extenstion of the jQuery core, although the outcome is the same. This is if you want to add traversing functions such as toArray and so on.

Type 3: This is the best method to add a plugin, the extended prototype of jQuery takes an object holding your plugin name and function and adds it to the plugin library for you.

positional argument follows keyword argument

The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:

argument_list        ::=  positional_arguments ["," starred_and_keywords]
                            ["," keywords_arguments]
                          | starred_and_keywords ["," keywords_arguments]
                          | keywords_arguments

Specifically, a keyword argument looks like this: tag='insider trading!' while a positional argument looks like this: ..., exchange, .... The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.

Also, when an argument has a default value, such as price=None, that means you don't have to provide it. If you don't provide it, it will use the default value instead.

To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity)

# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)

# Some positional, some keyword (all keywords at end):

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity, tag='insider trading!')

JPA Hibernate One-to-One relationship

JPA doesn't allow the @Id annotation on a OneToOne or ManyToOne mapping. What you are trying to do is one-to-one entity association with shared primary key. The simplest case is unidirectional one-to-one with shared key:

@Entity
public class Person {
    @Id
    private int id;

    @OneToOne
    @PrimaryKeyJoinColumn
    private OtherInfo otherInfo;

    rest of attributes ...
}

The main problem with this is that JPA provides no support for shared primary key generation in OtherInfo entity. The classic book Java Persistence with Hibernate by Bauer and King gives the following solution to the problem using Hibernate extension:

@Entity
public class OtherInfo {
    @Id @GeneratedValue(generator = "customForeignGenerator")
    @org.hibernate.annotations.GenericGenerator(
        name = "customForeignGenerator",
        strategy = "foreign",
        parameters = @Parameter(name = "property", value = "person")
    )
    private Long id;

    @OneToOne(mappedBy="otherInfo")
    @PrimaryKeyJoinColumn
    public Person person;

    rest of attributes ...
}

Also, see here.

How do I add a library project to Android Studio?

Open the build gradle module app file and add your dependency. If you download the library, just import and build as gradle.

Otherwise add repositories in side gradle module app:

repositories {
        maven { url 'http://clinker.47deg.com/nexus/content/groups/public' }
}

The first repositories will download the library for you.

And compile the downloaded library:

 compile ('com.fortysevendeg.swipelistview:swipelistview:1.0-SNAPSHOT@aar') {
        transitive = true
    }

If you are creating a library, you just need to import the project as import new module.

How can labels/legends be added for all chart types in chart.js (chartjs.org)?

  1. The legend is part of the default options of the ChartJs library. So you do not need to explicitly add it as an option.

  2. The library generates the HTML. It is merely a matter of adding that to the your page. For example, add it to the innerHTML of a given DIV. (Edit the default options if you are editing the colors, etc)


<div>
    <canvas id="chartDiv" height="400" width="600"></canvas>
    <div id="legendDiv"></div>
</div>

<script>
   var data = {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [
            {
                label: "The Flash's Speed",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "rgba(220,220,220,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: [65, 59, 80, 81, 56, 55, 40]
            },
            {
                label: "Superman's Speed",
                fillColor: "rgba(151,187,205,0.2)",
                strokeColor: "rgba(151,187,205,1)",
                pointColor: "rgba(151,187,205,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(151,187,205,1)",
                data: [28, 48, 40, 19, 86, 27, 90]
            }
        ]
    };

    var myLineChart = new Chart(document.getElementById("chartDiv").getContext("2d")).Line(data);
    document.getElementById("legendDiv").innerHTML = myLineChart.generateLegend();
</script>

CreateProcess: No such file or directory

try to put the path in the system variables instead of putting in user variables in environment variables.

how to call a function from another function in Jquery

I assume you don't want to rebind the event, but call the handler.

You can use trigger() to trigger events:

$('#billing_state_id').trigger('change');

If your handler doesn't rely on the event context and you don't want to trigger other handlers for the event, you could also name the function:

function someFunction() {
    //do stuff
}

$(document).ready(function(){
    //Load City by State
    $('#billing_state_id').live('change', someFunction);   
    $('#click_me').live('click', function() {
       //do something
       someFunction();
    });
  });

Also note that live() is deprecated, on() is the new hotness.

How to check if text fields are empty on form submit using jQuery?

You can bind an event handler to the "submit" JavaScript event using jQuery .submit method and then get trimmed #log text field value and check if empty of not like:

$('form').submit(function () {

    // Get the Login Name value and trim it
    var name = $.trim($('#log').val());

    // Check if empty of not
    if (name  === '') {
        alert('Text-field is empty.');
        return false;
    }
});

FIDDLE DEMO

How do I select between the 1st day of the current month and current day in MySQL?

select * from table_name 
where `date` between curdate() - dayofmonth(curdate()) + 1
                 and curdate()

SQLFiddle example

How to start IDLE (Python editor) without using the shortcut on Windows Vista?

there is a .bat script to start it (python 2.7).

c:\Python27\Lib\idlelib\idle.bat

Debug vs Release in CMake

A lot of the answers here are out of date/bad. So I'm going to attempt to answer it better. Granted I'm answering this question in 2020, so it's expected things would change.


How do I run CMake for each target type (debug/release)?

First off Debug/Release are called configurations in cmake (nitpick).

If you are using a single configuration generator (Ninja/Unix-Makefiles)

Then you need a build folder for each configuration.

Like this:

# Configure the build
cmake -S . -B build/Debug -D CMAKE_BUILD_TYPE=Release

# Actually build the binaries
cmake --build build/Debug

For multi-configuration generators it's slightly different (Ninja Multi-Config, Visual Studio)

# Configure the build
cmake -S . -B build

# Actually build the binaries
cmake --build build --config Debug

If you are wondering why this is necessary it's because cmake isn't a build system. It's a meta-build system (IE a build system that build's build systems). This is basically the result of handling build systems that support multiple-configurations in 1 build. If you'd like a deeper understanding I'd suggest reading a bit about cmake in Craig Scott's book "Professional CMake: A Practical Guide


How do I specify debug and release C/C++ flags using CMake?

The modern practice is to use target's and properties.

Here is an example:

add_library(foobar)

# Add this compile definition for debug builds, this same logic works for
# target_compile_options, target_link_options, etc.
target_compile_definitions(foobar PRIVATE
    $<$<CONFIG:Debug>:
        FOOBAR_DEBUG=1
    >
)

NOTE: How I'm using generator expressions to specify the configuration! Using CMAKE_BUILD_TYPE will result in bad builds for any multi-configuration generator!

Further more sometimes you need to set things globally and not just for one target. Use add_compile_definitions, add_compile_options, etc. Those functions support generator expressions. Don't use old style cmake unless you have to (that path is a land of nightmares)


How do I express that the main executable will be compiled with g++ and one nested library with gcc?

Your last question really doesn't make sense.

initialize a const array in a class initializer in C++

interestingly, in C# you have the keyword const that translates to C++'s static const, as opposed to readonly which can be only set at constructors and initializations, even by non-constants, ex:

readonly DateTime a = DateTime.Now;

I agree, if you have a const pre-defined array you might as well make it static. At that point you can use this interesting syntax:

//in header file
class a{
    static const int SIZE;
    static const char array[][10];
};
//in cpp file:
const int a::SIZE = 5;
const char array[SIZE][10] = {"hello", "cruel","world","goodbye", "!"};

however, I did not find a way around the constant '10'. The reason is clear though, it needs it to know how to perform accessing to the array. A possible alternative is to use #define, but I dislike that method and I #undef at the end of the header, with a comment to edit there at CPP as well in case if a change.

Disable all table constraints in Oracle

This is another way for disabling constraints (it came from https://asktom.oracle.com/pls/asktom/f?p=100:11:2402577774283132::::P11_QUESTION_ID:399218963817)

WITH qry0 AS
       (SELECT    'ALTER TABLE '
               || child_tname
               || ' DISABLE CONSTRAINT '
               || child_cons_name
                 disable_fk
              ,   'ALTER TABLE '
               || parent_tname
               || ' DISABLE CONSTRAINT '
               || parent.parent_cons_name
                 disable_pk
          FROM (SELECT a.table_name child_tname
                      ,a.constraint_name child_cons_name
                      ,b.r_constraint_name parent_cons_name
                      ,LISTAGG ( column_name, ',') WITHIN GROUP (ORDER BY position) child_columns
                  FROM user_cons_columns a
                      ,user_constraints b
                 WHERE a.constraint_name = b.constraint_name AND b.constraint_type = 'R'
                GROUP BY a.table_name, a.constraint_name
                        ,b.r_constraint_name) child
              ,(SELECT a.constraint_name parent_cons_name
                      ,a.table_name parent_tname
                      ,LISTAGG ( column_name, ',') WITHIN GROUP (ORDER BY position) parent_columns
                  FROM user_cons_columns a
                      ,user_constraints b
                 WHERE a.constraint_name = b.constraint_name AND b.constraint_type IN ('P', 'U')
                GROUP BY a.table_name, a.constraint_name) parent
         WHERE child.parent_cons_name = parent.parent_cons_name
           AND (parent.parent_tname LIKE 'V2_%' OR child.child_tname LIKE 'V2_%'))
SELECT DISTINCT disable_pk
  FROM qry0
UNION
SELECT DISTINCT disable_fk
  FROM qry0;

works like a charm

Ajax success event not working

I had this problem using an ajax function to recover the user password from Magento. The success event was not being fired, then I realized there were two errors:

  1. The result was not being returned in JSON format
  2. I was trying to convert an array to JSON format, but this array had non-utf characters

So every time I tried to use json_eoncde() to encode the returning array, the function was not working because one of its indexes had non-utf characters, most of them accentuation in brazilian portuguese words.

Attach event to dynamic elements in javascript

I have created a small library to help with this: Library source on GitHub

<script src="dynamicListener.min.js"></script>
<script>
// Any `li` or element with class `.myClass` will trigger the callback, 
// even elements created dynamically after the event listener was created.
addDynamicEventListener(document.body, 'click', '.myClass, li', function (e) {
    console.log('Clicked', e.target.innerText);
});
</script>

The functionality is similar to jQuery.on().

The library uses the Element.matches() method to test the target element against the given selector. When an event is triggered the callback is only called if the target element matches the selector given.

How to get a list of user accounts using the command line in MySQL?

SELECT * FROM mysql.user;

It's a big table so you might want to be more selective on what fields you choose.

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

How to disable the ability to select in a DataGridView?

I found setting all AllowUser... properties to false, ReadOnly to true, RowHeadersVisible to false, ScollBars to None, then faking the prevention of selection worked best for me. Not setting Enabled to false still allows the user to copy the data from the grid.

The following code also cleans up the look when you want a simple display grid (assuming rows are the same height):

int width = 0;
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
    width += dataGridView1.Columns[i].Width;
}

dataGridView1.Width = width;
dataGridView1.Height = dataGridView1.Rows[0].Height*(dataGridView1.Rows.Count+1);

Using TortoiseSVN via the command line

My fix for getting SVN commands was to copy .exe and .dll files from the TortoiseSVN directory and pasting them into system32 folder.

You could also perform the command from the TortoiseSVN directory and add the path of the working directory to each command. For example:

C:\Program Files\TortoiseSVN\bin> svn st -v C:\checkout

Adding the bin to the path should make it work without duplicating the files, but it didn't work for me.

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

somearray = ["some", "thing"]

anotherarray = ["another", "thing"]

somearray + anotherarray

Manifest Merger failed with multiple errors in Android Studio

Remove <activity android:name=".MainActivity"/> from your mainfest file. As you have already defined it as:

 <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

So, Manifest file showing ambiguity.

HTML5 record audio to file

The code shown below is copyrighted to Matt Diamond and available for use under MIT license. The original files are here:

Save this files and use

_x000D_
_x000D_
(function(window){_x000D_
_x000D_
      var WORKER_PATH = 'recorderWorker.js';_x000D_
      var Recorder = function(source, cfg){_x000D_
        var config = cfg || {};_x000D_
        var bufferLen = config.bufferLen || 4096;_x000D_
        this.context = source.context;_x000D_
        this.node = this.context.createScriptProcessor(bufferLen, 2, 2);_x000D_
        var worker = new Worker(config.workerPath || WORKER_PATH);_x000D_
        worker.postMessage({_x000D_
          command: 'init',_x000D_
          config: {_x000D_
            sampleRate: this.context.sampleRate_x000D_
          }_x000D_
        });_x000D_
        var recording = false,_x000D_
          currCallback;_x000D_
_x000D_
        this.node.onaudioprocess = function(e){_x000D_
          if (!recording) return;_x000D_
          worker.postMessage({_x000D_
            command: 'record',_x000D_
            buffer: [_x000D_
              e.inputBuffer.getChannelData(0),_x000D_
              e.inputBuffer.getChannelData(1)_x000D_
            ]_x000D_
          });_x000D_
        }_x000D_
_x000D_
        this.configure = function(cfg){_x000D_
          for (var prop in cfg){_x000D_
            if (cfg.hasOwnProperty(prop)){_x000D_
              config[prop] = cfg[prop];_x000D_
            }_x000D_
          }_x000D_
        }_x000D_
_x000D_
        this.record = function(){_x000D_
       _x000D_
          recording = true;_x000D_
        }_x000D_
_x000D_
        this.stop = function(){_x000D_
        _x000D_
          recording = false;_x000D_
        }_x000D_
_x000D_
        this.clear = function(){_x000D_
          worker.postMessage({ command: 'clear' });_x000D_
        }_x000D_
_x000D_
        this.getBuffer = function(cb) {_x000D_
          currCallback = cb || config.callback;_x000D_
          worker.postMessage({ command: 'getBuffer' })_x000D_
        }_x000D_
_x000D_
        this.exportWAV = function(cb, type){_x000D_
          currCallback = cb || config.callback;_x000D_
          type = type || config.type || 'audio/wav';_x000D_
          if (!currCallback) throw new Error('Callback not set');_x000D_
          worker.postMessage({_x000D_
            command: 'exportWAV',_x000D_
            type: type_x000D_
          });_x000D_
        }_x000D_
_x000D_
        worker.onmessage = function(e){_x000D_
          var blob = e.data;_x000D_
          currCallback(blob);_x000D_
        }_x000D_
_x000D_
        source.connect(this.node);_x000D_
        this.node.connect(this.context.destination);    //this should not be necessary_x000D_
      };_x000D_
_x000D_
      Recorder.forceDownload = function(blob, filename){_x000D_
        var url = (window.URL || window.webkitURL).createObjectURL(blob);_x000D_
        var link = window.document.createElement('a');_x000D_
        link.href = url;_x000D_
        link.download = filename || 'output.wav';_x000D_
        var click = document.createEvent("Event");_x000D_
        click.initEvent("click", true, true);_x000D_
        link.dispatchEvent(click);_x000D_
      }_x000D_
_x000D_
      window.Recorder = Recorder;_x000D_
_x000D_
    })(window);_x000D_
_x000D_
    //ADDITIONAL JS recorderWorker.js_x000D_
    var recLength = 0,_x000D_
      recBuffersL = [],_x000D_
      recBuffersR = [],_x000D_
      sampleRate;_x000D_
    this.onmessage = function(e){_x000D_
      switch(e.data.command){_x000D_
        case 'init':_x000D_
          init(e.data.config);_x000D_
          break;_x000D_
        case 'record':_x000D_
          record(e.data.buffer);_x000D_
          break;_x000D_
        case 'exportWAV':_x000D_
          exportWAV(e.data.type);_x000D_
          break;_x000D_
        case 'getBuffer':_x000D_
          getBuffer();_x000D_
          break;_x000D_
        case 'clear':_x000D_
          clear();_x000D_
          break;_x000D_
      }_x000D_
    };_x000D_
_x000D_
    function init(config){_x000D_
      sampleRate = config.sampleRate;_x000D_
    }_x000D_
_x000D_
    function record(inputBuffer){_x000D_
_x000D_
      recBuffersL.push(inputBuffer[0]);_x000D_
      recBuffersR.push(inputBuffer[1]);_x000D_
      recLength += inputBuffer[0].length;_x000D_
    }_x000D_
_x000D_
    function exportWAV(type){_x000D_
      var bufferL = mergeBuffers(recBuffersL, recLength);_x000D_
      var bufferR = mergeBuffers(recBuffersR, recLength);_x000D_
      var interleaved = interleave(bufferL, bufferR);_x000D_
      var dataview = encodeWAV(interleaved);_x000D_
      var audioBlob = new Blob([dataview], { type: type });_x000D_
_x000D_
      this.postMessage(audioBlob);_x000D_
    }_x000D_
_x000D_
    function getBuffer() {_x000D_
      var buffers = [];_x000D_
      buffers.push( mergeBuffers(recBuffersL, recLength) );_x000D_
      buffers.push( mergeBuffers(recBuffersR, recLength) );_x000D_
      this.postMessage(buffers);_x000D_
    }_x000D_
_x000D_
    function clear(){_x000D_
      recLength = 0;_x000D_
      recBuffersL = [];_x000D_
      recBuffersR = [];_x000D_
    }_x000D_
_x000D_
    function mergeBuffers(recBuffers, recLength){_x000D_
      var result = new Float32Array(recLength);_x000D_
      var offset = 0;_x000D_
      for (var i = 0; i < recBuffers.length; i++){_x000D_
        result.set(recBuffers[i], offset);_x000D_
        offset += recBuffers[i].length;_x000D_
      }_x000D_
      return result;_x000D_
    }_x000D_
_x000D_
    function interleave(inputL, inputR){_x000D_
      var length = inputL.length + inputR.length;_x000D_
      var result = new Float32Array(length);_x000D_
_x000D_
      var index = 0,_x000D_
        inputIndex = 0;_x000D_
_x000D_
      while (index < length){_x000D_
        result[index++] = inputL[inputIndex];_x000D_
        result[index++] = inputR[inputIndex];_x000D_
        inputIndex++;_x000D_
      }_x000D_
      return result;_x000D_
    }_x000D_
_x000D_
    function floatTo16BitPCM(output, offset, input){_x000D_
      for (var i = 0; i < input.length; i++, offset+=2){_x000D_
        var s = Math.max(-1, Math.min(1, input[i]));_x000D_
        output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);_x000D_
      }_x000D_
    }_x000D_
_x000D_
    function writeString(view, offset, string){_x000D_
      for (var i = 0; i < string.length; i++){_x000D_
        view.setUint8(offset + i, string.charCodeAt(i));_x000D_
      }_x000D_
    }_x000D_
_x000D_
    function encodeWAV(samples){_x000D_
      var buffer = new ArrayBuffer(44 + samples.length * 2);_x000D_
      var view = new DataView(buffer);_x000D_
_x000D_
      /* RIFF identifier */_x000D_
      writeString(view, 0, 'RIFF');_x000D_
      /* file length */_x000D_
      view.setUint32(4, 32 + samples.length * 2, true);_x000D_
      /* RIFF type */_x000D_
      writeString(view, 8, 'WAVE');_x000D_
      /* format chunk identifier */_x000D_
      writeString(view, 12, 'fmt ');_x000D_
      /* format chunk length */_x000D_
      view.setUint32(16, 16, true);_x000D_
      /* sample format (raw) */_x000D_
      view.setUint16(20, 1, true);_x000D_
      /* channel count */_x000D_
      view.setUint16(22, 2, true);_x000D_
      /* sample rate */_x000D_
      view.setUint32(24, sampleRate, true);_x000D_
      /* byte rate (sample rate * block align) */_x000D_
      view.setUint32(28, sampleRate * 4, true);_x000D_
      /* block align (channel count * bytes per sample) */_x000D_
      view.setUint16(32, 4, true);_x000D_
      /* bits per sample */_x000D_
      view.setUint16(34, 16, true);_x000D_
      /* data chunk identifier */_x000D_
      writeString(view, 36, 'data');_x000D_
      /* data chunk length */_x000D_
      view.setUint32(40, samples.length * 2, true);_x000D_
_x000D_
      floatTo16BitPCM(view, 44, samples);_x000D_
_x000D_
      return view;_x000D_
    }
_x000D_
<html>_x000D_
     <body>_x000D_
      <audio controls autoplay></audio>_x000D_
      <script type="text/javascript" src="recorder.js"> </script>_x000D_
                    <fieldset><legend>RECORD AUDIO</legend>_x000D_
      <input onclick="startRecording()" type="button" value="start recording" />_x000D_
      <input onclick="stopRecording()" type="button" value="stop recording and play" />_x000D_
                    </fieldset>_x000D_
      <script>_x000D_
       var onFail = function(e) {_x000D_
        console.log('Rejected!', e);_x000D_
       };_x000D_
_x000D_
       var onSuccess = function(s) {_x000D_
        var context = new webkitAudioContext();_x000D_
        var mediaStreamSource = context.createMediaStreamSource(s);_x000D_
        recorder = new Recorder(mediaStreamSource);_x000D_
        recorder.record();_x000D_
_x000D_
        // audio loopback_x000D_
        // mediaStreamSource.connect(context.destination);_x000D_
       }_x000D_
_x000D_
       window.URL = window.URL || window.webkitURL;_x000D_
       navigator.getUserMedia  = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;_x000D_
_x000D_
       var recorder;_x000D_
       var audio = document.querySelector('audio');_x000D_
_x000D_
       function startRecording() {_x000D_
        if (navigator.getUserMedia) {_x000D_
         navigator.getUserMedia({audio: true}, onSuccess, onFail);_x000D_
        } else {_x000D_
         console.log('navigator.getUserMedia not present');_x000D_
        }_x000D_
       }_x000D_
_x000D_
       function stopRecording() {_x000D_
        recorder.stop();_x000D_
        recorder.exportWAV(function(s) {_x000D_
                                _x000D_
                                  audio.src = window.URL.createObjectURL(s);_x000D_
        });_x000D_
       }_x000D_
      </script>_x000D_
     </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

RecyclerView vs. ListView

The RecyclerView is a new ViewGroup that is prepared to render any adapter-based view in a similar way. It is supossed to be the successor of ListView and GridView, and it can be found in the latest support-v7 version. The RecyclerView has been developed with extensibility in mind, so it is possible to create any kind of layout you can think of, but not without a little pain-in-the-ass dose.

Answer taken from Antonio leiva

 compile 'com.android.support:recyclerview-v7:27.0.0'

RecyclerView is indeed a powerful view than ListView . For more details you can visit This page.

How can I find out the total physical memory (RAM) of my linux box suitable to be parsed by a shell script?

Total online memory

Calculate the total online memory using the sys-fs.

totalmem=0;
for mem in /sys/devices/system/memory/memory*; do
  [[ "$(cat ${mem}/online)" == "1" ]] \
    && totalmem=$((totalmem+$((0x$(cat /sys/devices/system/memory/block_size_bytes)))));
done

#one-line code
totalmem=0; for mem in /sys/devices/system/memory/memory*; do [[ "$(cat ${mem}/online)" == "1" ]] && totalmem=$((totalmem+$((0x$(cat /sys/devices/system/memory/block_size_bytes))))); done

echo ${totalmem} bytes
echo $((totalmem/1024**3)) GB

Example output for 4 GB system:

4294967296 bytes
4 GB

Explanation

/sys/devices/system/memory/block_size_bytes

Number of bytes in a memory block (hex value). Using 0x in front of the value makes sure it's properly handled during the calculation.

/sys/devices/system/memory/memory*

Iterating over all available memory blocks to verify they are online and add the calculated block size to totalmem if they are.

[[ "$(cat ${mem}/online)" == "1" ]] &&

You can change or remove this if you prefer another memory state.

Getting pids from ps -ef |grep keyword

To kill a process by a specific keyword you could create an alias in ~/.bashrc (linux) or ~/.bash_profile (mac).

alias killps="kill -9 `ps -ef | grep '[k]eyword' | awk '{print $2}'`"

How to require a controller in an angularjs directive

I got lucky and answered this in a comment to the question, but I'm posting a full answer for the sake of completeness and so we can mark this question as "Answered".


It depends on what you want to accomplish by sharing a controller; you can either share the same controller (though have different instances), or you can share the same controller instance.

Share a Controller

Two directives can use the same controller by passing the same method to two directives, like so:

app.controller( 'MyCtrl', function ( $scope ) {
  // do stuff...
});

app.directive( 'directiveOne', function () {
  return {
    controller: 'MyCtrl'
  };
});

app.directive( 'directiveTwo', function () {
  return {
    controller: 'MyCtrl'
  };
});

Each directive will get its own instance of the controller, but this allows you to share the logic between as many components as you want.

Require a Controller

If you want to share the same instance of a controller, then you use require.

require ensures the presence of another directive and then includes its controller as a parameter to the link function. So if you have two directives on one element, your directive can require the presence of the other directive and gain access to its controller methods. A common use case for this is to require ngModel.

^require, with the addition of the caret, checks elements above directive in addition to the current element to try to find the other directive. This allows you to create complex components where "sub-components" can communicate with the parent component through its controller to great effect. Examples could include tabs, where each pane can communicate with the overall tabs to handle switching; an accordion set could ensure only one is open at a time; etc.

In either event, you have to use the two directives together for this to work. require is a way of communicating between components.

Check out the Guide page of directives for more info: http://docs.angularjs.org/guide/directive

How to click on hidden element in Selenium WebDriver?

If the <div> has id or name then you can use find_element_by_id or find_element_by_name

You can also try with class name, css and xpath

find_element_by_class_name
find_element_by_css_selector
find_element_by_xpath

"The system cannot find the file specified"

The most common reason could be the database connection string. You have to change the connection string attachDBFile=|DataDirectory|file_name.mdf. there might be problem in host name which would be (local),localhost or .\sqlexpress.

Differences between .NET 4.0 and .NET 4.5 in High level in .NET

This answer may be late reply but it will be useful for seeing this topic in future.

The features of .NET framework 4.5 can be seen in the following link.

To summarize:

  • Installation

    .NET Framework 4.5 does not support Windows XP or Windows Server 2003, and therefore, if you have to create applications that target these operating systems, you will need to stay with .NET Framework 4.0. In contrast, Windows 8 and Windows Server 2012 in all of their editions include .NET Framework 4.5.

  • Support for Arrays Larger than 2 GB on 64-bit Platforms
  • Enhanced Background Server Garbage Collection
  • Support for Timeouts in Regular Expression Evaluations
  • Support for Unicode 6.0.0 in Culture-Sensitive Sorting and Casing Rules on Windows 8
  • Simple Default Culture Definition for an Application Domain
  • Internationalized Domain Names in Windows 8 Apps

Export DataTable to Excel File

I had a project that I also needed an exact replica of a DataTable in Excel format. Using ClosedXML, the following code did exactly that for me.

using ClosedXML.Excel;

        private void DumpDataTableToExcel(DataTable dt, string SavePathAndFilename)
        {
            try
            {
                using (XLWorkbook excelWorkbook = new XLWorkbook())
                {
                    excelWorkbook.AddWorksheet(dt);
                    excelWorkbook.SaveAs(SavePathAndFilename);
                }
            }
            catch
            {
                //Insert error handling here...
            }
        }

This method will use your DataTable's column names as the column names in Excel and the DataTable name itself will be the sheet name. Hard to accomplish all of this with fewer lines of code.

Adding ClosedXML to your project is equally simple. There are instructions in the link above as well as directly on nuget.org.

Flexbox not giving equal width to elements

To create elements with equal width using Flex, you should set to your's child (flex elements):

flex-basis: 25%;
flex-grow: 0;

It will give to all elements in row 25% width. They will not grow and go one by one.

Presenting a UIAlertController properly on an iPad using iOS 8

Here's a quick solution:

NSString *text = self.contentTextView.text;
NSArray *items = @[text];

UIActivityViewController *activity = [[UIActivityViewController alloc]
                                      initWithActivityItems:items
                                      applicationActivities:nil];

activity.excludedActivityTypes = @[UIActivityTypePostToWeibo];

if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
    //activity.popoverPresentationController.sourceView = shareButtonBarItem;

    activity.popoverPresentationController.barButtonItem = shareButtonBarItem;

    [self presentViewController:activity animated:YES completion:nil];

}
[self presentViewController:activity animated:YES completion:nil];

How can I get a Unicode character's code?

In Java, char is technically a "16-bit integer", so you can simply cast it to int and you'll get it's code. From Oracle:

The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

So you can simply cast it to int.

char registered = '®';
System.out.println(String.format("This is an int-code: %d", (int) registered));
System.out.println(String.format("And this is an hexa code: %x", (int) registered));

How To Get The Current Year Using Vba

Try =Year(Now()) and format the cell as General.

How can I remove all files in my git repo and update/push from my local git repo?

I was trying to do :

git rm -r *

but at the end for me works :

git rm -r .

I hope it helps to you.

Set background color in PHP?

<?php
    header('Content-Type: text/css');
?>

some selector {
    background-color: <?php echo $my_colour_that_has_been_checked_to_be_a_safe_value; ?>;
}

Creating .pem file for APNS?

This is how I did it on Windows 7, after installing OpenSSL (link goes to the Win32 installer, choose the latest version and not the light version).

With this method you only need the .cer file downloaded from Apple.

c:\OpenSSL-Win32\bin\openssl.exe x509 -in aps_development.cer -inform DER -out developer_identity.pem -outform PEM

this will create a file which you will then need to add your private key too.

-----BEGIN PRIVATE KEY-----
MIIEuwIBADANBgkqhk....etc
MIIEuwIBADANBgkqhk....etc
MIIEuwIBADANBgkqhk....etc
MIIEuwIBADANBgkqhk....etc
-----END PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
AwIBAgwIBADAwIBADA....etc
AwIBAgwIBADAwIBADA....etc
AwIBAgwIBADAwIBADA....etc
-----END CERTIFICATE-----

That's it.

OwinStartup not firing

For me it was because they are not in the same namespace. After I remove my AppStart from "project.Startup.AppStart" and let they both Startup.cs and Startup.Auth.cs with "project.Startup" namespace, everything was back to work perfectly.

I hope it help!

App can't be opened because it is from an unidentified developer

Open terminal, go to extracted folder of eclipse and run the following command:

./eclipse -clean

Viewing root access files/folders of android on windows

Obviously, you'll need a rooted android device. Then set up an FTP server and transfer the files.

css to make bootstrap navbar transparent

Just leaving the default navbar built in with bootstrap works fine.
You just need to add the custom css below, that way everything still works as it should.

HTML:

<nav class="navbar navbar-default">

CSS:

.navbar-default {
    background-color: transparent;
}

Cannot find name 'require' after upgrading to Angular4

Add the following line at the top of the file that gives the error:

declare var require: any

How would I run an async Task<T> method synchronously?

Why not create a call like:

Service.GetCustomers();

that isn't async.

How to correct indentation in IntelliJ

You can also try out ctrl + alt + I even though you can also use l as well.

Can you style an html radio button to look like a checkbox?

Simple and neat with fontawesome

input[type=radio] {
    -moz-appearance: none;
    -webkit-appearance: none;
    -o-appearance: none;
    outline: none;
    content: none;
    margin-left: 5px;
}

input[type=radio]:before {
    font-family: "FontAwesome";
    content: "\f00c";
    font-size: 25px;
    color: transparent !important;
    background: #fff;
    width: 25px;
    height: 25px;
    border: 2px solid black;
    margin-right: 5px;
}

input[type=radio]:checked:before {
    color: black !important;
}

How to append to a file in Node?

You need to open it, then write to it.

var fs = require('fs'), str = 'string to append to file';
fs.open('filepath', 'a', 666, function( e, id ) {
  fs.write( id, 'string to append to file', null, 'utf8', function(){
    fs.close(id, function(){
      console.log('file closed');
    });
  });
});

Here's a few links that will help explain the parameters

open
write
close


EDIT: This answer is no longer valid, look into the new fs.appendFile method for appending.

Python 2: AttributeError: 'list' object has no attribute 'strip'

Split the strings and then use chain.from_iterable to combine them into a single list

>>> import itertools
>>> l = ['Facebook;Google+;MySpace', 'Apple;Android']
>>> l1 = [ x for x in itertools.chain.from_iterable( x.split(';') for x in l ) ]
>>> l1
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']

Executing <script> injected by innerHTML after AJAX call

Here is the script that will evaluates all script tags in the text.

function evalJSFromHtml(html) {
  var newElement = document.createElement('div');
  newElement.innerHTML = html;

  var scripts = newElement.getElementsByTagName("script");
  for (var i = 0; i < scripts.length; ++i) {
    var script = scripts[i];
    eval(script.innerHTML);
  }
}

Just call this function after you receive your HTML from server. Be warned: using eval can be dangerous.

Demo: http://plnkr.co/edit/LA7OPkRfAtgOhwcAnLrl?p=preview

HTML CSS Button Positioning

[type=submit]{
    margin-left: 121px;
    margin-top: 19px;
    width: 84px;
    height: 40px;   
    font-size:14px;
    font-weight:700;
}

git remove merge commit from history

Do git rebase -i <sha before the branches diverged> this will allow you to remove the merge commit and the log will be one single line as you wanted. You can also delete any commits that you do not want any more. The reason that your rebase wasn't working was that you weren't going back far enough.

WARNING: You are rewriting history doing this. Doing this with changes that have been pushed to a remote repo will cause issues. I recommend only doing this with commits that are local.

Unbound classpath container in Eclipse

In an already configured workspace where it just stopped building:

1. Right click the error
2. Select quick fix
3. Use workspace default JRE

This occasionally happens to me when working in a shared project after updating it with the latest changes. I'm not sure why, maybe their JRE installation path differs slightly from mine somehow.

Efficiency of Java "Double Brace Initialization"?

I second Nat's answer, except I would use a loop instead of creating and immediately tossing the implicit List from asList(elements):

static public Set<T> setOf(T ... elements) {
    Set set=new HashSet<T>(elements.size());
    for(T elm: elements) { set.add(elm); }
    return set;
    }

How to run travis-ci locally

Similar to Scott McLeod's but this also generates a bash script to run the steps from the .travis.yml.

Troubleshooting Locally in Docker with a generated Bash script

# choose the image according to the language chosen in .travis.yml
$ docker run -it -u travis quay.io/travisci/travis-jvm /bin/bash

# now that you are in the docker image, switch to the travis user
sudo - travis

# Install a recent ruby (default is 1.9.3)
rvm install 2.3.0
rvm use 2.3.0

# Install travis-build to generate a .sh out of .travis.yml
cd builds
git clone https://github.com/travis-ci/travis-build.git
cd travis-build
gem install travis
# to create ~/.travis
travis version
ln -s `pwd` ~/.travis/travis-build
bundle install

# Create project dir, assuming your project is `AUTHOR/PROJECT` on GitHub
cd ~/builds
mkdir AUTHOR
cd AUTHOR
git clone https://github.com/AUTHOR/PROJECT.git
cd PROJECT
# change to the branch or commit you want to investigate
travis compile > ci.sh
# You most likely will need to edit ci.sh as it ignores matrix and env
bash ci.sh

how to iterate through dictionary in a dictionary in django template?

This answer didn't work for me, but I found the answer myself. No one, however, has posted my question. I'm too lazy to ask it and then answer it, so will just put it here.

This is for the following query:

data = Leaderboard.objects.filter(id=custom_user.id).values(
    'value1',
    'value2',
    'value3')

In template:

{% for dictionary in data %}
  {% for key, value in dictionary.items %}
    <p>{{ key }} : {{ value }}</p>
  {% endfor %}
{% endfor %}

Razor View Engine : An expression tree may not contain a dynamic operation

A common error that is the cause of this is when you add

@Model SampleModel

at the top of the page instead of

@model SampleModel

How can I populate a select dropdown list from a JSON feed with AngularJS?

In my Angular Bootstrap dropdowns I initialize the JSON Array (vm.zoneDropdown) with ng-init (you can also have ng-init inside the directive template) and I pass the Array in a custom src attribute

<custom-dropdown control-id="zone" label="Zona" model="vm.form.zone" src="vm.zoneDropdown"
                         ng-init="vm.getZoneDropdownSrc()" is-required="true" form="farmaciaForm" css-class="custom-dropdown col-md-3"></custom-dropdown>

Inside the controller:

vm.zoneDropdown = [];
vm.getZoneDropdownSrc = function () {
    vm.zoneDropdown = $customService.getZone();
}

And inside the customDropdown directive template(note that this is only one part of the bootstrap dropdown):

<ul class="uib-dropdown-menu" role="menu" aria-labelledby="btn-append-to-body">
    <li role="menuitem" ng-repeat="dropdownItem in vm.src" ng-click="vm.setValue(dropdownItem)">
        <a ng-click="vm.preventDefault($event)" href="##">{{dropdownItem.text}}</a>
    </li>
</ul>

Show space, tab, CRLF characters in editor of Visual Studio

In the actual version this Option ist under Editor: Render Whitespace

iPhone Navigation Bar Title text color

Short and sweet.

[[[self navigationController] navigationBar] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor redColor]}];

Regex how to match an optional character

You have to mark the single letter as optional too:

([A-Z]{1})? +.*? +

or make the whole part optional

(([A-Z]{1}) +.*? +)?

Why does sudo change the PATH?

comment out both "Default env_reset" and "Default secure_path ..." in /etc/sudores file works for me

How to deal with SettingWithCopyWarning in Pandas

This topic is really confusing with Pandas. Luckily, it has a relatively simple solution.

The problem is that it is not always clear whether data filtering operations (e.g. loc) return a copy or a view of the DataFrame. Further use of such filtered DataFrame could therefore be confusing.

The simple solution is (unless you need to work with very large sets of data):

Whenever you need to update any values, always make sure that you explicitly copy the DataFrame before the assignment.

df  # Some DataFrame
df = df.loc[:, 0:2]  # Some filtering (unsure whether a view or copy is returned)
df = df.copy()  # Ensuring a copy is made
df[df["Name"] == "John"] = "Johny"  # Assignment can be done now (no warning)

What is the most efficient way of finding all the factors of a number in Python?

For n up to 10**16 (maybe even a bit more), here is a fast pure Python 3.6 solution,

from itertools import compress

def primes(n):
    """ Returns  a list of primes < n for n > 2 """
    sieve = bytearray([True]) * (n//2)
    for i in range(3,int(n**0.5)+1,2):
        if sieve[i//2]:
            sieve[i*i//2::i] = bytearray((n-i*i-1)//(2*i)+1)
    return [2,*compress(range(3,n,2), sieve[1:])]

def factorization(n):
    """ Returns a list of the prime factorization of n """
    pf = []
    for p in primeslist:
      if p*p > n : break
      count = 0
      while not n % p:
        n //= p
        count += 1
      if count > 0: pf.append((p, count))
    if n > 1: pf.append((n, 1))
    return pf

def divisors(n):
    """ Returns an unsorted list of the divisors of n """
    divs = [1]
    for p, e in factorization(n):
        divs += [x*p**k for k in range(1,e+1) for x in divs]
    return divs

n = 600851475143
primeslist = primes(int(n**0.5)+1) 
print(divisors(n))

Use of "this" keyword in formal parameters for static methods in C#

Scott Gu's quoted blog post explains it nicely.

For me, the answer to the question is in the following statement in that post:

Note how the static method above has a "this" keyword before the first parameter argument of type string. This tells the compiler that this particular Extension Method should be added to objects of type "string". Within the IsValidEmailAddress() method implementation I can then access all of the public properties/methods/events of the actual string instance that the method is being called on, and return true/false depending on whether it is a valid email or not.

How to convert IPython notebooks to PDF and HTML?

Only this answer would be useful to you if you have math, scientific formulae in your document. Even if you don't have them it works fine.

GUI way

  • open the jupyter notebook open the jupyter notebook

  • Go to Files > Download as > HTML or PDF via LaTeX Go to Files > Download as > HTML or PDF via LaTeX

  • Then check your Downloads folder for the file. PS: If LaTeX had any errors while compiling the PDF, it will fail. If this happens, download the HTML file and then use Web page to PDF tool or any other similar service to convert the HTML to PDF.

Command-Line way

  • Open the terminal
  • Navigate to the folder containing the jupyter notebook
  • type "jupyter nbconvert --to pdf your_jupyter_notebook.ipynb "

PS: If it fails, try Yogesh's answer.

What is the C# Using block and why should I use it?

using (B a = new B())
{
   DoSomethingWith(a);
}

is equivalent to

B a = new B();
try
{
  DoSomethingWith(a);
}
finally
{
   ((IDisposable)a).Dispose();
}

parsing a tab-separated file in Python

Like this:

>>> s='1\t2\t3\t4\t5'
>>> [x for x in s.split('\t')]
['1', '2', '3', '4', '5']

For a file:

# create test file:
>>> with open('tabs.txt','w') as o:
...    s='\n'.join(['\t'.join(map(str,range(i,i+10))) for i in [0,10,20,30]])
...    print >>o, s

#read that file:
>>> with open('tabs.txt','r') as f:
...    LoL=[x.strip().split('\t') for x in f]
... 
>>> LoL
[['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], 
 ['10', '11', '12', '13', '14', '15', '16', '17', '18', '19'], 
 ['20', '21', '22', '23', '24', '25', '26', '27', '28', '29'], 
 ['30', '31', '32', '33', '34', '35', '36', '37', '38', '39']]
>>> LoL[2][3]
23

If you want the input transposed:

>>> with open('tabs.txt','r') as f:
...    LoT=zip(*(line.strip().split('\t') for line in f))
... 
>>> LoT[2][3]
'32'

Or (better still) use the csv module in the default distribution...

Is it possible to get the current spark context settings in PySpark?

update configuration in Spark 2.3.1

To change the default spark configurations you can follow these steps:

Import the required classes

from pyspark.conf import SparkConf
from pyspark.sql import SparkSession

Get the default configurations

spark.sparkContext._conf.getAll()

Update the default configurations

conf = spark.sparkContext._conf.setAll([('spark.executor.memory', '4g'), ('spark.app.name', 'Spark Updated Conf'), ('spark.executor.cores', '4'), ('spark.cores.max', '4'), ('spark.driver.memory','4g')])

Stop the current Spark Session

spark.sparkContext.stop()

Create a Spark Session

spark = SparkSession.builder.config(conf=conf).getOrCreate()

Error handling in Bash

Use a trap!

tempfiles=( )
cleanup() {
  rm -f "${tempfiles[@]}"
}
trap cleanup 0

error() {
  local parent_lineno="$1"
  local message="$2"
  local code="${3:-1}"
  if [[ -n "$message" ]] ; then
    echo "Error on or near line ${parent_lineno}: ${message}; exiting with status ${code}"
  else
    echo "Error on or near line ${parent_lineno}; exiting with status ${code}"
  fi
  exit "${code}"
}
trap 'error ${LINENO}' ERR

...then, whenever you create a temporary file:

temp_foo="$(mktemp -t foobar.XXXXXX)"
tempfiles+=( "$temp_foo" )

and $temp_foo will be deleted on exit, and the current line number will be printed. (set -e will likewise give you exit-on-error behavior, though it comes with serious caveats and weakens code's predictability and portability).

You can either let the trap call error for you (in which case it uses the default exit code of 1 and no message) or call it yourself and provide explicit values; for instance:

error ${LINENO} "the foobar failed" 2

will exit with status 2, and give an explicit message.

Java creating .jar file

In order to create a .jar file, you need to use jar instead of java:

jar cf myJar.jar myClass.class

Additionally, if you want to make it executable, you need to indicate an entry point (i.e., a class with public static void main(String[] args)) for your application. This is usually accomplished by creating a manifest file that contains the Main-Class header (e.g., Main-Class: myClass).

However, as Mark Peters pointed out, with JDK 6, you can use the e option to define the entry point:

jar cfe myJar.jar myClass myClass.class 

Finally, you can execute it:

java -jar myJar.jar

See also