Programs & Examples On #Bit packing

How to change line-ending settings

For me what did the trick was running the command

git config auto.crlf false

inside the folder of the project, I wanted it specifically for one project.

That command changed the file in path {project_name}/.git/config (fyi .git is a hidden folder) by adding the lines

[auto]
    crlf = false

at the end of the file. I suppose changing the file does the same trick as well.

Define global constants

One approach for Angular4 would be defining a constant at module level:

const api_endpoint = 'http://127.0.0.1:6666/api/';

@NgModule({
  declarations: [AppComponent],
  bootstrap: [AppComponent],
  providers: [
    MessageService,
    {provide: 'API_ENDPOINT', useValue: api_endpoint}
  ]
})
export class AppModule {
}

Then, in your service:

import {Injectable, Inject} from '@angular/core';

@Injectable()
export class MessageService {

    constructor(private http: Http, 
      @Inject('API_ENDPOINT') private api_endpoint: string) { }

    getMessages(): Observable<Message[]> {
        return this.http.get(this.api_endpoint+'/messages')
            .map(response => response.json())
            .map((messages: Object[]) => {
                return messages.map(message => this.parseData(message));
            });
    }

    private parseData(data): Message {
        return new Message(data);
    }
}

CAST to DECIMAL in MySQL

From MySQL docs: Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC:

In standard SQL, the syntax DECIMAL(M) is equivalent to DECIMAL(M,0)

So, you are converting to a number with 2 integer digits and 0 decimal digits. Try this instead:

CAST((COUNT(*) * 1.5) AS DECIMAL(12,2)) 

Date formatting in WPF datagrid

I know the accepted answer is quite old, but there is a way to control formatting with AutoGeneratColumns :

First create a function that will trigger when a column is generated :

<DataGrid x:Name="dataGrid" AutoGeneratedColumns="dataGrid_AutoGeneratedColumns" Margin="116,62,10,10"/>

Then check if the type of the column generated is a DateTime and just change its String format to "d" to remove the time part :

private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            if(YourColumn == typeof(DateTime))
            {
                e.Column.ClipboardContentBinding.StringFormat = "d";
            }
        }

Shell script to delete directories older than n days

If you want to delete all subdirectories under /path/to/base, for example

/path/to/base/dir1
/path/to/base/dir2
/path/to/base/dir3

but you don't want to delete the root /path/to/base, you have to add -mindepth 1 and -maxdepth 1 options, which will access only the subdirectories under /path/to/base

-mindepth 1 excludes the root /path/to/base from the matches.

-maxdepth 1 will ONLY match subdirectories immediately under /path/to/base such as /path/to/base/dir1, /path/to/base/dir2 and /path/to/base/dir3 but it will not list subdirectories of these in a recursive manner. So these example subdirectories will not be listed:

/path/to/base/dir1/dir1
/path/to/base/dir2/dir1
/path/to/base/dir3/dir1

and so forth.

So , to delete all the sub-directories under /path/to/base which are older than 10 days;

find /path/to/base -mindepth 1 -maxdepth 1 -type d -ctime +10 | xargs rm -rf

How do I syntax check a Bash script without running it?

bash -n scriptname

Perhaps an obvious caveat: this validates syntax but won't check if your bash script tries to execute a command that isn't in your path, like ech hello instead of echo hello.

How to set 24-hours format for date on java?

Date d=new Date(new Date().getTime()+28800000);
String s=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(d);

HH will return 0-23 for hours.

kk will return 1-24 for hours.

See more here: Customizing Formats

use method setIs24HourView(Boolean is24HourView) to set time picker to set 24 hour view.

Bash integer comparison

Easier solution;

#/bin/bash
if (( ${1:-2} >= 2 )); then
    echo "First parameter must be 0 or 1"
fi
# rest of script...

Output

$ ./test 
First parameter must be 0 or 1
$ ./test 0
$ ./test 1
$ ./test 4
First parameter must be 0 or 1
$ ./test 2
First parameter must be 0 or 1

Explanation

  • (( )) - Evaluates the expression using integers.
  • ${1:-2} - Uses parameter expansion to set a value of 2 if undefined.
  • >= 2 - True if the integer is greater than or equal to two 2.

Disable HTTP OPTIONS, TRACE, HEAD, COPY and UNLOCK methods in IIS

For anyone looking for a UI option using IIS Manager.

  1. Open the Website in IIS Manager
  2. Go To Request Filtering and open the Request Filtering Window.
  3. Go to Verbs Tab and Add HTTP Verbs to "Allow Verb..." or "Deny Verb...". This allow to add the HTTP Verbs in the "Deny Verb.." Collection.

Request Filtering Window in IIS Manager Request Filtering Window in IIS Manager

Add Verb... or Deny Verb... enter image description here

Node.js console.log() not logging anything

Using modern --inspect with node the console.log is captured and relayed to the browser.

node --inspect myApp.js

or to capture early logging --inspect-brk can be used to stop the program on the first line of the first module...

node --inspect-brk myApp.js

Select 2 columns in one and combine them

I hope this answer helps:

SELECT (CAST(id AS NVARCHAR)+','+name) AS COMBINED_COLUMN FROM TABLENAME;

ERROR 1148: The used command is not allowed with this MySQL version

You can specify that as an additional option when setting up your client connection:

mysql -u myuser -p --local-infile somedatabase

This is because that feature opens a security hole. So you have to enable it in an explicit manner in case you really want to use it.

Both client and server should enable the local-file option. Otherwise it doesn't work.To enable it for files on the server side server add following to the my.cnf configuration file:

loose-local-infile = 1

How to tell whether a point is to the right or left side of a line

Assuming the points are (Ax,Ay) (Bx,By) and (Cx,Cy), you need to compute:

(Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax)

This will equal zero if the point C is on the line formed by points A and B, and will have a different sign depending on the side. Which side this is depends on the orientation of your (x,y) coordinates, but you can plug test values for A,B and C into this formula to determine whether negative values are to the left or to the right.

nginx- duplicate default server error

You likely have other files (such as the default configuration) located in /etc/nginx/sites-enabled that needs to be removed.

This issue is caused by a repeat of the default_server parameter supplied to one or more listen directives in your files. You'll likely find this conflicting directive reads something similar to:

listen 80 default_server;

As the nginx core module documentation for listen states:

The default_server parameter, if present, will cause the server to become the default server for the specified address:port pair. If none of the directives have the default_server parameter then the first server with the address:port pair will be the default server for this pair.

This means that there must be another file or server block defined in your configuration with default_server set for port 80. nginx is encountering that first before your mysite.com file so try removing or adjusting that other configuration.

If you are struggling to find where these directives and parameters are set, try a search like so:

grep -R default_server /etc/nginx

How to pass a JSON array as a parameter in URL

let qs = event.queryStringParameters;
const query = Object.keys(qs).map(key => key + '=' + qs[key]).join('&');

Is there a replacement for unistd.h for Windows (Visual C)?

The equivalent of unistd.h on Windows is windows.h

react hooks useEffect() cleanup for only componentWillUnmount?

Since the cleanup is not dependent on the username, you could put the cleanup in a separate useEffect that is given an empty array as second argument.

Example

_x000D_
_x000D_
const { useState, useEffect } = React;_x000D_
_x000D_
const ForExample = () => {_x000D_
  const [name, setName] = useState("");_x000D_
  const [username, setUsername] = useState("");_x000D_
_x000D_
  useEffect(_x000D_
    () => {_x000D_
      console.log("effect");_x000D_
    },_x000D_
    [username]_x000D_
  );_x000D_
_x000D_
  useEffect(() => {_x000D_
    return () => {_x000D_
      console.log("cleaned up");_x000D_
    };_x000D_
  }, []);_x000D_
_x000D_
  const handleName = e => {_x000D_
    const { value } = e.target;_x000D_
_x000D_
    setName(value);_x000D_
  };_x000D_
_x000D_
  const handleUsername = e => {_x000D_
    const { value } = e.target;_x000D_
_x000D_
    setUsername(value);_x000D_
  };_x000D_
_x000D_
  return (_x000D_
    <div>_x000D_
      <div>_x000D_
        <input value={name} onChange={handleName} />_x000D_
        <input value={username} onChange={handleUsername} />_x000D_
      </div>_x000D_
      <div>_x000D_
        <div>_x000D_
          <span>{name}</span>_x000D_
        </div>_x000D_
        <div>_x000D_
          <span>{username}</span>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  );_x000D_
};_x000D_
_x000D_
function App() {_x000D_
  const [shouldRender, setShouldRender] = useState(true);_x000D_
_x000D_
  useEffect(() => {_x000D_
    setTimeout(() => {_x000D_
      setShouldRender(false);_x000D_
    }, 5000);_x000D_
  }, []);_x000D_
_x000D_
  return shouldRender ? <ForExample /> : null;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App />, document.getElementById("root"));
_x000D_
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>_x000D_
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

How to restart a node.js server

If I am just run the node app from console (not using forever etc) I use control + C, not sure if OSX has the same key combination to terminate but much faster than finding the process id and killing it, you could also add the following code to the chat app you are using and then type 'exit' in the console whenever you want to close down the app.

process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function(data) {
  if (data == 'exit\n') process.exit();
});

How to write LDAP query to test if user is member of a group?

If you are using OpenLDAP (i.e. slapd) which is common on Linux servers, then you must enable the memberof overlay to be able to match against a filter using the (memberOf=XXX) attribute.

Also, once you enable the overlay, it does not update the memberOf attributes for existing groups (you will need to delete out the existing groups and add them back in again). If you enabled the overlay to start with, when the database was empty then you should be OK.

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

The error is try to fix a Youtube error.

The solution to avoid your Javascript-Console-Error complex is to accept that Youtube (and also other webpages) can have Javascript errors that you can't fix.

That is all.

PHP Echo text Color

This is an old question, but no one responded to the question regarding centering text in a terminal.

/**
 * Centers a string of text in a terminal window
 *
 * @param string $text The text to center
 * @param string $pad_string If set, the string to pad with (eg. '=' for a nice header)
 *
 * @return string The padded result, ready to echo
 */
function center($text, $pad_string = ' ') {
    $window_size = (int) `tput cols`;
    return str_pad($text, $window_size, $pad_string, STR_PAD_BOTH)."\n";
}

echo center('foo');
echo center('bar baz', '=');

How to activate virtualenv?

You can do

source ./python_env/bin/activate

or just go to the directory

cd /python_env/bin/

and then

source ./activate

Good Luck.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1

Just convert the text explicitly to string using str(). Worked for me.

Select and trigger click event of a radio button in jquery

You are triggering the event before the event is even bound.

Just move the triggering of the event to after attaching the event.

$(document).ready(function() {
  $("#checkbox_div input:radio").click(function() {

    alert("clicked");

   });

  $("input:radio:first").prop("checked", true).trigger("click");

});

Check Fiddle

How to handle calendar TimeZones using Java?

java.time

The modern approach uses the java.time classes that supplanted the troublesome legacy date-time classes bundled with the earliest versions of Java.

The java.sql.Timestamp class is one of those legacy classes. No longer needed. Instead use Instant or other java.time classes directly with your database using JDBC 4.2 and later.

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = myResultSet.getObject( … , Instant.class ) ; 

If you must interoperate with an existing Timestamp, convert immediately into java.time via the new conversion methods added to the old classes.

Instant instant = myTimestamp.toInstant() ;

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

ZoneId z = ZoneId.of( "America/Montreal" ) ;

Apply to the Instant to produce a ZonedDateTime object.

ZonedDateTime zdt = instant.atZone( z ) ;

To generate a string for display to the user, search Stack Overflow for DateTimeFormatter to find many discussions and examples.

Your Question is really about going the other direction, from user data-entry to the date-time objects. Generally best to break your data-entry into two parts, a date and a time-of-day.

LocalDate ld = LocalDate.parse( dateInput , DateTimeFormatter.ofPattern( "M/d/uuuu" , Locale.US ) ) ;
LocalTime lt = LocalTime.parse( timeInput , DateTimeFormatter.ofPattern( "H:m a" , Locale.US ) ) ;

Your Question is not clear. Do you want to interpret the date and the time entered by the user to be in UTC? Or in another time zone?

If you meant UTC, create a OffsetDateTime with an offset using the constant for UTC, ZoneOffset.UTC.

OffsetDateTime odt = OffsetDateTime.of( ld , lt , ZoneOffset.UTC ) ;

If you meant another time zone, combine along with a time zone object, a ZoneId. But which time zone? You might detect a default time zone. Or, if critical, you must confirm with the user to be certain of their intention.

ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;

To get a simpler object that is always in UTC by definition, extract an Instant.

Instant instant = odt.toInstant() ;

…or…

Instant instant = zdt.toInstant() ; 

Send to your database.

myPreparedStatement.setObject( … , instant ) ;

About java.time

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

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

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

Where to obtain the java.time classes?

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

Get visible items in RecyclerView

Finally, I found a solution to know if the current item is visible, from the onBindViewHolder event in the adapter.

The key is the method isViewPartiallyVisible from LayoutManager.

In your adapter, you can get the LayoutManager from the RecyclerView, which you get as parameter from the onAttachedToRecyclerView event.

Difference between <? super T> and <? extends T> in Java

I love the answer from @Bert F but this is the way my brain sees it.

I have an X in my hand. If I want to write my X into a List, that List needs to be either a List of X or a List of things that my X can be upcast to as I write them in i.e. any superclass of X...

List<? super   X>

If I get a List and I want to read an X out of that List, that better be a List of X or a List of things that can be upcast to X as I read them out, i.e. anything that extends X

List<? extends X>

Hope this helps.

Default session timeout for Apache Tomcat applications

Open $CATALINA_BASE/conf/web.xml and find this

<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly   -->
<!-- created sessions by modifying the value below.                       -->

<session-config>
  <session-timeout>30</session-timeout>
</session-config>

all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.

This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different

How to get the Display Name Attribute of an Enum member via MVC Razor code?

Building on Aydin's great answer, here's an extension method that doesn't require any type parameters.

using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;

public static class EnumExtensions
{
    public static string GetDisplayName(this Enum enumValue)
    {
        return enumValue.GetType()
                        .GetMember(enumValue.ToString())
                        .First()
                        .GetCustomAttribute<DisplayAttribute>()
                        .GetName();
    }
}

NOTE: GetName() should be used instead of the Name property. This ensures that the localized string will be returned if using the ResourceType attribute property.

Example

To use it, just reference the enum value in your view.

@{
    UserPromotion promo = UserPromotion.SendJobOffersByMail;
}

Promotion: @promo.GetDisplayName()

Output

Promotion: Send Job Offers By Mail

Invoke(Delegate)

this.Invoke(delegate) make sure that you are calling the delegate the argument to this.Invoke() on main thread/created thread.

I can say a Thumb rule don't access your form controls except from main thread.

May be the following lines make sense for using Invoke()

    private void SetText(string text)
    {
        // InvokeRequired required compares the thread ID of the
        // calling thread to the thread ID of the creating thread.
        // If these threads are different, it returns true.
        if (this.textBox1.InvokeRequired)
        {   
            SetTextCallback d = new SetTextCallback(SetText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            this.textBox1.Text = text;
        }
    }

There are situations though you create a Threadpool thread(i.e worker thread) it will run on main thread. It won't create a new thread coz main thread is available for processing further instructions. So First investigate whether the current running thread is main thread using this.InvokeRequired if returns true the current code is running on worker thread so call this.Invoke(d, new object[] { text });

else directly update the UI control(Here you are guaranteed that you are running the code on main thread.)

How to use GROUP_CONCAT in a CONCAT in MySQL

Try:

CREATE TABLE test (
  ID INTEGER,
  NAME VARCHAR (50),
  VALUE INTEGER
);

INSERT INTO test VALUES (1, 'A', 4);
INSERT INTO test VALUES (1, 'A', 5);
INSERT INTO test VALUES (1, 'B', 8);
INSERT INTO test VALUES (2, 'C', 9);

SELECT ID, GROUP_CONCAT(NAME ORDER BY NAME ASC SEPARATOR ',')
FROM (
  SELECT ID, CONCAT(NAME, ':', GROUP_CONCAT(VALUE ORDER BY VALUE ASC SEPARATOR ',')) AS NAME
  FROM test
  GROUP BY ID, NAME
) AS A
GROUP BY ID;

SQL Fiddle: http://sqlfiddle.com/#!2/b5abe/9/0

Pandas How to filter a Series

As DACW pointed out, there are method-chaining improvements in pandas 0.18.1 that do what you are looking for very nicely.

Rather than using .where, you can pass your function to either the .loc indexer or the Series indexer [] and avoid the call to .dropna:

test = pd.Series({
383:    3.000000,
663:    1.000000,
726:    1.000000,
737:    9.000000,
833:    8.166667
})

test.loc[lambda x : x!=1]

test[lambda x: x!=1]

Similar behavior is supported on the DataFrame and NDFrame classes.

CSV new-line character seen in unquoted field error

I realize this is an old post, but I ran into the same problem and don't see the correct answer so I will give it a try

Python Error:

_csv.Error: new-line character seen in unquoted field

Caused by trying to read Macintosh (pre OS X formatted) CSV files. These are text files that use CR for end of line. If using MS Office make sure you select either plain CSV format or CSV (MS-DOS). Do not use CSV (Macintosh) as save-as type.

My preferred EOL version would be LF (Unix/Linux/Apple), but I don't think MS Office provides the option to save in this format.

combining results of two select statements

While it is possible to combine the results, I would advise against doing so.

You have two fundamentally different types of queries that return a different number of rows, a different number of columns and different types of data. It would be best to leave it as it is - two separate queries.

How to allow access outside localhost

For the people who are using node project manager, also this line adding to package.json will be enough. For angular CLI users, mast3rd3mon's answer is true.

You can add

"server": "webpack-dev-server --inline --progress --host 0.0.0.0 --port 3000"

to package.json

'foo' was not declared in this scope c++

In C++ you are supposed to declare functions before you can use them. In your code integrate is not declared before the point of the first call to integrate. The same applies to sum. Hence the error. Either reorder your definitions so that function definition precedes the first call to that function, or introduce a [forward] non-defining declaration for each function.

Additionally, defining external non-inline functions in header files in a no-no in C++. Your definitions of SkewNormalEvalutatable::SkewNormalEvalutatable, getSkewNormal, integrate etc. have no business being in header file.

Also SkewNormalEvalutatable e(); declaration in C++ declares a function e, not an object e as you seem to assume. The simple SkewNormalEvalutatable e; will declare an object initialized by default constructor.

Also, you receive the last parameter of integrate (and of sum) by value as an object of Evaluatable type. That means that attempting to pass SkewNormalEvalutatable as last argument of integrate will result in SkewNormalEvalutatable getting sliced to Evaluatable. Polymorphism won't work because of that. If you want polymorphic behavior, you have to receive this parameter by reference or by pointer, but not by value.

Creating a dictionary from a CSV file

If you are OK with using the numpy package, then you can do something like the following:

import numpy as np

lines = np.genfromtxt("coors.csv", delimiter=",", dtype=None)
my_dict = dict()
for i in range(len(lines)):
   my_dict[lines[i][0]] = lines[i][1]

How to indent a few lines in Markdown markup?

Please use hard (non-breaking) spaces

Why use another markup language? (I Agree with @c z above).
One goal of Markdown is to make the documents readable even in a plain text editor.

Same result two approaches

The code

Sample code
&nbsp;&nbsp;&nbsp;&nbsp;5th position in an really ugly code  
    5th position in a clear an readable code  
    Again using non-breaking spaces :)

The result

Sample code
    5th position in an really ugly code
    5th position in a clear an readable code
    Again using non-breaking spaces :)

The visual representation of a non-breaking space (or hard space) is usually a normal space " ", however, its Unicode representation is U+00A0.
The Unicode representation of the ordinary space is U+0020 (32 in the ASCII Table).
Thus, text processors may behave differently while the visual representation remains the same.

Insert a hard space

| OS        | Input method                      |
|===========| ==================================|
| macOS     | OPTION+SPACE (ALT+SPACE)          |
| Linux     | Compose Space Space or AltGr+Space|
| Windows   | Alt+0+1+6+0                       |

Some text editor use Ctrl+Shift+Space.

Issue

Some text editors can convert hard spaces to common spaces in copying and pasting operations, so be careful.

Get Date Object In UTC format in Java

A Date doesn't have any time zone. What you're seeing is only the formatting of the date by the Date.toString() method, which uses your local timezone, always, to transform the timezone-agnostic date into a String that you can understand.

If you want to display the timezone-agnostic date as a string using the UTC timezone, then use a SimpleDateFormat with the UTC timezone (as you're already doing in your question).

In other terms, the timezone is not a property of the date. It's a property of the format used to transform the date into a string.

Passing an Object from an Activity to a Fragment

You should create a method within your fragment that accepts the type of object you wish to pass into it. In this case i named it "setObject" (creative huh? :) ) That method can then perform whatever action you need with that object.

MyFragment fragment;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

        if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {
            fragment = new MyFragment();
            getSupportFragmentManager().beginTransaction().add(android.R.id.content, detailsFragment)
                    .commit();
        } else {
           fragment = (MyFragment) getSupportFragmentManager().findFragmentById(
                    android.R.id.content);
        }


        fragment.setObject(yourObject); //create a method like this in your class "MyFragment"
}

Note that i'm using the support library and calls to getSupportFragmentManager() might be just getFragmentManager() for you depending on what you're working with

Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

Do what the compiler tells you to do, i.e. recompile with -fPIC. To learn what does this flag do and why you need it in this case, see Code Generation Options of the GCC manual.

In brief, the term position independent code (PIC) refers to the generated machine code which is memory address agnostic, i.e. does not make any assumptions about where it was loaded into RAM. Only position independent code is supposed to be included into shared objects (SO) as they should have an ability to dynamically change their location in RAM.

Finally, you can read about it on Wikipedia too.

Effective swapping of elements of an array in Java

public class SwapElements {

public static void main(String[] args) {

    int[] arr1 = new int[5];
    int[] arr2 = {10,20,30,40};

    System.out.println("arr1 Before Swapping " + Arrays.toString(arr1));
    System.out.println("arr2 Before Swapping " + Arrays.toString(arr2));

    int temp[];
    arr1[3] = 5;
    arr1[0] = 2;
    arr1[1] = 3;
    arr1[2] = 6;
    arr1[4] = 10;

    temp = arr1;
    arr1 = arr2;
    arr2 = temp;
    System.out.println("arr1 after Swapping " + Arrays.toString(arr1));
    System.out.println("arr2 after Swapping " + Arrays.toString(arr2));
}

}

Getting a list of all subdirectories in the current directory

This is how I do it.

    import os
    for x in os.listdir(os.getcwd()):
        if os.path.isdir(x):
            print(x)

alert a variable value

See with the help of the following example if you can use literals and '$' sign in your case.

    function doHomework(subject) {
    
      alert(\`Starting my ${subject} homework.\`);
    
    }

doHomework('maths');

How to update std::map after using the find method?

You can use std::map::at member function, it returns a reference to the mapped value of the element identified with key k.

std::map<char,int> mymap = {
                               { 'a', 0 },
                               { 'b', 0 },
                           };

  mymap.at('a') = 10;
  mymap.at('b') = 20;

Python No JSON object could be decoded

It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.

Hide all warnings in ipython

For jupyter lab this should work (@Alasja)

from IPython.display import HTML
HTML('''<script>
var code_show_err = false; 
var code_toggle_err = function() {
 var stderrNodes = document.querySelectorAll('[data-mime-type="application/vnd.jupyter.stderr"]')
 var stderr = Array.from(stderrNodes)
 if (code_show_err){
     stderr.forEach(ele => ele.style.display = 'block');
 } else {
     stderr.forEach(ele => ele.style.display = 'none');
 }
 code_show_err = !code_show_err
} 
document.addEventListener('DOMContentLoaded', code_toggle_err);
</script>
To toggle on/off output_stderr, click <a onclick="javascript:code_toggle_err()">here</a>.''')

forEach is not a function error with JavaScript array

parent.children will return a node list list, technically a html Collection. That is an array like object, but not an array, so you cannot call array functions over it directly. At this context you can use Array.from() to convert that into a real array,

Array.from(parent.children).forEach(child => {
  console.log(child)
})

Unstage a deleted file in git

I tried the above solutions and I was still having difficulties. I had other files staged with two files that were deleted accidentally.

To undo the two deleted files I had to unstage all of the files:

git reset HEAD .

At that point I was able to do the checkout of the deleted items:

git checkout -- WorkingFolder/FileName.ext

Finally I was able to restage the rest of the files and continue with my commit.

With MySQL, how can I generate a column containing the record index in a table?

SELECT @i:=@i+1 AS iterator, t.*
FROM tablename t,(SELECT @i:=0) foo

What is the effect of extern "C" in C++?

Not any C-header can be made compatible with C++ by merely wrapping in extern "C". When identifiers in a C-header conflict with C++ keywords the C++ compiler will complain about this.

For example, I have seen the following code fail in a g++ :

extern "C" {
struct method {
    int virtual;
};
}

Kinda makes sense, but is something to keep in mind when porting C-code to C++.

Limit length of characters in a regular expression?

Is there a way to limit a regex to 100 characters WITH regex?

Your example suggests that you'd like to grab a number from inside the regex and then use this number to place a maximum length on another part that is matched later in the regex. This usually isn't possible in a single pass. Your best bet is to have two separate regular expressions:

  • one to match the maximum length you'd like to use
  • one which uses the previously extracted value to verify that its own match does not exceed the specified length

If you just want to limit the number of characters matched by an expression, most regular expressions support bounds by using braces. For instance,

\d{3}-\d{3}-\d{4}

will match (US) phone numbers: exactly three digits, then a hyphen, then exactly three digits, then another hyphen, then exactly four digits.

Likewise, you can set upper or lower limits:

\d{5,10}

means "at least 5, but not more than 10 digits".


Update: The OP clarified that he's trying to limit the value, not the length. My new answer is don't use regular expressions for that. Extract the value, then compare it against the maximum you extracted from the size parameter. It's much less error-prone.

Unit testing click event in Angular

I'm using Angular 6. I followed Mav55's answer and it worked. However I wanted to make sure if fixture.detectChanges(); was really necessary so I removed it and it still worked. Then I removed tick(); to see if it worked and it did. Finally I removed the test from the fakeAsync() wrap, and surprise, it worked.

So I ended up with this:

it('should call onClick method', () => {
  const onClickMock = spyOn(component, 'onClick');
  fixture.debugElement.query(By.css('button')).triggerEventHandler('click', null);
  expect(onClickMock).toHaveBeenCalled();
});

And it worked just fine.

How do you check if a certain index exists in a table?

A slight deviation from the original question however may prove useful for future people landing here wanting to DROP and CREATE an index, i.e. in a deployment script.

You can bypass the exists check simply by adding the following to your create statement:

CREATE INDEX IX_IndexName
ON dbo.TableName
WITH (DROP_EXISTING = ON);

Read more here: CREATE INDEX (Transact-SQL) - DROP_EXISTING Clause

N.B. As mentioned in the comments, the index must already exist for this clause to work without throwing an error.

How to deal with "data of class uneval" error from ggplot2?

Another cause is accidentally putting the data=... inside the aes(...) instead of outside:

RIGHT:
ggplot(data=df[df$var7=='9-06',], aes(x=lifetime,y=rep_rate,group=mdcp,color=mdcp) ...)

WRONG:
ggplot(aes(data=df[df$var7=='9-06',],x=lifetime,y=rep_rate,group=mdcp,color=mdcp) ...)

In particular this can happen when you prototype your plot command with qplot(), which doesn't use an explicit aes(), then edit/copy-and-paste it into a ggplot()

qplot(data=..., x=...,y=..., ...)

ggplot(data=..., aes(x=...,y=...,...))

It's a pity ggplot's error message isn't Missing 'data' argument! instead of this cryptic nonsense, because that's what this message often means.

Confirm button before running deleting routine from website

Try this one :

 <script type="text/javascript">
      var baseUrl='http://example.com';
      function ConfirmDelete()
      {
            if (confirm("Delete Account?"))
                 location.href=baseUrl+'/deleteRecord.php';
      }
  </script>


  echo '<a type="button" onclick="ConfirmDelete()">DELETE ACCOUNT</a>';

Disable F5 and browser refresh using JavaScript

var ctrlKeyDown = false;

$(document).ready(function(){    
    $(document).on("keydown", keydown);
    $(document).on("keyup", keyup);
});

function keydown(e) { 

    if ((e.which || e.keyCode) == 116 || ((e.which || e.keyCode) == 82 && ctrlKeyDown)) {
        // Pressing F5 or Ctrl+R
        e.preventDefault();
    } else if ((e.which || e.keyCode) == 17) {
        // Pressing  only Ctrl
        ctrlKeyDown = true;
    }
};

function keyup(e){
    // Key up Ctrl
    if ((e.which || e.keyCode) == 17) 
        ctrlKeyDown = false;
};

Switching the order of block elements with CSS

<div id="container">
    <div id="a">Block A</div>
    <div id="b">Block B</div>
    <div id="c">Block C</div>
</div>

lets say the height of a block is 100px

#container     {position:relative; height: 300px;}
#a, #b, #c     {position:absolute; height: 100px}
#c             {top: 0px;}
#b             {top: 100px;}
#a             {top: 200px;}

regular expression to match exactly 5 digits

My test string for the following:

testing='12345,abc,123,54321,ab15234,123456,52341';

If I understand your question, you'd want ["12345", "54321", "15234", "52341"].

If JS engines supported regexp lookbehinds, you could do:

testing.match(/(?<!\d)\d{5}(?!\d)/g)

Since it doesn't currently, you could:

testing.match(/(?:^|\D)(\d{5})(?!\d)/g)

and remove the leading non-digit from appropriate results, or:

pentadigit=/(?:^|\D)(\d{5})(?!\d)/g;
result = [];
while (( match = pentadigit.exec(testing) )) {
    result.push(match[1]);
}

Note that for IE, it seems you need to use a RegExp stored in a variable rather than a literal regexp in the while loop, otherwise you'll get an infinite loop.

How to place the ~/.composer/vendor/bin directory in your PATH?

On Fedora:

Some composer bins are not in the .composer directory So you need to locate them using:

locate composer | grep vendor/bin

Then echo the the part into the .bashrc

echo 'export PATH="$PATH:$HOME/{you_composer_vendor_path}"' >> ~/.bashrc

Mine was "/.config/composer/vendor/bin" Cheers!

ASP.NET Bundles how to disable minification

I combined a few answers given by others in this question to come up with another alternative solution.

Goal: To always bundle the files, to disable the JS and CSS minification in the event that <compilation debug="true" ... /> and to always apply a custom transformation to the CSS bundle.

My solution:

1) In web.config: <compilation debug="true" ... />

2) In the Global.asax Application_Start() method:

 protected void Application_Start() {
     ...
     BundleTable.EnableOptimizations = true; // Force bundling to occur

     // If the compilation node in web.config indicates debugging mode is enabled
     // then clear all transforms. I.e. disable Js and CSS minification.
     if (HttpContext.Current.IsDebuggingEnabled) {
         BundleTable.Bundles.ToList().ForEach(b => b.Transforms.Clear());
     }

      // Add a custom CSS bundle transformer. In my case the transformer replaces a
      // token in the CSS file with an AppConfig value representing the website URL
      // in the current environment. E.g. www.mydevwebsite in Dev and
      // www.myprodwebsite.com in Production.
      BundleTable.Bundles.ToList()
          .FindAll(x => x.GetType() == typeof(StyleBundle))
          .ForEach(b => b.Transforms.Add(new MyStyleBundleTransformer()));
     ...
}

HTTP 400 (bad request) for logical error, not malformed request syntax

On Java EE servers a 400 is returned if your URL refers to a non-existent "web -application". Is that a "syntax error"? Depends on what you mean by syntax error. I would say yes.

In English syntax rules prescribe certain relationships between parts of speech. For instance "Bob marries Mary" is syntactically correct, because it follows the pattern {Noun + Verb + Noun}. Whereas "Bob marriage Mary" would be syntactically incorrect, {Noun + Noun + Noun}.

The syntax of a simple URLis { protocol + : + // + server + : + port }. According to this "http://www.google.com:80" is syntactically correct.

But what about "abc://www.google.com:80"? It seems to follow the exact same pattern. But really it is a syntax error. Why? Because 'abc' is not a DEFINED protocol.

The point is that determining whether or not we have a 400 situation requires more than parsing the characters and spaces and delimiters. It must also recognize what are the valid "parts of speech".

Creating an empty list in Python

list() is inherently slower than [], because

  1. there is symbol lookup (no way for python to know in advance if you did not just redefine list to be something else!),

  2. there is function invocation,

  3. then it has to check if there was iterable argument passed (so it can create list with elements from it) ps. none in our case but there is "if" check

In most cases the speed difference won't make any practical difference though.

pip install: Please check the permissions and owner of that directory

What is the problem here is that you somehow installed into virtualenv using sudo. Probably by accident. This means root user will rewrite Python package data, making all file owned by root and your normal user cannot write those files anymore. Usually virtualenv should be used and owned by your normal UNIX user only.

You can fix the issue by changing UNIX file permissions pack to your user. Try:

$ sudo chown -R USERNAME /Users/USERNAME/Library/Logs/pip
$ sudo chown -R USERNAME /Users/USERNAME/Library/Caches/pip

then pip should be able to write those files again.

More information about UNIX file permission management

Display only date and no time

Just had to deal with this scenario myself - found a really easy way to do this, simply annotate your property in the model like this:

[DataType(DataType.Date)]
public DateTime? SomeDateProperty { get; set; }

It will hide the time button from the date picker too.

Sorry if this answer is a little late ;)

How to list all users in a Linux group?

getent group insert_group_name_here | awk -F ':' '{print $4}' | sed 's|,| |g'

This returns a space separated list of users which I've used in scripts to populate arrays.

for i in $(getent group ftp | awk -F ':' '{print $4}' | sed 's|,| |g')
    do
        userarray+=("$i")
    done

or

userarray+=("$(getent group GROUPNAME | awk -F ':' '{print $4}' | sed 's|,| |g')")

How do I set the default locale in the JVM?

You can set it on the command line via JVM parameters:

java -Duser.country=CA -Duser.language=fr ... com.x.Main

For further information look at Internationalization: Understanding Locale in the Java Platform - Using Locale

Why do we use web.xml?

Web.xml is called as deployment descriptor file and its is is an XML file that contains information on the configuration of the web application, including the configuration of servlets.

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

How can a Java program get its own process ID?

Here's a backdoor method which might not work with all VMs but should work on both linux and windows (original example here):

java.lang.management.RuntimeMXBean runtime = 
    java.lang.management.ManagementFactory.getRuntimeMXBean();
java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm");
jvm.setAccessible(true);
sun.management.VMManagement mgmt =  
    (sun.management.VMManagement) jvm.get(runtime);
java.lang.reflect.Method pid_method =  
    mgmt.getClass().getDeclaredMethod("getProcessId");
pid_method.setAccessible(true);

int pid = (Integer) pid_method.invoke(mgmt);

apache server reached MaxClients setting, consider raising the MaxClients setting

Did you consider using nginx (or other event based web server) instead of apache?

nginx shall allow higher number of connections and consume much less resources (as it is event based and does not create separate process per connection). Anyway, you will need some processes, doing real work (like WSGI servers or so) and if they stay on the same server as the front end web server, you only shift the performance problem to a bit different place.

Latest apache version shall allow similar solution (configure it in event based manner), but this is not my area of expertise.

using OR and NOT in solr query

simple do id:("12345") OR id:("7890") .... and so on

What is Domain Driven Design?

Domain Driven Design is a methodology and process prescription for the development of complex systems whose focus is mapping activities, tasks, events, and data within a problem domain into the technology artifacts of a solution domain.

The emphasis of Domain Driven Design is to understand the problem domain in order to create an abstract model of the problem domain which can then be implemented in a particular set of technologies. Domain Driven Design as a methodology provides guidelines for how this model development and technology development can result in a system that meets the needs of the people using it while also being robust in the face of change in the problem domain.

The process side of Domain Driven Design involves the collaboration between domain experts, people who know the problem domain, and the design/architecture experts, people who know the solution domain. The idea is to have a shared model with shared language so that as people from these two different domains with their two different perspectives discuss the solution they are actually discussing a shared knowledge base with shared concepts.

The lack of a shared problem domain understanding between the people who need a particular system and the people who are designing and implementing the system seems to be a core impediment to successful projects. Domain Driven Design is a methodology to address this impediment.

It is more than having an object model. The focus is really about the shared communication and improving collaboration so that the actual needs within the problem domain can be discovered and an appropriate solution created to meet those needs.

Domain-Driven Design: The Good and The Challenging provides a brief overview with this comment:

DDD helps discover the top-level architecture and inform about the mechanics and dynamics of the domain that the software needs to replicate. Concretely, it means that a well done DDD analysis minimizes misunderstandings between domain experts and software architects, and it reduces the subsequent number of expensive requests for change. By splitting the domain complexity in smaller contexts, DDD avoids forcing project architects to design a bloated object model, which is where a lot of time is lost in working out implementation details — in part because the number of entities to deal with often grows beyond the size of conference-room white boards.

Also see this article Domain Driven Design for Services Architecture which provides a short example. The article provides the following thumbnail description of Domain Driven Design.

Domain Driven Design advocates modeling based on the reality of business as relevant to our use cases. As it is now getting older and hype level decreasing, many of us forget that the DDD approach really helps in understanding the problem at hand and design software towards the common understanding of the solution. When building applications, DDD talks about problems as domains and subdomains. It describes independent steps/areas of problems as bounded contexts, emphasizes a common language to talk about these problems, and adds many technical concepts, like entities, value objects and aggregate root rules to support the implementation.

Martin Fowler has written a number of articles in which Domain Driven Design as a methodology is mentioned. For instance this article, BoundedContext, provides an overview of the bounded context concept from Domain Driven Development.

In those younger days we were advised to build a unified model of the entire business, but DDD recognizes that we've learned that "total unification of the domain model for a large system will not be feasible or cost-effective" 1. So instead DDD divides up a large system into Bounded Contexts, each of which can have a unified model - essentially a way of structuring MultipleCanonicalModels.

Changing all files' extensions in a folder with one command on Windows

Rename multiple file extensions:

You want to change ringtone1.mp3, ringtone2.mp3 to ringtone1.wav, ringtone2.wav

Here is how to do that: I am in d drive on command prompt (CMD) so I use:

d:\>ren *.* *.wav 

This is just an example of file extensions, you can use any type of file extension like WAV, MP3, JPG, GIF, bmp, PDF, DOC, DOCX, TXT this depends on what your operating system.

And, since you have thousands of files, make sure to wait until the cursor starts blinking again indicating that it's done working.

How to get base url with jquery or javascript?

var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];

LINQ: Select an object and change some properties without creating a new object

If you just want to update the property on all elements then

someList.All(x => { x.SomeProp = "foo"; return true; })

Display names of all constraints for a table in Oracle SQL

Often enterprise databases have several users and I'm not aways on the right one :

SELECT * FROM ALL_CONSTRAINTS WHERE table_name = 'YOUR TABLE NAME' ;

Picked from Oracle documentation

Javascript Date: next month

Instead, try:

var now = new Date();
current = new Date(now.getFullYear(), now.getMonth()+1, 1);

JavaScript post request like a form submit

A simple quick-and-dirty implementation of @Aaron answer:

document.body.innerHTML += '<form id="dynForm" action="http://example.com/" method="post"><input type="hidden" name="q" value="a"></form>';
document.getElementById("dynForm").submit();

Of course, you should rather use a JavaScript framework such as Prototype or jQuery...

How do I toggle an element's class in pure JavaScript?

Here is a code for IE >= 9 by using split(" ") on the className :

function toggleClass(element, className) {
    var arrayClass = element.className.split(" ");
    var index = arrayClass.indexOf(className);

    if (index === -1) {
        if (element.className !== "") {
            element.className += ' '
        }
        element.className += className;
    } else {
        arrayClass.splice(index, 1);
        element.className = "";
        for (var i = 0; i < arrayClass.length; i++) {
            element.className += arrayClass[i];
            if (i < arrayClass.length - 1) {
                element.className += " ";
            }
        }
    }
}

size of NumPy array

Yes numpy has a size function, and shape and size are not quite the same.

Input

import numpy as np
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
arrData = np.array(data)

print(data)
print(arrData.size)
print(arrData.shape)

Output

[[1, 2, 3, 4], [5, 6, 7, 8]]

8 # size

(2, 4) # shape

Python import csv to list

A simple loop would suffice:

lines = []
with open('test.txt', 'r') as f:
    for line in f.readlines():
        l,name = line.strip().split(',')
        lines.append((l,name))

print lines

MySql Table Insert if not exist otherwise update

Try using this:

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index orPRIMARY KEY, MySQL performs an [UPDATE`](http://dev.mysql.com/doc/refman/5.7/en/update.html) of the old row...

The ON DUPLICATE KEY UPDATE clause can contain multiple column assignments, separated by commas.

With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify the CLIENT_FOUND_ROWS flag to mysql_real_connect() when connecting to mysqld, the affected-rows value is 1 (not 0) if an existing row is set to its current values...

how to include js file in php?

Pekka has the correct answer (hence my making this answer a Community Wiki): Use src, not href, to specify the file.

Regarding:

When i try it this way:

<script type="text/javascript">
    document.write('<script type="text/javascript" src="datetimepicker_css.js"></script>');
</script>

the first tag in the document.write function closes
what is the correct way to do this?

You don't want or need document.write for this, but just in case you ever do need to put the characters </script> inside a script tag for some other reason: You do that by ensuring that the HTML parser (which doesn't understand JavaScript) doesn't see a literal </script>. There are a couple of ways of doing that. One way is to escape the / even though you don't need to:

<script type='text/javascript'>
alert("<\/script>"); // Works, HTML parser doesn't see this as a closing script tag
//      ^--- note the seemingly-unnecessary backslash
</script>

Or if you're feeling more paranoid:

<script type='text/javascript'>
alert("</scr" + "ipt>"); // Works, HTML parser doesn't see this as a closing script tag
</script>

...since in each case, JavaScript sees the string as </script> but the HTML parser doesn't.

How to pass multiple parameters in a querystring

This can be done by using:

Response.Redirect("http://localhost/YourControllerName/ActionMethodName?querystring1=querystringvalue1&querystring2=querystringvalue2&querystring3=querystringvalue3");

assembly to compare two numbers

As already mentioned, usually the comparison is done through subtraction.
For example, X86 Assembly/Control Flow.

At the hardware level there are special digital circuits for doing the calculations, like adders.

In Go's http package, how do I get the query string on a POST request?

Below words come from the official document.

Form contains the parsed form data, including both the URL field's query parameters and the POST or PUT form data. This field is only available after ParseForm is called.

So, sample codes as below would work.

func parseRequest(req *http.Request) error {
    var err error

    if err = req.ParseForm(); err != nil {
        log.Error("Error parsing form: %s", err)
        return err
    }

    _ = req.Form.Get("xxx")

    return nil
}

Selecting element by data attribute with jQuery

I haven't seen a JavaScript answer without jQuery. Hopefully it helps someone.

_x000D_
_x000D_
var elements = document.querySelectorAll('[data-customerID="22"]');_x000D_
_x000D_
elements[0].innerHTML = 'it worked!';
_x000D_
<a data-customerID='22'>test</a>
_x000D_
_x000D_
_x000D_

Info:

How can I completely uninstall nodejs, npm and node in Ubuntu

Note: This will completely remove nodejs from your system; then you can make a fresh install from the below commands.

Removing Nodejs and Npm

sudo apt-get remove nodejs npm node
sudo apt-get purge nodejs

Now remove .node and .npm folders from your system

sudo rm -rf /usr/local/bin/npm 
sudo rm -rf /usr/local/share/man/man1/node* 
sudo rm -rf /usr/local/lib/dtrace/node.d 
sudo rm -rf ~/.npm 
sudo rm -rf ~/.node-gyp 
sudo rm -rf /opt/local/bin/node 
sudo rm -rf opt/local/include/node 
sudo rm -rf /opt/local/lib/node_modules  

sudo rm -rf /usr/local/lib/node*
sudo rm -rf /usr/local/include/node*
sudo rm -rf /usr/local/bin/node*

Go to home directory and remove any node or node_modules directory, if exists.

You can verify your uninstallation by these commands; they should not output anything.

which node
which nodejs
which npm

Installing NVM (Node Version Manager) by downloading and running a script

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash

The command above will clone the NVM repository from Github to the ~/.nvm directory:

Close and reopen your terminal to start using nvm or run the following to use it now:

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

As the output above says, you should either close and reopen the terminal or run the commands to add the path to nvm script to the current shell session. You can do whatever is easier for you.

Once the script is in your PATH, verify that nvm was properly installed by typing:

nvm --version

which should give this output:

0.34.0

Installing Node.js and npm

nvm install node
nvm install --lts

Once the installation is completed, verify it by printing the Node.js version:

node --version

should give this output:

v12.8.1

Npm should also be installed with node, verify it using

npm -v

should give:

6.13.4

Extra - [Optional] You can also use two different versions of node using nvm easily

nvm install 8.10.0 # just put the node version number Now switch between node versions

$ nvm ls
->     v12.14.1
        v13.7.0
default -> lts/* (-> v12.14.1)
node -> stable (-> v13.7.0) (default)
stable -> 13.7 (-> v13.7.0) (default)
iojs -> N/A (default)
unstable -> N/A (default)
lts/* -> lts/erbium (-> v12.14.1)
lts/argon -> v4.9.1 (-> N/A)
lts/boron -> v6.17.1 (-> N/A)
lts/carbon -> v8.17.0 (-> N/A)
lts/dubnium -> v10.18.1 (-> N/A)

In my case v12.14.1 and v13.7.0 both are installed, to switch I have to just use

nvm use 12.14.1

Configuring npm for global installations In your home directory, create a directory for global installations:

mkdir ~/.npm-global

Configure npm to use the new directory path:

npm config set prefix '~/.npm-global'

In your preferred text editor, open or create a ~/.profile file if does not exist and add this line:

PATH="$HOME/.npm-global/bin:$PATH"

On the command line, update your system variables:

source ~/.profile

That's all

How to unsubscribe to a broadcast event in angularJS. How to remove function registered via $on

After debugging the code, i created my own function just like "blesh"'s answer. So this is what i did

MyModule = angular.module('FIT', [])
.run(function ($rootScope) {
        // Custom $off function to un-register the listener.
        $rootScope.$off = function (name, listener) {
            var namedListeners = this.$$listeners[name];
            if (namedListeners) {
                // Loop through the array of named listeners and remove them from the array.
                for (var i = 0; i < namedListeners.length; i++) {
                    if (namedListeners[i] === listener) {
                        return namedListeners.splice(i, 1);
                    }
                }
            }
        }
});

so by attaching my function to $rootscope now it is available to all my controllers.

and in my code I am doing

$scope.$off("onViewUpdated", callMe);

Thanks

EDIT: The AngularJS way to do this is in @LiviuT's answer! But if you want to de-register the listener in another scope and at the same time want to stay away from creating local variables to keep references of de-registeration function. This is a possible solution.

Form inside a table

Use the "form" attribute, if you want to save your markup:

<form method="GET" id="my_form"></form>

<table>
    <tr>
        <td>
            <input type="text" name="company" form="my_form" />
            <button type="button" form="my_form">ok</button>
        </td>
    </tr>
</table>

(*Form fields outside of the < form > tag)

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

One more idea for anyone else getting this...

I had some gzipped svg, but it had a php error in the output, which caused this error message. (Because there was text in the middle of gzip binary.) Fixing the php error solved it.

using facebook sdk in Android studio

Facebook publishes the SDK on maven central :

Just add :

repositories {
    jcenter()       // IntelliJ main repo.
}

dependencies {
    compile 'com.facebook.android:facebook-android-sdk:+'
}

How to pass json POST data to Web API method as an object?

EDIT : 31/10/2017

The same code/approach will work for Asp.Net Core 2.0 as well. The major difference is, In asp.net core, both web api controllers and Mvc controllers are merged together to single controller model. So your return type might be IActionResult or one of it's implementation (Ex :OkObjectResult)


Use

contentType:"application/json"

You need to use JSON.stringify method to convert it to JSON string when you send it,

And the model binder will bind the json data to your class object.

The below code will work fine (tested)

$(function () {
    var customer = {contact_name :"Scott",company_name:"HP"};
    $.ajax({
        type: "POST",
        data :JSON.stringify(customer),
        url: "api/Customer",
        contentType: "application/json"
    });
});

Result

enter image description here

contentType property tells the server that we are sending the data in JSON format. Since we sent a JSON data structure,model binding will happen properly.

If you inspect the ajax request's headers, you can see that the Content-Type value is set as application/json.

If you do not specify contentType explicitly, It will use the default content type which is application/x-www-form-urlencoded;


Edit on Nov 2015 to address other possible issues raised in comments

Posting a complex object

Let's say you have a complex view model class as your web api action method parameter like this

public class CreateUserViewModel
{
   public int Id {set;get;}
   public string Name {set;get;}  
   public List<TagViewModel> Tags {set;get;}
}
public class TagViewModel
{
  public int Id {set;get;}
  public string Code {set;get;}
}

and your web api end point is like

public class ProductController : Controller
{
    [HttpPost]
    public CreateUserViewModel Save([FromBody] CreateUserViewModel m)
    {
        // I am just returning the posted model as it is. 
        // You may do other stuff and return different response.
        // Ex : missileService.LaunchMissile(m);
        return m;
    }
}

At the time of this writing, ASP.NET MVC 6 is the latest stable version and in MVC6, Both Web api controllers and MVC controllers are inheriting from Microsoft.AspNet.Mvc.Controller base class.

To send data to the method from client side, the below code should work fine

//Build an object which matches the structure of our view model class
var model = {
    Name: "Shyju",
    Id: 123,
    Tags: [{ Id: 12, Code: "C" }, { Id: 33, Code: "Swift" }]
};

$.ajax({
    type: "POST",
    data: JSON.stringify(model),
    url: "../product/save",
    contentType: "application/json"
}).done(function(res) {       
    console.log('res', res);
    // Do something with the result :)
});

Model binding works for some properties, but not all ! Why ?

If you do not decorate the web api method parameter with [FromBody] attribute

[HttpPost]
public CreateUserViewModel Save(CreateUserViewModel m)
{
    return m;
}

And send the model(raw javascript object, not in JSON format) without specifying the contentType property value

$.ajax({
    type: "POST",
    data: model,
    url: "../product/save"
}).done(function (res) {
     console.log('res', res);
});

Model binding will work for the flat properties on the model, not the properties where the type is complex/another type. In our case, Id and Name properties will be properly bound to the parameter m, But the Tags property will be an empty list.

The same problem will occur if you are using the short version, $.post which will use the default Content-Type when sending the request.

$.post("../product/save", model, function (res) {
    //res contains the markup returned by the partial view
    console.log('res', res);
});

"Unknown class <MyClass> in Interface Builder file" error at runtime

In my case I get this error message by a very stupid mistake by me: on interface builder I wanted to set the identifier of a UITableViewCell, but I typed the identifier accidentally to the 'Custom class' entry in interface builder.

I made cells 1000 times before....

Update built-in vim on Mac OS X

A note to romainl's answer: aliases don't work together with sudo because only the first word is checked on aliases. To change this add another alias to your .profile / .bashrc:

alias sudo='sudo '

With this change sudo vim will behave as expected!

HTML table with horizontal scrolling (first column fixed)

I have a similar table styled like so:

<table style="width:100%; table-layout:fixed">
    <tr>
        <td style="width: 150px">Hello, World!</td>
        <td>
            <div>
                <pre style="margin:0; overflow:scroll">My preformatted content</pre>
            </div>
        </td>
    </tr>
</table>

Fitting a histogram with python

Here is another solution using only matplotlib.pyplot and numpy packages. It works only for Gaussian fitting. It is based on maximum likelihood estimation and have already been mentioned in this topic. Here is the corresponding code :

# Python version : 2.7.9
from __future__ import division
import numpy as np
from matplotlib import pyplot as plt

# For the explanation, I simulate the data :
N=1000
data = np.random.randn(N)
# But in reality, you would read data from file, for example with :
#data = np.loadtxt("data.txt")

# Empirical average and variance are computed
avg = np.mean(data)
var = np.var(data)
# From that, we know the shape of the fitted Gaussian.
pdf_x = np.linspace(np.min(data),np.max(data),100)
pdf_y = 1.0/np.sqrt(2*np.pi*var)*np.exp(-0.5*(pdf_x-avg)**2/var)

# Then we plot :
plt.figure()
plt.hist(data,30,normed=True)
plt.plot(pdf_x,pdf_y,'k--')
plt.legend(("Fit","Data"),"best")
plt.show()

and here is the output.

Concatenating two std::vectors

With C++11, I'd prefer following to append vector b to a:

std::move(b.begin(), b.end(), std::back_inserter(a));

when a and b are not overlapped, and b is not going to be used anymore.


This is std::move from <algorithm>, not the usual std::move from <utility>.

How to disable right-click context-menu in JavaScript

You can't rely on context menus because the user can deactivate it. Most websites want to use the feature to annoy the visitor.

SQLException: No suitable driver found for jdbc:derby://localhost:1527

I had the same problem when I was writing Java application on Netbeans.Here is the solution:

  1. Find your project in projects selection tab

  2. Right click "Libraries"

  3. Click "Add JAR/Folder..."

  4. Choose "derbyclient.jar"

  5. Click "Open", then you will see "derbyclient.jar" under your "Libraries"

  6. Make sure your URL, user name, pass word is correct, and run your code:)

Git merge is not possible because I have unmerged files

It might be the Unmerged paths that cause

error: Merging is not possible because you have unmerged files.

If so, try:

git status

if it says

You have unmerged paths.

do as suggested: either resolve conflicts and then commit or abort the merge entirely with

git merge --abort

You might also see files listed under Unmerged paths, which you can resolve by doing

git rm <file>

Decimal values in SQL for dividing results

You will need to cast or convert the values to decimal before division. Take a look at this http://msdn.microsoft.com/en-us/library/aa226054.aspx

For example

DECLARE @num1 int = 3 DECLARE @num2 int = 2

SELECT @num1/@num2

SELECT @num1/CONVERT(decimal(4,2), @num2)

The first SELECT will result in what you're seeing while the second SELECT will have the correct answer 1.500000

How to set standard encoding in Visual Studio

I work with Windows7.

Control Panel - Region and Language - Administrative - Language for non-Unicode programs.

After I set "Change system locale" to English(United States). My default encoding of vs2010 change to Windows-1252. It was gb2312 before.

I created a new .cpp file for a C++ project, after checking in the new file to TFS the encoding show Windows-1252 from the properties page of the file.

ERROR 1064 (42000) in MySQL

If the line before your error contains COMMENT '' either populate the comment in the script or remove the empty comment definition. I've found this in scripts generated by MySQL Workbench.

link with target="_blank" does not open in new tab in Chrome

If you use React this should work:

_x000D_
_x000D_
<a href="#" onClick={()=>window.open("https://...")}</a>
_x000D_
_x000D_
_x000D_

How to convert a timezone aware string to datetime in Python without dateutil?

Here is the Python Doc for datetime object using dateutil package..

from dateutil.parser import parse

get_date_obj = parse("2012-11-01T04:16:13-04:00")
print get_date_obj

How do I remove a key from a JavaScript object?

The delete operator allows you to remove a property from an object.

The following examples all do the same thing.

// Example 1
var key = "Cow";
delete thisIsObject[key]; 

// Example 2
delete thisIsObject["Cow"];

// Example 3
delete thisIsObject.Cow;

If you're interested, read Understanding Delete for an in-depth explanation.

How to fire an event when v-model changes?

You can actually simplify this by removing the v-on directives:

<input type="radio" name="optionsRadios" id="optionsRadios1" value="1" v-model="srStatus">

And use the watch method to listen for the change:

new Vue ({
    el: "#app",
    data: {
        cases: [
            { name: 'case A', status: '1' },
            { name: 'case B', status: '0' },
            { name: 'case C', status: '1' }
        ],
        activeCases: [],
        srStatus: ''
    },
    watch: {
        srStatus: function(val, oldVal) {
            for (var i = 0; i < this.cases.length; i++) {
                if (this.cases[i].status == val) {
                    this.activeCases.push(this.cases[i]);
                    alert("Fired! " + val);
                }
            }
        }
    }
});

AngularJS - Multiple ng-view in single template

UI-Router is a project that can help: https://github.com/angular-ui/ui-router One of it's features is Multiple Named Views

UI-Router has many features and i recommend you using it if you're working on an advanced app.

Check documentation of Multiple Named Views here.

django admin - add custom form fields that are not part of the model

Django 2.1.1 The primary answer got me halfway to answering my question. It did not help me save the result to a field in my actual model. In my case I wanted a textfield that a user could enter data into, then when a save occurred the data would be processed and the result put into a field in the model and saved. While the original answer showed how to get the value from the extra field, it did not show how to save it back to the model at least in Django 2.1.1

This takes the value from an unbound custom field, processes, and saves it into my real description field:

class WidgetForm(forms.ModelForm):
    extra_field = forms.CharField(required=False)

    def processData(self, input):
        # example of error handling
        if False:
            raise forms.ValidationError('Processing failed!')

        return input + " has been processed"

    def save(self, commit=True):
        extra_field = self.cleaned_data.get('extra_field', None)

        # self.description = "my result" note that this does not work

        # Get the form instance so I can write to its fields
        instance = super(WidgetForm, self).save(commit=commit)

        # this writes the processed data to the description field
        instance.description = self.processData(extra_field)

        if commit:
            instance.save()

        return instance

    class Meta:
        model = Widget
        fields = "__all__"

Best tool for inspecting PDF files?

My sugession is Foxit PDF Reader which is very helpful to do important text editing work on pdf file.

Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function

You can use the Set-Variable cmdlet. Passing $global:var3 sends the value of $var3, which is not what you want. You want to send the name.

$global:var1 = $null

function foo ($a, $b, $varName)
{
   Set-Variable -Name $varName -Value ($a + $b) -Scope Global
}

foo 1 2 var1

This is not very good programming practice, though. Below would be much more straightforward, and less likely to introduce bugs later:

$global:var1 = $null

function ComputeNewValue ($a, $b)
{
   $a + $b
}

$global:var1 = ComputeNewValue 1 2

Django URL Redirect

Another way of doing it is using HttpResponsePermanentRedirect like so:

In view.py

def url_redirect(request):
    return HttpResponsePermanentRedirect("/new_url/")

In the url.py

url(r'^old_url/$', "website.views.url_redirect", name="url-redirect"),

size of struct in C

Aligning to 6 bytes is not weird, because it is aligning to addresses multiple to 4.

So basically you have 34 bytes in your structure and the next structure should be placed on the address, that is multiple to 4. The closest value after 34 is 36. And this padding area counts into the size of the structure.

Resizing a button

You should not use "width" and "height" attributes directly, use the style attribute like style="some css here" if you want to use inline styling:

<div class="button" style="width:60px;height:30px;">This is a button</div>

Note, however, that inline styling should generally be avoided since it makes maintenance and style updates a nightmare. Personally, if I had a button styling like yours but also wanted to apply different sizes, I would work with multiple css classes for sizing, like this:

_x000D_
_x000D_
   .button {_x000D_
        background-color: #000000;_x000D_
        color: #FFFFFF;_x000D_
        padding: 10px;_x000D_
        border-radius: 10px;_x000D_
        -moz-border-radius: 10px;_x000D_
        -webkit-border-radius: 10px;_x000D_
        margin:10px_x000D_
    }_x000D_
    _x000D_
    .small-btn {_x000D_
        width: 50px;_x000D_
        height: 25px;_x000D_
    }_x000D_
    _x000D_
    .medium-btn {_x000D_
        width: 70px;_x000D_
        height: 30px;_x000D_
    }_x000D_
    _x000D_
    .big-btn {_x000D_
        width: 90px;_x000D_
        height: 40px;_x000D_
    }
_x000D_
    <div class="button big-btn">This is a big button</div>_x000D_
    <div class="button medium-btn">This is a medium button</div>_x000D_
    <div class="button small-btn">This is a small button</div>_x000D_
 
_x000D_
_x000D_
_x000D_

jsFiddle example

Using this way of defining styles removes all style information from your HTML markup, which in will make it easier down the road if you want to change the size of all small buttons - you'll only have to change them once in the CSS.

Merge two HTML table cells

use colspan for do this

 <td colspan="3">PUR mix up column</td>

Override devise registrations controller

In your form are you passing in any other attributes, via mass assignment that don't belong to your user model, or any of the nested models?

If so, I believe the ActiveRecord::UnknownAttributeError is triggered in this instance.

Otherwise, I think you can just create your own controller, by generating something like this:

# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
  def new
    super
  end

  def create
    # add custom create logic here
  end

  def update
    super
  end
end 

And then tell devise to use that controller instead of the default with:

# app/config/routes.rb
devise_for :users, :controllers => {:registrations => "registrations"}

Binding a generic list to a repeater - ASP.NET

Code Behind:

public class Friends
{
    public string   ID      { get; set; }
    public string   Name    { get; set; }
    public string   Image   { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
        List <Friends> friendsList = new List<Friends>();

        foreach (var friend  in friendz)
        {
            friendsList.Add(
                new Friends { ID = friend.id, Name = friend.name }    
            );

        }

        this.rptFriends.DataSource = friendsList;
        this.rptFriends.DataBind();
}

.aspx Page

<asp:Repeater ID="rptFriends" runat="server">
            <HeaderTemplate>
                <table border="0" cellpadding="0" cellspacing="0">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                        </tr>
                    </thead>
                    <tbody>
            </HeaderTemplate>
            <ItemTemplate>
                    <tr>
                        <td><%# Eval("ID") %></td>
                        <td><%# Eval("Name") %></td>
                    </tr>
            </ItemTemplate>
            <FooterTemplate>
                    </tbody>
                </table>
            </FooterTemplate>
        </asp:Repeater>

Get list of a class' instance methods

TestClass.methods(false) 

to get only methods that belong to that class only.

TestClass.instance_methods(false) would return the methods from your given example (since they are instance methods of TestClass).

HashMap with multiple values under the same key

If you use Spring Framework. There is: org.springframework.util.MultiValueMap.

To create unmodifiable multi value map:

Map<String,List<String>> map = ...
MultiValueMap<String, String> multiValueMap = CollectionUtils.toMultiValueMap(map);

Or use org.springframework.util.LinkedMultiValueMap

Java generating non-repeating random numbers

Integer[] arr = {...};
Collections.shuffle(Arrays.asList(arr));

For example:

public static void main(String[] args) {
    Integer[] arr = new Integer[1000];
    for (int i = 0; i < arr.length; i++) {
        arr[i] = i;
    }
    Collections.shuffle(Arrays.asList(arr));
    System.out.println(Arrays.toString(arr));

}

Java "?" Operator for checking null - What is it? (Not Ternary!)

That's actually Groovy's safe-dereference operator. You can't use it in pure Java (sadly), so that post is simply wrong (or more likely slightly misleading, if it's claiming Groovy to be the "latest version of Java").

Url decode UTF-8 in Python

The data is UTF-8 encoded bytes escaped with URL quoting, so you want to decode, with urllib.parse.unquote(), which handles decoding from percent-encoded data to UTF-8 bytes and then to text, transparently:

from urllib.parse import unquote

url = unquote(url)

Demo:

>>> from urllib.parse import unquote
>>> url = 'example.com?title=%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%B2%D0%B0%D1%8F+%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0'
>>> unquote(url)
'example.com?title=????????+??????'

The Python 2 equivalent is urllib.unquote(), but this returns a bytestring, so you'd have to decode manually:

from urllib import unquote

url = unquote(url).decode('utf8')

Convert array to JSON

One other way could be this:

        var json_arr = {};
        json_arr["name1"] = "value1";
        json_arr["name2"] = "value2";
        json_arr["name3"] = "value3";

        var json_string = JSON.stringify(json_arr);

Example of AES using Crypto++

Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:

Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.

#include <iostream>
#include <iomanip>

#include "modes.h"
#include "aes.h"
#include "filters.h"

int main(int argc, char* argv[]) {

    //Key and IV setup
    //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-   
    //bit). This key is secretly exchanged between two parties before communication   
    //begins. DEFAULT_KEYLENGTH= 16 bytes
    CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
    memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
    memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );

    //
    // String and Sink setup
    //
    std::string plaintext = "Now is the time for all good men to come to the aide...";
    std::string ciphertext;
    std::string decryptedtext;

    //
    // Dump Plain Text
    //
    std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
    std::cout << plaintext;
    std::cout << std::endl << std::endl;

    //
    // Create Cipher Text
    //
    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
    stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
    stfEncryptor.MessageEnd();

    //
    // Dump Cipher Text
    //
    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

    for( int i = 0; i < ciphertext.size(); i++ ) {

        std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
    }

    std::cout << std::endl << std::endl;

    //
    // Decrypt
    //
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
    stfDecryptor.MessageEnd();

    //
    // Dump Decrypted Text
    //
    std::cout << "Decrypted Text: " << std::endl;
    std::cout << decryptedtext;
    std::cout << std::endl << std::endl;

    return 0;
}

For installation details :

sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils

Can I use Twitter Bootstrap and jQuery UI at the same time?

Because this is the top result on google on jquery ui and bootstrap.js I decided to add this as community wiki.

I am using:

  • Bootstrap v3.2.0
  • jquery-2.1.0
  • jquery-ui-1.10.3

and somehow when I include bootstrap.js it disables the dropdown of the jquery ui autocomplete.

my three workarounds:

  • exclude bootstrap.js
  • or more to typeahead lib
  • move from bootstrap.js to bootstrap.min.js (strange, but worked for me)

How do I check the difference, in seconds, between two dates?

Here's the one that is working for me.

from datetime import datetime

date_format = "%H:%M:%S"

# You could also pass datetime.time object in this part and convert it to string.
time_start = str('09:00:00') 
time_end = str('18:00:00')

# Then get the difference here.    
diff = datetime.strptime(time_end, date_format) - datetime.strptime(time_start, date_format)

# Get the time in hours i.e. 9.60, 8.5
result = diff.seconds / 3600;

Hope this helps!

Artificially create a connection timeout error

Plug in your network cable into a switch which has no other connection/cables. That should work imho.

Stylesheet not updating

This may not have been the OP's problem, but I had the same problem and solved it by flushing then disabling Supercache on my cpanel. Perhaps some other newbies like myself won't know that many hosting providers cache CSS and some other static files, and these cached old versions of CSS files will persist in the cloud for hours after you edit the file on your server. If your site serves up old versions of CSS files after you edit them, and you're certain you've cleared your browser cache, and you don't know whether your host is caching stuff, check that first before you try any other more complicated suggestions.

What's the best way to set a single pixel in an HTML5 canvas?

I hadn't considered fillRect(), but the answers spurred me to benchmark it against putImage().

Putting 100,000 randomly coloured pixels in random locations, with Chrome 9.0.597.84 on an (old) MacBook Pro, takes less than 100ms with putImage(), but nearly 900ms using fillRect(). (Benchmark code at http://pastebin.com/4ijVKJcC).

If instead I choose a single colour outside of the loops and just plot that colour at random locations, putImage() takes 59ms vs 102ms for fillRect().

It seems that the overhead of generating and parsing a CSS colour specification in rgb(...) syntax is responsible for most of the difference.

Putting raw RGB values straight into an ImageData block on the other hand requires no string handling or parsing.

Unable to load Private Key. (PEM routines:PEM_read_bio:no start line:pem_lib.c:648:Expecting: ANY PRIVATE KEY)

your .key file contains illegal characters. you can check .key file like this:

# file server.key

output "server.key: UTF-8 Unicode (with BOM) text" means it is a plain text, not a key file. The correct output should be "server.key: PEM RSA private key".

use below command to remove illegal characters:

# tail -c +4 server.key > new_server.key

The new_server.key should be correct.

For more detail, you can click here, thanks for the post.

How to initialize an array's length in JavaScript?

  • Array(5) gives you an array with length 5 but no values, hence you can't iterate over it.

  • Array.apply(null, Array(5)).map(function () {}) gives you an array with length 5 and undefined as values, now it can be iterated over.

  • Array.apply(null, Array(5)).map(function (x, i) { return i; }) gives you an array with length 5 and values 0,1,2,3,4.

  • Array(5).forEach(alert) does nothing, Array.apply(null, Array(5)).forEach(alert) gives you 5 alerts

  • ES6 gives us Array.from so now you can also use Array.from(Array(5)).forEach(alert)

  • If you want to initialize with a certain value, these are good to knows...
    Array.from('abcde'), Array.from('x'.repeat(5))
    or Array.from({length: 5}, (v, i) => i) // gives [0, 1, 2, 3, 4]

remove legend title in ggplot

Another option using labs and setting colour to NULL.

ggplot(df, aes(x, y, colour = g)) +
  geom_line(stat = "identity") +
  theme(legend.position = "bottom") +
  labs(colour = NULL)

enter image description here

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

you can also try this trick:

ps aux | grep puma

sample output:

myname           77921   0.0  0.0  2433828   1972 s000  R+   11:17AM   0:00.00 grep puma
myname           67661   0.0  2.3  2680504 191204 s002  S+   11:00AM   0:18.38 puma 3.11.2 (tcp://localhost:3000) [my_proj]

then:

kill -9 67661

Replacing spaces with underscores in JavaScript?

Just using replace:

_x000D_
_x000D_
var text = 'Hello World';_x000D_
    _x000D_
new_text = text.replace(' ', '_');_x000D_
    _x000D_
console.log(new_text);
_x000D_
_x000D_
_x000D_

How to compress image size?

i resolve this problem in this way, later i will improve the code

protected Void doInBackground(byte[]... data) {
        FileOutputStream outStream = null;

        // Write to Internal Storage
        try {
            File dir = new File (context.getFilesDir());
            dir.mkdirs();

            String fileName ="image.jpg";
            File outFile = new File(dir, fileName);
            outFile.setExecutable(true, false);
            outFile.setWritable(true, false);
            outStream = new FileOutputStream(outFile);
            outStream.write(data[0]);
            outStream.flush();
            outStream.close();
            InputStream in = new FileInputStream(context.getFilesDir()+"image.jpg");
            Bitmap bm2 = BitmapFactory.decodeStream(in);
            OutputStream stream = new FileOutputStream(String.valueOf(context.getFilesDir()+pathImage+"/"+idPicture+".jpg"));
            bm2.compress(Bitmap.CompressFormat.JPEG, 50, stream);
            stream.close();
            in.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
        return null;
    }

mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)

If 'localhost' doesn't work but 127.0.0.1 does. Make sure your local hosts file points to the correct location. (/etc/hosts for linux/mac, C:\Windows\System32\drivers\etc\hosts for windows).

Also, make sure your user is allowed to connect to whatever database you're trying to select.

Go Back to Previous Page

history.go(-1) this is a possible solution to the problem but it does not work in incognito mode as history is not maintained by the browser in this mode.

Git will not init/sync/update new submodules

Sort of magically, but today I ran git submodule init followed by git submodule sync followed by git submodule update and it started pulling my submodules... Magic? Perhaps! This is truly one of the most annoying experiences with Git…

Scratch that. I actually got it working by doing git submodule update --init --recursive. Hope this helps.

PS: Make sure you are in the root git directory, not the submodule's.

PHP Warning: mysqli_connect(): (HY000/2002): Connection refused

Sometimes you need to include mysql db port id in the server like so.

$serverName = "127.0.0.1:3307";

Passing additional variables from command line to make

If you make a file called Makefile and add a variable like this $(unittest) then you will be able to use this variable inside the Makefile even with wildcards

example :

make unittest=*

I use BOOST_TEST and by giving a wildcard to parameter --run_test=$(unittest) then I will be able to use regular expression to filter out the test I want my Makefile to run

How to load a resource from WEB-INF directory of a web archive

Here is how it works for me with no Servlet use.

Let's say I am trying to access web.xml in project/WebContent/WEB-INF/web.xml

  1. In project property Source-tab add source folder by pointing to the parent container for WEB-INF folder (in my case WebContent )

  2. Now let's use class loader:

    InputStream inStream = class.getClass().getClassLoader().getResourceAsStream("Web-INF/web.xml")
    

How can I change the language (to english) in Oracle SQL Developer?

On MAC High Sierra (10.13.6)

cd /Users/vkrishna/.sqldeveloper/18.2.0

nano product.conf

on the last line add

AddVMOption -Duser.language=en

Save the file and restart.

=======================================

If you are using standalone Oracle Data Modeller

find ~/ -name "datamodeler.conf"

and edit this file

cd /Users/vkrishna//Desktop/OracleDataModeler-18.2.0.179.0756.app/Contents/Resources/datamodeler/datamodeler/bin/

Add somewhere in the last

AddVMOption -Duser.language=en

save and restart, done!

Is floating point math broken?

Floating point rounding errors. 0.1 cannot be represented as accurately in base-2 as in base-10 due to the missing prime factor of 5. Just as 1/3 takes an infinite number of digits to represent in decimal, but is "0.1" in base-3, 0.1 takes an infinite number of digits in base-2 where it does not in base-10. And computers don't have an infinite amount of memory.

C# using Sendkey function to send a key to another application

If notepad is already started, you should write:

// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);

//...

Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
    IntPtr h = p.MainWindowHandle;
    SetForegroundWindow(h);
    SendKeys.SendWait("k");
}

GetProcessesByName returns an array of processes, so you should get the first one (or find the one you want).

If you want to start notepad and send the key, you should write:

Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");

The only situation in which the code may not work is when notepad is started as Administrator and your application is not.

Android Studio rendering problems

All you had to do is go to styles.xml file and replace your parent theme from

 Theme.AppCompat.Light.DarkActionBar 
to 
 Base.Theme.AppCompat.Light.DarkActionBar

HTML/CSS font color vs span style

The <font> tag has been deprecated, at least in XHTML. That means that it's use is officially "frowned upon," and there is no guarantee that future browsers will continue to display the text as you intended.

You have to use CSS. Go with the <span> tag, or a separate style sheet. According to its specification, the <span> tag has no semantic meaning and just allows you to change the style of a particular region.

How to copy and edit files in Android shell?

Since the permission policy on my device is a bit paranoid (cannot adb pull application data), I wrote a script to copy files recursively.

Note: this recursive file/folder copy script is intended for Android!

copy-r:

#! /system/bin/sh

src="$1"
dst="$2"
dir0=`pwd`

myfind() {
    local fpath=$1

    if [ -e "$fpath" ]
    then
    echo $fpath
    if [ -d "$fpath" ]
    then
        for fn in $fpath/*
        do
            myfind $fn
        done
    fi
    else
    : echo "$fpath not found"
    fi
}


if [ ! -z "$dst" ]
then
    if [ -d "$src" ]
    then
    echo 'the source is a directory'

    mkdir -p $dst

    if [[ "$dst" = /* ]]
    then
        : # Absolute path
    else
        # Relative path
        dst=`pwd`/$dst
    fi

    cd $src
    echo "COPYING files and directories from `pwd`"
    for fn in $(myfind .)
    do
        if [ -d $fn ]
        then
            echo "DIR  $dst/$fn"
            mkdir -p $dst/$fn
        else
            echo "FILE $dst/$fn"
            cat $fn >$dst/$fn
        fi
    done
    echo "DONE"
    cd $dir0

    elif [ -f "$src" ]
    then
    echo 'the source is a file'
    srcn="${src##*/}"
    if [ -z "$srcn" ]
    then
        srcn="$src"
    fi

    if [[ "$dst" = */ ]]
    then
        mkdir -p $dst
        echo "copying $src" '->' "$dst/$srcn"
        cat $src >$dst/$srcn
    elif [ -d "$dst" ]
    then
        echo "copying $src" '->' "$dst/$srcn"
        cat $src >$dst/$srcn
    else
        dstdir=${dst%/*}
        if [ ! -z "$dstdir" ]
        then
            mkdir -p $dstdir
        fi
        echo "copying $src" '->' "$dst"
        cat $src >$dst
    fi
    else
    echo "$src is neither a file nor a directory"
    fi
else
    echo "Use: copy-r src-dir dst-dir"
    echo "Use: copy-r src-file existing-dst-dir"
    echo "Use: copy-r src-file dst-dir/"
    echo "Use: copy-r src-file dst-file"
fi

Here I provide the source of a lightweight find for Android because on some devices this utility is missing. Instead of myfind one can use find, if it is defined on the device.

Installation:

$ adb push copy-r /sdcard/

Running within adb shell (rooted):

# . /sdcard/copy-r files/ /sdcard/files3 

or

# source /sdcard/copy-r files/ /sdcard/files3 

(The hash # above is the su prompt, while . is the command that causes the shell to run the specified file, almost the same as source).

After copying, I can adb pull the files from the sd-card.

Writing files to the app directory was trickier, I tried to set r/w permissions on files and its subdirectories, it did not work (well, it allowed me to read, but not write, which is strange), so I had to do:

        String[] cmdline = { "sh", "-c", "source /sdcard/copy-r /sdcard/files4 /data/data/com.example.myapp/files" }; 
        try {
            Runtime.getRuntime().exec(cmdline);
        } catch (IOException e) {
            e.printStackTrace();
        }

in the application's onCreate().

PS just in case someone needs the code to unprotect application's directories to enable adb shell access on a non-rooted phone,

        setRW(appContext.getFilesDir().getParentFile());

    public static void setRW(File... files) {
        for (File file : files) {
            if (file.isDirectory()) {
                setRW(file.listFiles()); // Calls same method again.
            } else {
            }
            file.setReadable(true, false);
            file.setWritable(true, false);
        }
    }

although for some unknown reason I could read but not write.

Apply CSS styles to an element depending on its child elements

In my case, I had to change the cell padding of an element that contained an input checkbox for a table that's being dynamically rendered with DataTables:

<td class="dt-center">
    <input class="a" name="constCheck" type="checkbox" checked="">
</td>

After implementing the following line code within the initComplete function I was able to produce the correct padding, which fixed the rows from being displayed with an abnormally large height

 $('tbody td:has(input.a)').css('padding', '0px');

Now, you can see that the correct styles are being applied to the parent element:

<td class=" dt-center" style="padding: 0px;">
    <input class="a" name="constCheck" type="checkbox" checked="">
</td>

Essentially, this answer is an extension of @KP's answer, but the more collaboration of implementing this the better. In summation, I hope this helps someone else because it works! Lastly, thank you so much @KP for leading me in the right direction!

Create new XML file and write data to it?

PHP has several libraries for XML Manipulation.

The Document Object Model (DOM) approach (which is a W3C standard and should be familiar if you've used it in other environments such as a Web Browser or Java, etc). Allows you to create documents as follows

<?php
    $doc = new DOMDocument( );
    $ele = $doc->createElement( 'Root' );
    $ele->nodeValue = 'Hello XML World';
    $doc->appendChild( $ele );
    $doc->save('MyXmlFile.xml');
?>

Even if you haven't come across the DOM before, it's worth investing some time in it as the model is used in many languages/environments.

Send multipart/form-data files with angular using $http

Here's an updated answer for Angular 4 & 5. TransformRequest and angular.identity were dropped. I've also included the ability to combine files with JSON data in one request.

Angular 5 Solution:

import {HttpClient} from '@angular/common/http';

uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
  // Note that setting a content-type header
  // for mutlipart forms breaks some built in
  // request parsers like multer in express.
  const options = {} as any; // Set any options you like
  const formData = new FormData();

  // Append files to the virtual form.
  for (const file of files) {
    formData.append(file.name, file)
  }

  // Optional, append other kev:val rest data to the form.
  Object.keys(restObj).forEach(key => {
    formData.append(key, restObj[key]);
  });

  // Send it.
  return this.httpClient.post(uploadUrl, formData, options)
    .toPromise()
    .catch((e) => {
      // handle me
    });
}

Angular 4 Solution:

// Note that these imports below are deprecated in Angular 5
import {Http, RequestOptions} from '@angular/http';

uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
  // Note that setting a content-type header
  // for mutlipart forms breaks some built in
  // request parsers like multer in express.
  const options = new RequestOptions();
  const formData = new FormData();

  // Append files to the virtual form.
  for (const file of files) {
    formData.append(file.name, file)
  }

  // Optional, append other kev:val rest data to the form.
  Object.keys(restObj).forEach(key => {
    formData.append(key, restObj[key]);
  });

  // Send it.
  return this.http.post(uploadUrl, formData, options)
    .toPromise()
    .catch((e) => {
      // handle me
    });
}

ToggleClass animate jQuery?

I attempted to use the toggleClass method to hide an item on my site (using visibility:hidden as opposed to display:none) with a slight animation, but for some reason the animation would not work (possibly due to an older version of jQuery UI).

The class was removed and added correctly, but the duration I added did not seem to make any difference - the item was simply added or removed with no effect.

So to resolve this I used a second class in my toggle method and applied a CSS transition instead:

The CSS:

.hidden{
    visibility:hidden;
    opacity: 0;
    -moz-transition: opacity 1s, visibility 1.3s;
    -webkit-transition: opacity 1s, visibility 1.3s;
    -o-transition: opacity 1s, visibility 1.3s;
    transition: opacity 1s, visibility 1.3s;
}
.shown{
    visibility:visible;
    opacity: 1;
    -moz-transition: opacity 1s, visibility 1.3s;
    -webkit-transition: opacity 1s, visibility 1.3s;
    -o-transition: opacity 1s, visibility 1.3s;
    transition: opacity 1s, visibility 1.3s;
}

The JS:

    function showOrHide() {
        $('#element').toggleClass("hidden shown");
    }

Thanks @tomas.satinsky for the awesome (and super simple) answer on this post.

Install .ipa to iPad with or without iTunes

  • Goto http://buildtry.com

  • Upload .ipa (iOS) or .apk (Android) file

  • Copy and Share the link with testers

  • Open the link in iOS or Android device browser and click Install

Meaning of 'const' last in a function declaration of a class?

Blair's answer is on the mark.

However note that there is a mutable qualifier which may be added to a class's data members. Any member so marked can be modified in a const method without violating the const contract.

You might want to use this (for example) if you want an object to remember how many times a particular method is called, whilst not affecting the "logical" constness of that method.

jQuery/JavaScript to replace broken images

I use lazy load and have to do this in order to make it work properly:

lazyload();

var errorURL = "https://example.com/thisimageexist.png";

$(document).ready(function () {
  $('[data-src]').on("error", function () {
    $(this).attr('src', errorURL);
  });
});

Integrating MySQL with Python in Windows

This may read like your grandpa givin advice, but all answers here did not mention the best way: go nd install ActivePython instead of python.org windows binaries. I was really wondering for a long time why Python development on windows was such a pita - until I installed activestate python. I am not affiliated with them. It is just the plain truth. Write it on every wall: Python development on Windows = ActiveState! you then just pypm install mysql-python and everything works smoothly. no compile orgy. no strange errors. no terror. Just start coding and doing real work after five minutes. This is the only way to go on windows. Really.

Clear a terminal screen for real

None of the answers I read worked in PuTTY, so I found a comment on this article:

In the settings for your connection, under "Window->Behavior" you'll find a setting "System Menu Appears on ALT alone". Then CTRL + L, ALT, l (that's a lower case L) will scroll the screen and then clear the scrollback buffer.

(relevant to the OP because I am connecting to an Ubuntu server, but also apparently relevant no matter what your server is running.)

Symfony2 : How to get form validation errors after binding the request to the form

SYMFONY 3.X

Other SF 3.X methods given here did not work for me because I could submit empty data to the form (but I have NotNull/NotBlanck constraints). In this case the error string would look like this :

string(282) "ERROR: This value should not be blank.
ERROR: This value should not be blank.
ERROR: This value should not be blank.
ERROR: This value should not be blank.
ERROR: This value should not be blank.
ERROR: This value should not be null.
name:
    ERROR: This value should not be blank.
"

Which is not very usefull. So I made this:

public function buildErrorArray(FormInterface $form)
{
    $errors = [];

    foreach ($form->all() as $child) {
        $errors = array_merge(
            $errors,
            $this->buildErrorArray($child)
        );
    }

    foreach ($form->getErrors() as $error) {
        $errors[$error->getCause()->getPropertyPath()] = $error->getMessage();
    }

    return $errors;
}

Which would return that :

array(7) {
  ["data.name"]=>
  string(31) "This value should not be blank."
  ["data.street"]=>
  string(31) "This value should not be blank."
  ["data.zipCode"]=>
  string(31) "This value should not be blank."
  ["data.city"]=>
  string(31) "This value should not be blank."
  ["data.state"]=>
  string(31) "This value should not be blank."
  ["data.countryCode"]=>
  string(31) "This value should not be blank."
  ["data.organization"]=>
  string(30) "This value should not be null."
}

bash string compare to multiple correct values

If the main intent is to check whether the supplied value is not found in a list, maybe you can use the extended regular expression matching built in BASH via the "equal tilde" operator (see also this answer):

if ! [[ "$cms" =~ ^(wordpress|meganto|typo3)$ ]]; then get_cms ; fi

Have a nice day

No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes

if none of it worked for one of you guys, my problem was with a package name that didn't start with a 'com'. changed it, now it works.

hope that helps

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

Just to add to Jon's coding if you needed to take it a step further, and do more than just one column you can add something like

Dim copyRange2 As Range
Dim copyRange3 As Range

Set copyRange2 =src.Range("B2:B" & lastRow)
Set copyRange3 =src.Range("C2:C" & lastRow)

copyRange2.SpecialCells(xlCellTypeVisible).Copy tgt.Range("B12")
copyRange3.SpecialCells(xlCellTypeVisible).Copy tgt.Range("C12")

put these near the other codings that are the same you can easily change the Ranges as you need.

I only add this because it was helpful for me. I'd assume Jon already knows this but for those that are less experienced sometimes it's helpful to see how to change/add/modify these codings. I figured since Ruya didn't know how to manipulate the original coding it could be helpful if one ever needed to copy over only 2 visibile columns, or only 3, etc. You can use this same coding, add in extra lines that are almost the same and then the coding is copying over whatever you need.

I don't have enough reputation to reply to Jon's comment directly so I have to post as a new comment, sorry.

How to: Create trigger for auto update modified date with SQL Server 2008

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

Python Pylab scatter plot error bars (the error on each point is unique)

This is almost like the other answer but you don't need a scatter plot at all, you can simply specify a scatter-plot-like format (fmt-parameter) for errorbar:

import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
e = [0.5, 1., 1.5, 2.]
plt.errorbar(x, y, yerr=e, fmt='o')
plt.show()

Result:

enter image description here

A list of the avaiable fmt parameters can be found for example in the plot documentation:

character   description
'-'     solid line style
'--'    dashed line style
'-.'    dash-dot line style
':'     dotted line style
'.'     point marker
','     pixel marker
'o'     circle marker
'v'     triangle_down marker
'^'     triangle_up marker
'<'     triangle_left marker
'>'     triangle_right marker
'1'     tri_down marker
'2'     tri_up marker
'3'     tri_left marker
'4'     tri_right marker
's'     square marker
'p'     pentagon marker
'*'     star marker
'h'     hexagon1 marker
'H'     hexagon2 marker
'+'     plus marker
'x'     x marker
'D'     diamond marker
'd'     thin_diamond marker
'|'     vline marker
'_'     hline marker

Iterating through a variable length array

You've specifically mentioned a "variable-length array" in your question, so neither of the existing two answers (as I write this) are quite right.

Java doesn't have any concept of a "variable-length array", but it does have Collections, which serve in this capacity. Any collection (technically any "Iterable", a supertype of Collections) can be looped over as simply as this:

Collection<Thing> things = ...;
for (Thing t : things) {
  System.out.println(t);
}

EDIT: it's possible I misunderstood what he meant by 'variable-length'. He might have just meant it's a fixed length but not every instance is the same fixed length. In which case the existing answers would be fine. I'm not sure what was meant.

What is the <leader> in a .vimrc file?

The "Leader key" is a way of extending the power of VIM's shortcuts by using sequences of keys to perform a command. The default leader key is backslash. Therefore, if you have a map of <Leader>Q, you can perform that action by typing \Q.

Ambiguous overload call to abs(double)

The header <math.h> is a C std lib header. It defines a lot of stuff in the global namespace. The header <cmath> is the C++ version of that header. It defines essentially the same stuff in namespace std. (There are some differences, like that the C++ version comes with overloads of some functions, but that doesn't matter.) The header <cmath.h> doesn't exist.

Since vendors don't want to maintain two versions of what is essentially the same header, they came up with different possibilities to have only one of them behind the scenes. Often, that's the C header (since a C++ compiler is able to parse that, while the opposite won't work), and the C++ header just includes that and pulls everything into namespace std. Or there's some macro magic for parsing the same header with or without namespace std wrapped around it or not. To this add that in some environments it's awkward if headers don't have a file extension (like editors failing to highlight the code etc.). So some vendors would have <cmath> be a one-liner including some other header with a .h extension. Or some would map all includes matching <cblah> to <blah.h> (which, through macro magic, becomes the C++ header when __cplusplus is defined, and otherwise becomes the C header) or <cblah.h> or whatever.

That's the reason why on some platforms including things like <cmath.h>, which ought not to exist, will initially succeed, although it might make the compiler fail spectacularly later on.

I have no idea which std lib implementation you use. I suppose it's the one that comes with GCC, but this I don't know, so I cannot explain exactly what happened in your case. But it's certainly a mix of one of the above vendor-specific hacks and you including a header you ought not to have included yourself. Maybe it's the one where <cmath> maps to <cmath.h> with a specific (set of) macro(s) which you hadn't defined, so that you ended up with both definitions.

Note, however, that this code still ought not to compile:

#include <cmath>

double f(double d)
{
  return abs(d);
}

There shouldn't be an abs() in the global namespace (it's std::abs()). However, as per the above described implementation tricks, there might well be. Porting such code later (or just trying to compile it with your vendor's next version which doesn't allow this) can be very tedious, so you should keep an eye on this.

How do I base64 encode (decode) in C?

I fix @ryyst answer's bug and this is a url safe version:

    #include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
 
static char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
                                'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
                                'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
                                'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
                                'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
                                'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
                                'w', 'x', 'y', 'z', '0', '1', '2', '3',
                                '4', '5', '6', '7', '8', '9', '-', '_'};
static char *decoding_table = NULL;
static int mod_table[] = {0, 2, 1};
 
void build_decoding_table() {
 
    decoding_table = malloc(256);
 
    for (int i = 0; i < 64; i++)
        decoding_table[(unsigned char) encoding_table[i]] = i;
}
 
 
void base64_cleanup() {
    free(decoding_table);
} 
 
char *base64_encode(const char *data,
                    size_t input_length,
                    size_t *output_length) {
 
    *output_length = 4 * ((input_length + 2) / 3);
 
    char *encoded_data = malloc(*output_length);
    if (encoded_data == NULL) return NULL;
 
    for (int i = 0, j = 0; i < input_length;) {
 
        uint32_t octet_a = i < input_length ? (unsigned char)data[i++] : 0;
        uint32_t octet_b = i < input_length ? (unsigned char)data[i++] : 0;
        uint32_t octet_c = i < input_length ? (unsigned char)data[i++] : 0;
 
        uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
 
        encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F];
        encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F];
        encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F];
        encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];
    }
 
    //int i=0;
    for (int i = 0; i < mod_table[input_length % 3]; i++)
        encoded_data[*output_length - 1 - i] = '=';
    
    *output_length  = *output_length -2 + mod_table[input_length % 3];
    encoded_data[*output_length] =0;

    return encoded_data;
}
 
 
unsigned char *base64_decode(const char *data,
                             size_t input_length,
                             size_t *output_length) {
 
    if (decoding_table == NULL) build_decoding_table();
 
    if (input_length % 4 != 0) return NULL;
 
    *output_length = input_length / 4 * 3;
    if (data[input_length - 1] == '=') (*output_length)--;
    if (data[input_length - 2] == '=') (*output_length)--;
 
    unsigned char *decoded_data = malloc(*output_length);
    if (decoded_data == NULL) return NULL;
 
    for (int i = 0, j = 0; i < input_length;) {
 
        uint32_t sextet_a = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
        uint32_t sextet_b = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
        uint32_t sextet_c = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
        uint32_t sextet_d = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
 
        uint32_t triple = (sextet_a << 3 * 6)
        + (sextet_b << 2 * 6)
        + (sextet_c << 1 * 6)
        + (sextet_d << 0 * 6);
 
        if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;
        if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;
        if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;
    }
 
    return decoded_data;
}
 
int main(){
    
    const char * data = "Hello World! ??!??!";
    size_t input_size = strlen(data);
    printf("Input size: %ld \n",input_size);
    char * encoded_data = base64_encode(data, input_size, &input_size);
    printf("After size: %ld \n",input_size);
    printf("Encoded Data is: %s \n",encoded_data);
    
    size_t decode_size = strlen(encoded_data);
    printf("Output size: %ld \n",decode_size);
    unsigned char * decoded_data = base64_decode(encoded_data, decode_size, &decode_size);
    printf("After size: %ld \n",decode_size);
    printf("Decoded Data is: %s \n",decoded_data);
    return 0;
}

Simple way to encode a string according to a password?

An other implementation of @qneill code which include CRC checksum of the original message, it throw an exception if the check fail:

import hashlib
import struct
import zlib

def vigenere_encode(text, key):
    text = '{}{}'.format(text, struct.pack('i', zlib.crc32(text)))

    enc = []
    for i in range(len(text)):
        key_c = key[i % len(key)]
        enc_c = chr((ord(text[i]) + ord(key_c)) % 256)
        enc.append(enc_c)

    return base64.urlsafe_b64encode("".join(enc))


def vigenere_decode(encoded_text, key):
    dec = []
    encoded_text = base64.urlsafe_b64decode(encoded_text)
    for i in range(len(encoded_text)):
        key_c = key[i % len(key)]
        dec_c = chr((256 + ord(encoded_text[i]) - ord(key_c)) % 256)
        dec.append(dec_c)

    dec = "".join(dec)
    checksum = dec[-4:]
    dec = dec[:-4]

    assert zlib.crc32(dec) == struct.unpack('i', checksum)[0], 'Decode Checksum Error'

    return dec

Serialize form data to JSON

Trying to solve the same problem (validation without getting into complex plugins and libraries), I created jQuery.serializeJSON, that improves serializeArray to support any kind of nested objects.

This plugin got very popular, but in another project I was using Backbone.js, where I would like to write the validation logic in the Backbone.js models. Then I created Backbone.Formwell, which allows you to show the errors returned by the validation method directly in the form.

Django return redirect() with parameters

Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.

Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:

/link/mybackend/?field1=value1&field2=value2&field3=value3

and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET.

So your urlconf would be:

url(r'^link/(?P<backend>\w+?)/$', my_function)

and the view would look like:

def my_function(request, backend):
   data = request.GET

and the reverse would be (after importing urllib):

return "%s?%s" % (redirect('my_function', args=(backend,)),
                  urllib.urlencode(form.cleaned_data))

Edited after comment

The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.

If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.

That said, if all you want to do is store the data, then just put it in the session:

request.session['temp_data'] = form.cleaned_data

Overflow Scroll css is not working in the div

I edited your: Fiddle

html, body{ margin:0; padding:0; overflow:hidden; height:100% }
.header { margin: 0 auto; width:500px; height:30px; background-color:#dadada;}
.wrapper{ margin: 0 auto; width:500px; overflow:scroll; height: 100%;}

Giving the html-tag a 100% height is the solution. I also deleted the container div. You don't need it when your layout stays like this.

How to gettext() of an element in Selenium Webdriver

You need to store it in a String variable first before displaying it like so:

String Txt = TxtBoxContent.getText();
System.out.println(Txt);

JavaScript variable number of arguments to function

Use the arguments object when inside the function to have access to all arguments passed in.

Displaying a Table in Django from Database

If you want to table do following steps:-

views.py:

def view_info(request):
    objs=Model_name.objects.all()
    ............
    return render(request,'template_name',{'objs':obj})

.html page

 {% for item in objs %}
    <tr> 
         <td>{{ item.field1 }}</td>
         <td>{{ item.field2 }}</td>
         <td>{{ item.field3 }}</td>
         <td>{{ item.field4 }}</td>
    </tr>
       {% endfor %}

Node package ( Grunt ) installed but not available

Sometimes you have to npm install package_name -g for it to work.

AngularJS Error: $injector:unpr Unknown Provider

Be sure that you load controller outsideapp.config. The following code may cause this error:

app.config(["$stateProvider", "$urlRouterProvider", function ($stateProvider, $urlRouterProvider) {
       var AuthCtrl = require('components/auth/AuthCtrl'); //NOTICE HERE
       $stateProvider.state('login',{
            url: "/users/login",
            templateUrl: require("components/auth/login.tpl.html"),
            controller: AuthCtrl // ERROR
        })
}))

To fix this error, we must move AuthCtrl to outsideapp.config:

var AuthCtrl = require('components/auth/AuthCtrl'); //NOTICE HERE
app.config(["$stateProvider", "$urlRouterProvider", function ($stateProvider, $urlRouterProvider) {
       $stateProvider.state('login',{
            url: "/users/login",
            templateUrl: require("components/auth/login.tpl.html"),
            controller: AuthCtrl // WORK
        });
}))

Test if remote TCP port is open from a shell script

If you're using ksh or bash they both support IO redirection to/from a socket using the /dev/tcp/IP/PORT construct. In this Korn shell example I am redirecting no-op's (:) std-in from a socket:

W$ python -m SimpleHTTPServer &
[1]     16833
Serving HTTP on 0.0.0.0 port 8000 ...
W$ : </dev/tcp/127.0.0.1/8000

The shell prints an error if the socket is not open:

W$ : </dev/tcp/127.0.0.1/8001
ksh: /dev/tcp/127.0.0.1/8001: cannot open [Connection refused]

You can therefore use this as the test in an if condition:

SERVER=127.0.0.1 PORT=8000
if (: < /dev/tcp/$SERVER/$PORT) 2>/dev/null
then
    print succeeded
else
    print failed
fi

The no-op is in a subshell so I can throw std-err away if the std-in redirection fails.

I often use /dev/tcp for checking the availability of a resource over HTTP:

W$ print arghhh > grr.html
W$ python -m SimpleHTTPServer &
[1]     16863
Serving HTTP on 0.0.0.0 port 8000 ...
W$ (print -u9 'GET /grr.html HTTP/1.0\n';cat <&9) 9<>/dev/tcp/127.0.0.1/8000
HTTP/1.0 200 OK
Server: SimpleHTTP/0.6 Python/2.6.1
Date: Thu, 14 Feb 2013 12:56:29 GMT
Content-type: text/html
Content-Length: 7
Last-Modified: Thu, 14 Feb 2013 12:55:44 GMT

arghhh
W$ 

This one-liner opens file descriptor 9 for reading from and writing to the socket, prints the HTTP GET to the socket and uses cat to read from the socket.

how to overwrite css style

Yes, you can indeed. There are three ways of achieving this that I can think of.

  1. Add inline styles to the elements.
  2. create and append a new <style> element, and add the text to override this style to it.
  3. Modify the css rule itself.

Notes:

  1. is somewhat messy and adds to the parsing the browser needs to do to render.
  2. perhaps my favourite method
  3. Not cross-browser, some browsers like it done one way, others a different way, while the remainder just baulk at the idea.

How can I create a "Please Wait, Loading..." animation using jQuery?

If you are using Turbolinks With Rails this is my solution:

This is the CoffeeScript

$(window).on 'page:fetch', ->
  $('body').append("<div class='modal'></div>")
  $('body').addClass("loading")

$(window).on 'page:change', ->
  $('body').removeClass("loading")

This is the SASS CSS based on the first excellent answer from Jonathan Sampson

# loader.css.scss

.modal {
    display:    none;
    position:   fixed;
    z-index:    1000;
    top:        0;
    left:       0;
    height:     100%;
    width:      100%;
    background: rgba( 255, 255, 255, 0.4)
            asset-url('ajax-loader.gif', image)
            50% 50% 
            no-repeat;
}
body.loading {
    overflow: hidden;   
}

body.loading .modal {
    display: block;
}

How to replace NA values in a table for selected columns

Starting from the data.table y, you can just write:
y[, (cols):=lapply(.SD, function(i){i[is.na(i)] <- 0; i}), .SDcols = cols]
Don't forget to library(data.table) before creating y and running this command.

How to remove numbers from string using Regex.Replace?

As a string extension:

    public static string RemoveIntegers(this string input)
    {
        return Regex.Replace(input, @"[\d-]", string.Empty);
    }

Usage:

"My text 1232".RemoveIntegers(); // RETURNS "My text "

get the margin size of an element with jquery

You'll want to use...

alert(parseInt($this.parents("div:.item-form").css("marginTop").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginRight").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginBottom").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginLeft").replace('px', '')));

How to change the order of DataFrame columns?

I think this function is more straightforward. You Just need to specify a subset of columns at the start or the end or both:

def reorder_df_columns(df, start=None, end=None):
    """
        This function reorder columns of a DataFrame.
        It takes columns given in the list `start` and move them to the left.
        Its also takes columns in `end` and move them to the right.
    """
    if start is None:
        start = []
    if end is None:
        end = []
    assert isinstance(start, list) and isinstance(end, list)
    cols = list(df.columns)
    for c in start:
        if c not in cols:
            start.remove(c)
    for c in end:
        if c not in cols or c in start:
            end.remove(c)
    for c in start + end:
        cols.remove(c)
    cols = start + cols + end
    return df[cols]

Why I got " cannot be resolved to a type" error?

I had this problem while the other class (CarService) was still empty, no methods, nothing. When it had methods and variables, the error was gone.

calculating the difference in months between two dates

Old question I know, but might help someone. I've used @Adam accepted answer above, but then checked if the difference is 1 or -1 then check to see if it is a full calendar month's difference. So 21/07/55 and 20/08/55 would not be a full month, but 21/07/55 and 21/07/55 would be.

/// <summary>
/// Amended date of birth cannot be greater than or equal to one month either side of original date of birth.
/// </summary>
/// <param name="dateOfBirth">Date of birth user could have amended.</param>
/// <param name="originalDateOfBirth">Original date of birth to compare against.</param>
/// <returns></returns>
public JsonResult ValidateDateOfBirth(string dateOfBirth, string originalDateOfBirth)
{
    DateTime dob, originalDob;
    bool isValid = false;

    if (DateTime.TryParse(dateOfBirth, out dob) && DateTime.TryParse(originalDateOfBirth, out originalDob))
    {
        int diff = ((dob.Month - originalDob.Month) + 12 * (dob.Year - originalDob.Year));

        switch (diff)
        {
            case 0:
                // We're on the same month, so ok.
                isValid = true;
                break;
            case -1:
                // The month is the previous month, so check if the date makes it a calendar month out.
                isValid = (dob.Day > originalDob.Day);
                break;
            case 1:
                // The month is the next month, so check if the date makes it a calendar month out.
                isValid = (dob.Day < originalDob.Day);
                break;
            default:
                // Either zero or greater than 1 month difference, so not ok.
                isValid = false;
                break;
        }
        if (!isValid)
            return Json("Date of Birth cannot be greater than one month either side of the date we hold.", JsonRequestBehavior.AllowGet);
    }
    else
    {
        return Json("Date of Birth is invalid.", JsonRequestBehavior.AllowGet);
    }
    return Json(true, JsonRequestBehavior.AllowGet);
}

What's the difference between JPA and Hibernate?

JPA is a specification that you implement in your data layer to perform db opertations, OR mappings and other required tasks.

Since it is just a specification, you need a tool to have it implemented. That tool can be either Hibernate, TopLink, iBatis, spring-data etc.

You don't necessarily require JPA if you are using Hibernate in your Data Layer. But if you use JPA specification for Hibernate, then it will make switching to other ORM tools like iBatis, TopLink easy in future, because the specification is common for others as well.

*(if you remember, you do import javax.persistence.*; when you use annotations for OR mapping (like @Id, @Column, @GeneratedValue etc.) in Hibernate, that's where you are using JPA under Hibernate, you can use JPA's @Query & other features as well)

How to use ESLint with Jest

Add environment only for __tests__ folder

You could add a .eslintrc.yml file in your __tests__ folders, that extends you basic configuration:

extends: <relative_path to .eslintrc>
env:
    jest: true

If you have only one __tests__folder, this solution is the best since it scope jest environment only where it is needed.

Dealing with many test folders

If you have more test folders (OPs case), I'd still suggest to add those files. And if you have tons of those folders can add them with a simple zsh script:

#!/usr/bin/env zsh

for folder in **/__tests__/ ;do
    count=$(($(tr -cd '/' <<< $folder | wc -c)))
    echo $folder : $count
    cat <<EOF > $folder.eslintrc.yml
extends: $(printf '../%.0s' {1..$count}).eslintrc
env:
    jest: true
EOF
done

This script will look for __tests__ folders and add a .eslintrc.yml file with to configuration shown above. This script has to be launched within the folder containing your parent .eslintrc.

How to make HTML code inactive with comments

HTML Comments:

<!-- <div> This div will not show </div> -->

See Reference

CSS Comments:

/* This style will not apply */

See Reference

JavaScript Comments:

// This single line JavaScript code will not execute

OR

/*
   The whole block of JavaScript code will not execute
*/

See Reference

Best way to store passwords in MYSQL database

First off, md5 and sha1 have been proven to be vulnerable to collision attacks and can be rainbow tabled easily (when they see if you hash is the same in their database of common passwords).

There are currently two things that are secure enough for passwords that you can use.

The first is sha512. sha512 is a sub-version of SHA2. SHA2 has not yet been proven to be vulnerable to collision attacks and sha512 will generate a 512-bit hash. Here is an example of how to use sha512:

<?php
hash('sha512',$password);

The other option is called bcrypt. bcrypt is famous for its secure hashes. It's probably the most secure one out there and most customizable one too.

Before you want to start using bcrypt you need to check if your sever has it enabled, Enter this code:

<?php
if (defined("CRYPT_BLOWFISH") && CRYPT_BLOWFISH) {
    echo "CRYPT_BLOWFISH is enabled!";
}else {
echo "CRYPT_BLOWFISH is not available";
}

If it returns that it is enabled then the next step is easy, All you need to do to bcrypt a password is (note: for more customizability you need to see this How do you use bcrypt for hashing passwords in PHP?):

crypt($password, $salt);

A salt is usually a random string that you add at the end of all your passwords when you hash them. Using a salt means if someone gets your database, they can not check the hashes for common passwords. Checking the database is called using a rainbow table. You should always use a salt when hashing!

Here are my proofs for the SHA1 and MD5 collision attack vulnerabilities:
http://www.schneier.com/blog/archives/2012/10/when_will_we_se.html, http://eprint.iacr.org/2010/413.pdf,
http://people.csail.mit.edu/yiqun/SHA1AttackProceedingVersion.pdf,
http://conf.isi.qut.edu.au/auscert/proceedings/2006/gauravaram06collision.pdf and
Understanding sha-1 collision weakness

Using client certificate in Curl command

This is how I did it:

curl -v \
  --key ./admin-key.pem \
  --cert ./admin.pem \
  https://xxxx/api/v1/

relative path in BAT script

Use this in your batch file:

%~dp0\bin\Iris.exe

%~dp0 resolves to the full path of the folder in which the batch script resides.

How to get an IFrame to be responsive in iOS Safari?

CSS only solution

HTML

<div class="container">
    <div class="h_iframe">
        <iframe  src="//www.youtube.com/embed/9KunP3sZyI0" frameborder="0" allowfullscreen></iframe>
    </div>
</div>

CSS

html,body {
    height:100%;
}
.h_iframe iframe {
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
}

DEMO

Another demo here with HTML page in iframe

How do I find out what version of WordPress is running?

I know I'm super late regarding this topic but there's this easy to use library where you can easily get the version numbers of Worpress, PHP, Apache, and MySQL, all-in-one.

It is called the Wordpress Environment (W18T) library

<?php
include_once 'W18T.class.php';
$environment = new W18T();
echo $environment;
?>

Output

{
    "platform": {
        "name": "WordPress",
        "version": "4.9.1"
    },
    "interpreter": {
        "name": "PHP",
        "version": "7.2.0"
    },
    "web_server": {
        "name": "Apache",
        "version": "2.4.16"
    },
    "database_server": {
        "name": "MySQL",
        "version": "5.7.20"
    },
    "operating_system": {
        "name": "Darwin",
        "version": "17.0.0"
    }
}

I hope it helps.

Stateless vs Stateful

Stateless means there is no memory of the past. Every transaction is performed as if it were being done for the very first time.

Stateful means that there is memory of the past. Previous transactions are remembered and may affect the current transaction.

Stateless:

// The state is derived by what is passed into the function

function int addOne(int number)
{
    return number + 1;
}

Stateful:

// The state is maintained by the function

private int _number = 0; //initially zero

function int addOne()
{
   _number++;
   return _number;
}

Refer from: https://softwareengineering.stackexchange.com/questions/101337/whats-the-difference-between-stateful-and-stateless

ASP.NET MVC: Custom Validation by DataAnnotation

Self validated model

Your model should implement an interface IValidatableObject. Put your validation code in Validate method:

public class MyModel : IValidatableObject
{
    public string Title { get; set; }
    public string Description { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (Title == null)
            yield return new ValidationResult("*", new [] { nameof(Title) });

        if (Description == null)
            yield return new ValidationResult("*", new [] { nameof(Description) });
    }
}

Please notice: this is a server-side validation. It doesn't work on client-side. You validation will be performed only after form submission.

pytest cannot import module while python can

I solved my problem by setting the PYTHONPATH in Environment Variables for the specific configuration I'm running my tests with.

While you're viewing the test file on PyCharm:

  1. Ctrl + Shift + A
  2. Type Edit Configurations
  3. Set your PYTHONPATH under Environment > Environment variables.

Laravel PHP Command Not Found

Late answer...

Composer 1.10.1 2020-03-13 20:34:27 laravel --version Laravel Installer 3.0.1

Put export PATH=$PATH:~/.config/composer/vendor/bin:$PATH in your ~/.zshrc or ~/.bashrc source ~/.zshrc or ~/.bashrc This works