Programs & Examples On #Quoted printable

New lines (\r\n) are not working in email body

If you are sending HTML email then use <BR> (or <BR />, or </BR>) as stated.
If you are sending a plain text email then use %0D%0A
\r = %0D (Ctrl+M = carriage return)
\n = %0A (Ctrl+A = line feed)

If you have an email link in your email,
EG

<A HREF="mailto?To=...&Body=Line 1%250D%250ALine 2">Send email</A>

Then use %250D%250A

%25 = %

Python: Converting from ISO-8859-1/latin1 to UTF-8

Try decoding it first, then encoding:

apple.decode('iso-8859-1').encode('utf8')

Problem with SMTP authentication in PHP using PHPMailer, with Pear Mail works

Check if you have set restrict outgoing SMTP to only some system users (root, MTA, mailman...). That restriction may prevent the spammers, but will redirect outgoing SMTP connections to the local mail server.

How to printf long long

    // acos(0.0) will return value of pi/2, inverse of cos(0) is pi/2 
    double pi = 2 * acos(0.0);
    int n; // upto 6 digit
    scanf("%d",&n); //precision with which you want the value of pi
    printf("%.*lf\n",n,pi); // * will get replaced by n which is the required precision

How to generate an openSSL key using a passphrase from the command line?

genrsa has been replaced by genpkey & when run manually in a terminal it will prompt for a password:

openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096

However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell script:

get_passwd() {
    local passwd=
    echo -ne "Enter passwd for private key: ? "; read -s passwd
    openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}

Convert JSONArray to String Array

You might want to take a look at JSONArray.toList(), which returns a List containing Maps and Lists, which represent your JSON structure. So you can use it with Java Streams like this:

JSONArray array = new JSONArray(jsonString);
List<String> result = array.toList().stream()
        .filter(Map.class::isInstance)
        .map(Map.class::cast)
        .map(o -> o.get("name"))
        .filter(String.class::isInstance)
        .map(String.class::cast)
        .collect(Collectors.toList());

This might just be useful even for more complex objects.

Alternatively you can just use an IntStream to iterate over all items in the JSONArray and map all names:

JSONArray array = new JSONArray(jsonString);
List<String> result = IntStream.range(0, array.length())
        .mapToObj(array::getJSONObject)
        .map(o -> o.getString("name"))
        .collect(Collectors.toList());

Validate SSL certificates with Python

I was having the same problem but wanted to minimize 3rd party dependencies (because this one-off script was to be executed by many users). My solution was to wrap a curl call and make sure that the exit code was 0. Worked like a charm.

How do I center a window onscreen in C#?

 Centering a form in runtime

1.Set following property of Form:
   -> StartPosition : CenterScreen
   -> WindowState: Normal

This will center the form at runtime but if form size is bigger then expected, do second step.

2. Add Custom Size after InitializeComponent();

public Form1()
{
    InitializeComponent();
    this.Size = new Size(800, 600);
}

SQL Server query - Selecting COUNT(*) with DISTINCT

try this:

SELECT
    COUNT(program_name) AS [Count],program_type AS [Type]
    FROM (SELECT DISTINCT program_name,program_type
              FROM cm_production 
              WHERE push_number=@push_number
         ) dt
    GROUP BY program_type

What rules does software version numbering follow?

The usual method I have seen is X.Y.Z, which generally corresponds to major.minor.patch:

  • Major version numbers change whenever there is some significant change being introduced. For example, a large or potentially backward-incompatible change to a software package.
  • Minor version numbers change when a new, minor feature is introduced or when a set of smaller features is rolled out.
  • Patch numbers change when a new build of the software is released to customers. This is normally for small bug-fixes or the like.

Other variations use build numbers as an additional identifier. So you may have a large number for X.Y.Z.build if you have many revisions that are tested between releases. I use a couple of packages that are identified by year/month or year/release. Thus, a release in the month of September of 2010 might be 2010.9 or 2010.3 for the 3rd release of this year.

There are many variants to versioning. It all boils down to personal preference.

For the "1.3v1.1", that may be two different internal products, something that would be a shared library / codebase that is rev'd differently from the main product; that may indicate version 1.3 for the main product, and version 1.1 of the internal library / package.

What is console.log in jQuery?

it will print log messages in your developer console (firebug/webkit dev tools/ie dev tools)

Storing data into list with class

If you want to instantiate and add in the same line, you'd have to do something like this:

lstemail.Add(new EmailData { FirstName = "JOhn", LastName = "Smith", Location = "Los Angeles" });

or just instantiate the object prior, and add it directly in:

EmailData data = new EmailData();
data.FirstName = "JOhn";
data.LastName = "Smith";
data.Location = "Los Angeles"

lstemail.Add(data);

How to return a value from pthread threads in C?

You've returned a pointer to a local variable. That's bad even if threads aren't involved.

The usual way to do this, when the thread that starts is the same thread that joins, would be to pass a pointer to an int, in a location managed by the caller, as the 4th parameter of pthread_create. This then becomes the (only) parameter to the thread's entry-point. You can (if you like) use the thread exit value to indicate success:

#include <pthread.h>
#include <stdio.h>

int something_worked(void) {
    /* thread operation might fail, so here's a silly example */
    void *p = malloc(10);
    free(p);
    return p ? 1 : 0;
}

void *myThread(void *result)
{
   if (something_worked()) {
       *((int*)result) = 42;
       pthread_exit(result);
   } else {
       pthread_exit(0);
   }
}

int main()
{
   pthread_t tid;
   void *status = 0;
   int result;

   pthread_create(&tid, NULL, myThread, &result);
   pthread_join(tid, &status);

   if (status != 0) {
       printf("%d\n",result);
   } else {
       printf("thread failed\n");
   }

   return 0;
}

If you absolutely have to use the thread exit value for a structure, then you'll have to dynamically allocate it (and make sure that whoever joins the thread frees it). That's not ideal, though.

presentViewController and displaying navigation bar

It is true that if you present a view controller modally on the iPhone, it will always be presented full screen no matter how you present it on the top view controller of a navigation controller or any other way around. But you can always show the navigation bar with the following workaround way:

Rather than presenting that view controller modally present a navigation controller modally with its root view controller set as the view controller you want:

MyViewController *myViewController = [[MyViewController alloc] initWithNibName:nil bundle:nil];
UINavigationController *navigationController = 
    [[UINavigationController alloc] initWithRootViewController:myViewController];

//now present this navigation controller modally 
[self presentViewController:navigationController
                   animated:YES
                   completion:^{

                        }];

You should see a navigation bar when your view is presented modally.

Create list of single item repeated N times

As others have pointed out, using the * operator for a mutable object duplicates references, so if you change one you change them all. If you want to create independent instances of a mutable object, your xrange syntax is the most Pythonic way to do this. If you are bothered by having a named variable that is never used, you can use the anonymous underscore variable.

[e for _ in xrange(n)]

Generic htaccess redirect www to non-www

www to non www with https

RewriteEngine on

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Why use ICollection and not IEnumerable or List<T> on many-many/one-many relationships?

I remember it this way:

  1. IEnumerable has one method GetEnumerator() which allows one to read through the values in a collection but not write to it. Most of the complexity of using the enumerator is taken care of for us by the for each statement in C#. IEnumerable has one property: Current, which returns the current element.

  2. ICollection implements IEnumerable and adds few additional properties the most use of which is Count. The generic version of ICollection implements the Add() and Remove() methods.

  3. IList implements both IEnumerable and ICollection, and add the integer indexing access to items (which is not usually required, as ordering is done in database).

How to compare pointers?

It depends on the types of the values, and the way that operators happen to have been defined. For example, string comparison is by value, not by address. But char * is by address normally (I think).

A big trap for the unwary. There is no guaranteed pointer comparison operator, but

  (void *)a == (void *)b 

is probably fairly safe.

jdk7 32 bit windows version to download

Look for "Windows x86", it's the 32 bit version.

Is it possible to clone html element objects in JavaScript / JQuery?

You need to select "#foo2" as your selector. Then, get it with html().

Here is the html:

<div id="foo1">

</div>
<div id="foo2">
    <div>Foo Here</div>
</div>?

Here is the javascript:

$("#foo2").click(function() {
    //alert("clicked");
    var value=$(this).html();
    $("#foo1").html(value);
});?

Here is the jsfiddle: http://jsfiddle.net/fritzdenim/DhCjf/

How to find value using key in javascript dictionary

Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.

If you make Dict into an object, this will work:

var dict = {};
var addPair = function (myKey, myValue) {
    dict[myKey] = myValue;
};
var giveValue = function (myKey) {
    return dict[myKey];
};

The myKey variable is already a string, so you don't need more quotes.

Stacking DIVs on top of each other?

If you mean by literally putting one on the top of the other, one on the top (Same X, Y positions, but different Z position), try using the z-index CSS attribute. This should work (untested)

<div>
    <div style='z-index: 1'>1</div>
    <div style='z-index: 2'>2</div>
    <div style='z-index: 3'>3</div>
    <div style='z-index: 4'>4</div>
</div>

This should show 4 on the top of 3, 3 on the top of 2, and so on. The higher the z-index is, the higher the element is positioned on the z-axis. I hope this helped you :)

Bootstrap Modal sitting behind backdrop

Although the z-index of the .modal is higher than that of the .modal-backdrop, that .modal is in a parent div #content-wrap which has a lower z-index than .modal-backdrop (z-index: 1002 vs z-index: 1030).

Because the parent has lower z-index than the .modal-backdrop everything in it will be behind the modal, irrespective of any z-index given to the children.

If you remove the z-index you have set on both the body div#fullContainer #content-wrap and also on the #ctrlNavPanel, everything seems to work ok.

body div#fullContainer #content-wrap {
  background: #ffffff;
  bottom: 0;
  box-shadow: -5px 0px 8px #000000;
  position: absolute;
  top: 0;
  width: 100%;
}

#ctrlNavPanel {
  background: #333333;
  bottom: 0;
  box-sizing: content-box;
  height: 100%;
  overflow-y: auto;
  position: absolute;
  top: 0;
  width: 250px;
}

NOTE: I think that you may have initially used z-indexes on the #content-wrap and #ctrlNavPanel to ensure the nav sits behind, but that's not necessary because the nav element comes before the content-wrap in the HTML, so you only need to position them, not explicitly set a stacking order.


EDIT As Schmalzy picked up on, the links are no longer clickable. This is because the full-container is 100% wide and so covers the navigation. The quickest way to fix this is to place the navigation inside that div:

<div id="fullContainer">
  <aside id="ctrlNavPanel">
    <ul class="nav-link-list">
      <li><label>Menu</label></li>
      <li><a href="/"><span class="fa fa-lg fa-home"></span> Home</a></li>
      <li><a><span class="fa fa-lg fa-group"></span>About Us</a></li>
      <li><a><span class="fa fa-lg fa-book"></span> Contacts</a></li>
    </ul>
  </aside>
  <div id="content-wrap">
    ...
  </div>
</div>

DEMO HERE

Rails: Default sort order for a rails model?

A quick update to Michael's excellent answer above.

For Rails 4.0+ you need to put your sort in a block like this:

class Book < ActiveRecord::Base
  default_scope { order('created_at DESC') }
end

Notice that the order statement is placed in a block denoted by the curly braces.

They changed it because it was too easy to pass in something dynamic (like the current time). This removes the problem because the block is evaluated at runtime. If you don't use a block you'll get this error:

Support for calling #default_scope without a block is removed. For example instead of default_scope where(color: 'red'), please use default_scope { where(color: 'red') }. (Alternatively you can just redefine self.default_scope.)

As @Dan mentions in his comment below, you can do a more rubyish syntax like this:

class Book < ActiveRecord::Base
  default_scope { order(created_at: :desc) }
end

or with multiple columns:

class Book < ActiveRecord::Base
  default_scope { order({begin_date: :desc}, :name) }
end

Thanks @Dan!

Oracle query to fetch column names

On Several occasions, we would need comma separated list of all the columns from a table in a schema. In such cases we can use this generic function which fetches the comma separated list as a string.

CREATE OR REPLACE FUNCTION cols(
    p_schema_name IN VARCHAR2,
    p_table_name  IN VARCHAR2)
  RETURN VARCHAR2
IS
  v_string VARCHAR2(4000);
BEGIN
  SELECT LISTAGG(COLUMN_NAME , ',' ) WITHIN GROUP (
  ORDER BY ROWNUM )
  INTO v_string
  FROM ALL_TAB_COLUMNS
  WHERE OWNER    = p_schema_name
  AND table_name = p_table_name;
  RETURN v_string;
END;
/

So, simply calling the function from the query yields a row with all the columns.

select cols('HR','EMPLOYEES') FROM DUAL;

EMPLOYEE_ID,FIRST_NAME,LAST_NAME,EMAIL,PHONE_NUMBER,HIRE_DATE,JOB_ID,SALARY,COMMISSION_PCT,MANAGER_ID,DEPARTMENT_ID

Note: LISTAGG will fail if the combined length of all columns exceed 4000 characters which is rare. For most cases , this will work.

Convert JS Object to form data

I had a scenario where nested JSON had to be serialised in a linear fashion while form data is constructed, since this is how server expects values. So, I wrote a small recursive function which translates the JSON which is like this:

{
   "orderPrice":"11",
   "cardNumber":"************1234",
   "id":"8796191359018",
   "accountHolderName":"Raj Pawan",
   "expiryMonth":"02",
   "expiryYear":"2019",
   "issueNumber":null,
   "billingAddress":{
      "city":"Wonderland",
      "code":"8796682911767",
      "firstname":"Raj Pawan",
      "lastname":"Gumdal",
      "line1":"Addr Line 1",
      "line2":null,
      "state":"US-AS",
      "region":{
         "isocode":"US-AS"
      },
      "zip":"76767-6776"
   }
}

Into something like this:

{
   "orderPrice":"11",
   "cardNumber":"************1234",
   "id":"8796191359018",
   "accountHolderName":"Raj Pawan",
   "expiryMonth":"02",
   "expiryYear":"2019",
   "issueNumber":null,
   "billingAddress.city":"Wonderland",
   "billingAddress.code":"8796682911767",
   "billingAddress.firstname":"Raj Pawan",
   "billingAddress.lastname":"Gumdal",
   "billingAddress.line1":"Addr Line 1",
   "billingAddress.line2":null,
   "billingAddress.state":"US-AS",
   "billingAddress.region.isocode":"US-AS",
   "billingAddress.zip":"76767-6776"
}

The server would accept form data which is in this converted format.

Here is the function:

function jsonToFormData (inJSON, inTestJSON, inFormData, parentKey) {
    // http://stackoverflow.com/a/22783314/260665
    // Raj: Converts any nested JSON to formData.
    var form_data = inFormData || new FormData();
    var testJSON = inTestJSON || {};
    for ( var key in inJSON ) {
        // 1. If it is a recursion, then key has to be constructed like "parent.child" where parent JSON contains a child JSON
        // 2. Perform append data only if the value for key is not a JSON, recurse otherwise!
        var constructedKey = key;
        if (parentKey) {
            constructedKey = parentKey + "." + key;
        }

        var value = inJSON[key];
        if (value && value.constructor === {}.constructor) {
            // This is a JSON, we now need to recurse!
            jsonToFormData (value, testJSON, form_data, constructedKey);
        } else {
            form_data.append(constructedKey, inJSON[key]);
            testJSON[constructedKey] = inJSON[key];
        }
    }
    return form_data;
}

Invocation:

        var testJSON = {};
        var form_data = jsonToFormData (jsonForPost, testJSON);

I am using testJSON just to see the converted results since I would not be able to extract the contents of form_data. AJAX post call:

        $.ajax({
            type: "POST",
            url: somePostURL,
            data: form_data,
            processData : false,
            contentType : false,
            success: function (data) {
            },
            error: function (e) {
            }
        });

Get time of specific timezone

If you know the UTC offset then you can pass it and get the time using the following function:

function calcTime(city, offset) {
    // create Date object for current location
    var d = new Date();

    // convert to msec
    // subtract local time zone offset
    // get UTC time in msec
    var utc = d.getTime() + (d.getTimezoneOffset() * 60000);

    // create new Date object for different city
    // using supplied offset
    var nd = new Date(utc + (3600000*offset));

    // return time as a string
    return "The local time for city"+ city +" is "+ nd.toLocaleString();
}

alert(calcTime('Bombay', '+5.5'));

Taken from: Convert Local Time to Another

Inserting created_at data with Laravel

In your User model, add the following line in the User class:

public $timestamps = true;

Now, whenever you save or update a user, Laravel will automatically update the created_at and updated_at fields.


Update:
If you want to set the created at manually you should use the date format Y-m-d H:i:s. The problem is that the format you have used is not the same as Laravel uses for the created_at field.

Update: Nov 2018 Laravel 5.6 "message": "Access level to App\\Note::$timestamps must be public", Make sure you have the proper access level as well. Laravel 5.6 is public.

How do I exclude Weekend days in a SQL Server query?

Assuming you're using SQL Server, use DATEPART with dw:

SELECT date_created
FROM your_table
WHERE DATEPART(dw, date_created) NOT IN (1, 7);

EDIT: I should point out that the actual numeric value returned by DATEPART(dw) is determined by the value set by using SET DATEFIRST:
http://msdn.microsoft.com/en-us/library/ms181598.aspx

Property [title] does not exist on this collection instance

$about = DB::where('page', 'about-me')->first(); 

in stead of get().

It works on my project. Thanks.

How to insert blank lines in PDF?

You can add Blank Line throw PdfContentByte class in itextPdf. As shown below:

package com.pdf.test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class Ranvijay {

    public static final String RESULT = "d:/printReport.pdf";

    public void createPdf(String filename) throws Exception {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(filename));
        document.open();

        Font bold = new Font(Font.FontFamily.HELVETICA, 8f, Font.BOLD);
        Font normal = new Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL);
        PdfPTable tabletmp = new PdfPTable(1);
        tabletmp.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        tabletmp.setWidthPercentage(100);
        PdfPTable table = new PdfPTable(2);
        float[] colWidths = { 45, 55 };
        table.setWidths(colWidths);
        String imageUrl = "http://ssl.gstatic.com/s2/oz/images/logo/2x/googleplus_color_33-99ce54a16a32f6edc61a3e709eb61d31.png";
        Image image2 = Image.getInstance(new URL(imageUrl));
        image2.setWidthPercentage(60);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);
        PdfPCell cell = new PdfPCell();
        cell.setBorder(Rectangle.NO_BORDER);
        cell.addElement(image2);
        table.addCell(cell);
        String email = "[email protected]";
        String collectionDate = "09/09/09";
        Chunk chunk1 = new Chunk("Date: ", normal);
        Phrase ph1 = new Phrase(chunk1);

        Chunk chunk2 = new Chunk(collectionDate, bold);
        Phrase ph2 = new Phrase(chunk2);

        Chunk chunk3 = new Chunk("\nEmail: ", normal);
        Phrase ph3 = new Phrase(chunk3);

        Chunk chunk4 = new Chunk(email, bold);
        Phrase ph4 = new Phrase(chunk4);

        Paragraph ph = new Paragraph();
        ph.add(ph1);
        ph.add(ph2);
        ph.add(ph3);
        ph.add(ph4);

        table.addCell(ph);
        tabletmp.addCell(table);
        PdfContentByte canvas = writer.getDirectContent();
        canvas.saveState();
        canvas.setLineWidth((float) 10 / 10);
        canvas.moveTo(40, 806 - (5 * 10));
        canvas.lineTo(555, 806 - (5 * 10));
        canvas.stroke();
        document.add(tabletmp);
        canvas.restoreState();
        PdfPTable tabletmp1 = new PdfPTable(1);
        tabletmp1.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        tabletmp1.setWidthPercentage(100);

        document.add(tabletmp1);

        document.close();
    }

    /**
     * Main method.
     * 
     * @param args
     *            no arguments needed
     * @throws DocumentException
     * @throws IOException
     */
    public static void main(String[] args) throws Exception {
        new Ranvijay().createPdf(RESULT);
        System.out.println("Done Please check........");
    }

}

Convert ascii value to char

for (int i = 0; i < 5; i++){
    int asciiVal = rand()%26 + 97;
    char asciiChar = asciiVal;
    cout << asciiChar << " and ";
}

How do I get a reference to the app delegate in Swift?

In the Xcode 6.2, this also works

let appDelegate = UIApplication.sharedApplication().delegate! as AppDelegate

let aVariable = appDelegate.someVariable

file_get_contents behind a proxy?

Depending on how the proxy login works stream_context_set_default might help you.

$context  = stream_context_set_default(
  array(
    'http'=>array(
      'header'=>'Authorization: Basic ' . base64_encode('username'.':'.'userpass')
    )
  )
);
$result = file_get_contents('http://..../...');

MySQL: determine which database is selected?

slightly off-topic (using the CLI instead of PHP), but still worth knowing: You can set the prompt to display the default database by using any of the following

mysql --prompt='\d> '
export MYSQL_PS1='\d> '

or once inside

prompt \d>\_
\R \d>\_

How to click a href link using Selenium

How to click on link without using click method in selenum?

This is a tricky question. Follow the below steps:

driver.get("https://www.google.com");
String gmaillink= driver.findElement(By.xpath("//a[@href='https://mail.google.com/mail/?tab=wm&ogbl']")).getAttribute("href");
System.out.println(gmaillink);
driver.get(gmaillink);

Deleting multiple columns based on column names in Pandas

You can just pass the column names as a list with specifying the axis as 0 or 1

  • axis=1: Along the Rows
  • axis=0: Along the Columns
  • By default axis=0

    data.drop(["Colname1","Colname2","Colname3","Colname4"],axis=1)

How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?

Use window.URL:

> s = 'http://www.example.com/index.html?1111342=Adam%20Franco&348572=Bob%20Jones'
> u = new URL(s)
> Array.from(u.searchParams.entries())
[["1111342", "Adam Franco"], ["348572", "Bob Jones"]]

Java: Converting String to and from ByteBuffer and associated problems

Check out the CharsetEncoder and CharsetDecoder API descriptions - You should follow a specific sequence of method calls to avoid this problem. For example, for CharsetEncoder:

  1. Reset the encoder via the reset method, unless it has not been used before;
  2. Invoke the encode method zero or more times, as long as additional input may be available, passing false for the endOfInput argument and filling the input buffer and flushing the output buffer between invocations;
  3. Invoke the encode method one final time, passing true for the endOfInput argument; and then
  4. Invoke the flush method so that the encoder can flush any internal state to the output buffer.

By the way, this is the same approach I am using for NIO although some of my colleagues are converting each char directly to a byte in the knowledge they are only using ASCII, which I can imagine is probably faster.

Cleanest way to toggle a boolean variable in Java?

Before:

boolean result = isresult();
if (result) {
    result = false;
} else {
    result = true;
}

After:

boolean result = isresult();
result ^= true;

get dataframe row count based on conditions

You are asking for the condition where all the conditions are true, so len of the frame is the answer, unless I misunderstand what you are asking

In [17]: df = DataFrame(randn(20,4),columns=list('ABCD'))

In [18]: df[(df['A']>0) & (df['B']>0) & (df['C']>0)]
Out[18]: 
           A         B         C         D
12  0.491683  0.137766  0.859753 -1.041487
13  0.376200  0.575667  1.534179  1.247358
14  0.428739  1.539973  1.057848 -1.254489

In [19]: df[(df['A']>0) & (df['B']>0) & (df['C']>0)].count()
Out[19]: 
A    3
B    3
C    3
D    3
dtype: int64

In [20]: len(df[(df['A']>0) & (df['B']>0) & (df['C']>0)])
Out[20]: 3

Base64: java.lang.IllegalArgumentException: Illegal character

Just use the below code to resolve this:

JsonObject obj = Json.createReader(new ByteArrayInputStream(Base64.getDecoder().decode(accessToken.split("\\.")[1].
                        replace('-', '+').replace('_', '/')))).readObject();

In the above code replace('-', '+').replace('_', '/') did the job. For more details see the https://jwt.io/js/jwt.js. I understood the problem from the part of the code got from that link:

function url_base64_decode(str) {
  var output = str.replace(/-/g, '+').replace(/_/g, '/');
  switch (output.length % 4) {
    case 0:
      break;
    case 2:
      output += '==';
      break;
    case 3:
      output += '=';
      break;
    default:
      throw 'Illegal base64url string!';
  }
  var result = window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
  try{
    return decodeURIComponent(escape(result));
  } catch (err) {
    return result;
  }
}

How to redirect to action from JavaScript method?

(This is more of a comment but I can't comment because of the low reputation, somebody might find these useful)

If you're in sth.com/product and you want to redirect to sth.com/product/index use

window.location.href = "index";

If you want to redirect to sth.com/home

window.location.href = "/home";

and if you want you want to redirect to sth.com/home/index

window.location.href = "/home/index";

How to make picturebox transparent?

Just use the Form Paint method and draw every Picturebox on it, it allows transparency :

    private void frmGame_Paint(object sender, PaintEventArgs e)
    {
        DoubleBuffered = true;
        for (int i = 0; i < Controls.Count; i++)
            if (Controls[i].GetType() == typeof(PictureBox))
            {
                var p = Controls[i] as PictureBox;
                p.Visible = false;
                e.Graphics.DrawImage(p.Image, p.Left, p.Top, p.Width, p.Height);
            }
    }

How can I pass a member function where a free function is expected?

If you actually don't need to use the instance a (i.e. you can make it static like @mathengineer 's answer) you can simply pass in a non-capture lambda. (which decay to function pointer)


#include <iostream>

class aClass
{
public:
   void aTest(int a, int b)
   {
      printf("%d + %d = %d", a, b, a + b);
   }
};

void function1(void (*function)(int, int))
{
    function(1, 1);
}

int main()
{
   //note: you don't need the `+`
   function1(+[](int a,int b){return aClass{}.aTest(a,b);}); 
}

Wandbox


note: if aClass is costly to construct or has side effect, this may not be a good way.

Laravel 5.2 - pluck() method returns array

In Laravel 5.1+, you can use the value() instead of pluck.

To get first occurence, You can either use

DB::table('users')->value('name');

or use,

DB::table('users')->where('id', 1)->pluck('name')->first();

Random "Element is no longer attached to the DOM" StaleElementReferenceException

I had the same problem and mine was caused by an old selenium version. I cannot update to a newer version due to development environment. The problem is caused by HTMLUnitWebElement.switchFocusToThisIfNeeded(). When you navigate to a new page it might happen that the element you clicked on the old page is the oldActiveElement (see below). Selenium tries to get context from the old element and fails. That's why they built a try catch in future releases.

Code from selenium-htmlunit-driver version < 2.23.0:

private void switchFocusToThisIfNeeded() {
    HtmlUnitWebElement oldActiveElement =
        ((HtmlUnitWebElement)parent.switchTo().activeElement());

    boolean jsEnabled = parent.isJavascriptEnabled();
    boolean oldActiveEqualsCurrent = oldActiveElement.equals(this);
    boolean isBody = oldActiveElement.getTagName().toLowerCase().equals("body");
    if (jsEnabled &&
        !oldActiveEqualsCurrent &&
        !isBody) {
      oldActiveElement.element.blur();
      element.focus();
    }
}

Code from selenium-htmlunit-driver version >= 2.23.0:

private void switchFocusToThisIfNeeded() {
    HtmlUnitWebElement oldActiveElement =
        ((HtmlUnitWebElement)parent.switchTo().activeElement());

    boolean jsEnabled = parent.isJavascriptEnabled();
    boolean oldActiveEqualsCurrent = oldActiveElement.equals(this);
    try {
        boolean isBody = oldActiveElement.getTagName().toLowerCase().equals("body");
        if (jsEnabled &&
            !oldActiveEqualsCurrent &&
            !isBody) {
        oldActiveElement.element.blur();
        }
    } catch (StaleElementReferenceException ex) {
      // old element has gone, do nothing
    }
    element.focus();
}

Without updating to 2.23.0 or newer you can just give any element on the page focus. I just used element.click() for example.

Invalid shorthand property initializer

In options object you have used "=" sign to assign value to port but we have to use ":" to assign values to properties in object when using object literal to create an object i.e."{}" ,these curly brackets. Even when you use function expression or create an object inside object you have to use ":" sign. for e.g.:

    var rishabh = {
        class:"final year",
        roll:123,
        percent: function(marks1, marks2, marks3){
                      total = marks1 + marks2 + marks3;
                      this.percentage = total/3 }
                    };

john.percent(85,89,95);
console.log(rishabh.percentage);

here we have to use commas "," after each property. but you can use another style to create and initialize an object.

var john = new Object():
john.father = "raja";  //1st way to assign using dot operator
john["mother"] = "rani";// 2nd way to assign using brackets and key must be string

Python's most efficient way to choose longest string in list?

From the Python documentation itself, you can use max:

>>> mylist = ['123','123456','1234']
>>> print max(mylist, key=len)
123456

Does delete on a pointer to a subclass call the base class destructor?

I was wondering why my class' destructor was not called. The reason was that I had forgot to include definition of that class (#include "class.h"). I only had a declaration like "class A;" and the compiler was happy with it and let me call "delete".

Remove a CLASS for all child elements

This should work:

$("#table-filters>ul>li.active").removeClass("active");
//Find all `li`s with class `active`, children of `ul`s, children of `table-filters`

SQL Server - Convert date field to UTC

I do not believe the above code will work. The reason is that it depends upon the difference between the current date in local and UTC times. For example, here in California we are now in PDT (Pacific Daylight Time); the difference between this time and UTC is 7 hours. The code provided will, if run now, add 7 hours to every date which is desired to be converted. But if a historical stored date, or a date in the future, is converted, and that date is not during daylight savings time, it will still add 7, when the correct offset is 8. Bottom line: you cannot convert date/times properly between time zones (including UTC, which does not obey daylight savings time) by only looking at the current date. You must consider the date itself that you are converting, as to whether daylight time was in force on that date. Furthermore, the dates at which daylight and standard times change themselves have changed (George Bush changed the dates during his administration for the USA!). In other words, any solution which even references getdate() or getutcdate() does not work. It must parse the actual date to be converted.

Get local IP address in Node.js

Here's my utility method for getting the local IP address, assuming you are looking for an IPv4 address and the machine only has one real network interface. It could easily be refactored to return an array of IP addresses for multi-interface machines.

function getIPAddress() {
  var interfaces = require('os').networkInterfaces();
  for (var devName in interfaces) {
    var iface = interfaces[devName];

    for (var i = 0; i < iface.length; i++) {
      var alias = iface[i];
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal)
        return alias.address;
    }
  }
  return '0.0.0.0';
}

Use dynamic variable names in `dplyr`

Since you are dynamically building a variable name as a character value, it makes more sense to do assignment using standard data.frame indexing which allows for character values for column names. For example:

multipetal <- function(df, n) {
    varname <- paste("petal", n , sep=".")
    df[[varname]] <- with(df, Petal.Width * n)
    df
}

The mutate function makes it very easy to name new columns via named parameters. But that assumes you know the name when you type the command. If you want to dynamically specify the column name, then you need to also build the named argument.


dplyr version >= 1.0

With the latest dplyr version you can use the syntax from the glue package when naming parameters when using :=. So here the {} in the name grab the value by evaluating the expression inside.

multipetal <- function(df, n) {
  mutate(df, "petal.{n}" := Petal.Width * n)
}

dplyr version >= 0.7

dplyr starting with version 0.7 allows you to use := to dynamically assign parameter names. You can write your function as:

# --- dplyr version 0.7+---
multipetal <- function(df, n) {
    varname <- paste("petal", n , sep=".")
    mutate(df, !!varname := Petal.Width * n)
}

For more information, see the documentation available form vignette("programming", "dplyr").


dplyr (>=0.3 & <0.7)

Slightly earlier version of dplyr (>=0.3 <0.7), encouraged the use of "standard evaluation" alternatives to many of the functions. See the Non-standard evaluation vignette for more information (vignette("nse")).

So here, the answer is to use mutate_() rather than mutate() and do:

# --- dplyr version 0.3-0.5---
multipetal <- function(df, n) {
    varname <- paste("petal", n , sep=".")
    varval <- lazyeval::interp(~Petal.Width * n, n=n)
    mutate_(df, .dots= setNames(list(varval), varname))
}

dplyr < 0.3

Note this is also possible in older versions of dplyr that existed when the question was originally posed. It requires careful use of quote and setName:

# --- dplyr versions < 0.3 ---
multipetal <- function(df, n) {
    varname <- paste("petal", n , sep=".")
    pp <- c(quote(df), setNames(list(quote(Petal.Width * n)), varname))
    do.call("mutate", pp)
}

JQuery show/hide when hover

I hope my script help you.

<i class="mostrar-producto">mostrar...</i>
<div class="producto" style="display:none;position: absolute;">Producto</div>

My script

<script>
$(".mostrar-producto").mouseover(function(){
     $(".producto").fadeIn();
 });

 $(".mostrar-producto").mouseleave(function(){
      $(".producto").fadeOut();
  });
</script>

Updating an object with setState in React

Simple and dynamic way.

This will do the job, but you need to set all the ids to the parent so the parent will point to the name of the object, being id = "jasper" and name the name of the input element = property inside of the object jasper.

handleChangeObj = ({target: { id , name , value}}) => this.setState({ [id]: { ...this.state[id] , [name]: value } });

Disable XML validation in Eclipse

Window > Preferences > Validation > uncheck XML Validator Manual and Build enter image description here

How to use activity indicator view on iPhone?

Using Storyboard-

Create-

  • Go to main.storyboard (This can be found in theProject Navigator on the left hand side of your Xcode) and drag and drop the "Activity Indicator View" from the Object Library.

Activity Indicator View from Object Library

  • Go to the header file and create an IBOutlet for the UIActivityIndicatorView-

     @interface ViewController : UIViewController
    
         @property (nonatomic,strong) IBOutlet UIActivityIndicatorView *activityIndicatorView;
    
     @end
    
  • Establish the connection from the Outlets to the UIActivityIndicatorView.

Start:

Use the following code when you need to start the activity indicator using following code in your implementation file(.m)-

 [self.activityIndicatorView startAnimating];

Stop:

Use the following code when you need to stop the activity indicator using following code in your implementation file(.m)-

 [self.activityIndicatorView stopAnimating];

Hibernate problem - "Use of @OneToMany or @ManyToMany targeting an unmapped class"

In my case a has to add my classes, when building the SessionFactory, with addAnnotationClass

Configuration configuration.configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration
            .addAnnotatedClass(MyEntity1.class)
            .addAnnotatedClass(MyEntity2.class)
            .buildSessionFactory(builder.build());

Resize svg when window is resized in d3.js

_x000D_
_x000D_
d3.select("div#chartId")
   .append("div")
   // Container class to make it responsive.
   .classed("svg-container", true) 
   .append("svg")
   // Responsive SVG needs these 2 attributes and no width and height attr.
   .attr("preserveAspectRatio", "xMinYMin meet")
   .attr("viewBox", "0 0 600 400")
   // Class to make it responsive.
   .classed("svg-content-responsive", true)
   // Fill with a rectangle for visualization.
   .append("rect")
   .classed("rect", true)
   .attr("width", 600)
   .attr("height", 400);
_x000D_
.svg-container {
  display: inline-block;
  position: relative;
  width: 100%;
  padding-bottom: 100%; /* aspect ratio */
  vertical-align: top;
  overflow: hidden;
}
.svg-content-responsive {
  display: inline-block;
  position: absolute;
  top: 10px;
  left: 0;
}

svg .rect {
  fill: gold;
  stroke: steelblue;
  stroke-width: 5px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

<div id="chartId"></div>
_x000D_
_x000D_
_x000D_

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

When you export you use the compatibility system set to MYSQL40. Worked for me.

Oracle copy data to another table

If you want to create table with data . First create the table :

create table new_table as ( select * from old_table); 

and then insert

insert into new_table ( select * from old_table);

If you want to create table without data . You can use :

create table new_table as ( select * from old_table where 1=0);

SQL Server: Query fast, but slow from procedure

I found the problem, here's the script of the slow and fast versions of the stored procedure:

dbo.ViewOpener__RenamedForCruachan__Slow.PRC

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Slow
    @SessionGUID uniqueidentifier
AS

SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

dbo.ViewOpener__RenamedForCruachan__Fast.PRC

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Fast
    @SessionGUID uniqueidentifier 
AS

SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

If you didn't spot the difference, I don't blame you. The difference is not in the stored procedure at all. The difference that turns a fast 0.5 cost query into one that does an eager spool of 6 million rows:

Slow: SET ANSI_NULLS OFF

Fast: SET ANSI_NULLS ON


This answer also could be made to make sense, since the view does have a join clause that says:

(table.column IS NOT NULL)

So there is some NULLs involved.


The explanation is further proved by returning to Query Analizer, and running

SET ANSI_NULLS OFF

.

DECLARE @SessionGUID uniqueidentifier
SET @SessionGUID = 'BCBA333C-B6A1-4155-9833-C495F22EA908'

.

SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank

And the query is slow.


So the problem isn't because the query is being run from a stored procedure. The problem is that Enterprise Manager's connection default option is ANSI_NULLS off, rather than ANSI_NULLS on, which is QA's default.

Microsoft acknowledges this fact in KB296769 (BUG: Cannot use SQL Enterprise Manager to create stored procedures containing linked server objects). The workaround is include the ANSI_NULLS option in the stored procedure dialog:

Set ANSI_NULLS ON
Go
Create Proc spXXXX as
....

What is the purpose of Order By 1 in SQL select statement?

As mentioned in other answers ORDER BY 1 orders by the first column.

I came across another example of where you might use it though. We have certain queries which need to be ordered select the same column. You would get a SQL error if ordering by Name in the below.

SELECT Name, Name FROM Segment ORDER BY 1

RSA Public Key format

Reference Decoder of CRL,CRT,CSR,NEW CSR,PRIVATE KEY, PUBLIC KEY,RSA,RSA Public Key Parser

RSA Public Key

-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----

Encrypted Private Key

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
-----END RSA PRIVATE KEY-----

CRL

-----BEGIN X509 CRL-----
-----END X509 CRL-----

CRT

-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----

CSR

-----BEGIN CERTIFICATE REQUEST-----
-----END CERTIFICATE REQUEST-----

NEW CSR

-----BEGIN NEW CERTIFICATE REQUEST-----
-----END NEW CERTIFICATE REQUEST-----

PEM

-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----

PKCS7

-----BEGIN PKCS7-----
-----END PKCS7-----

PRIVATE KEY

-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----

DSA KEY

-----BEGIN DSA PRIVATE KEY-----
-----END DSA PRIVATE KEY-----

Elliptic Curve

-----BEGIN EC PRIVATE KEY-----
-----END EC PRIVATE KEY-----

PGP Private Key

-----BEGIN PGP PRIVATE KEY BLOCK-----
-----END PGP PRIVATE KEY BLOCK-----

PGP Public Key

-----BEGIN PGP PUBLIC KEY BLOCK-----
-----END PGP PUBLIC KEY BLOCK-----

How to handle the `onKeyPress` event in ReactJS?

You need to call event.persist(); this method on your keyPress event. Example:

const MyComponent = (props) => {
   const keyboardEvents = (event) =>{
       event.persist();
       console.log(event.key); // this will return string of key name like 'Enter'
   }
   return(
         <div onKeyPress={keyboardEvents}></div>
   )
}

If you now type console.log(event) in keyboardEvents function you will get other attributes like:

keyCode // number
charCode // number
shiftKey // boolean
ctrlKey // boolean
altKey // boolean

And many other attributes

Thanks & Regards

P.S: React Version : 16.13.1

How can I pass request headers with jQuery's getJSON() method?

I agree with sunetos that you'll have to use the $.ajax function in order to pass request headers. In order to do that, you'll have to write a function for the beforeSend event handler, which is one of the $.ajax() options. Here's a quick sample on how to do that:

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $.ajax({
          url: 'service.svc/Request',
          type: 'GET',
          dataType: 'json',
          success: function() { alert('hello!'); },
          error: function() { alert('boo!'); },
          beforeSend: setHeader
        });
      });

      function setHeader(xhr) {
        xhr.setRequestHeader('securityCode', 'Foo');
        xhr.setRequestHeader('passkey', 'Bar');
      }
    </script>
  </head>
  <body>
    <h1>Some Text</h1>
  </body>
</html>

If you run the code above and watch the traffic in a tool like Fiddler, you'll see two requests headers passed in:

  • securityCode with a value of Foo
  • passkey with a value of Bar

The setHeader function could also be inline in the $.ajax options, but I wanted to call it out.

Hope this helps!

removing bold styling from part of a header

It is super simple, By using "font" inside paragraph. An example is shown below:

<h1>Heading 1</h1>
<p><font size="6"> Heading 1</font></p>

Heading 1

Heading 1

JavaScript, get date of the next day

Copy-pasted from here: Incrementing a date in JavaScript

Three options for you:

Using just JavaScript's Date object (no libraries):

var today = new Date();
var tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000));

Or if you don't mind changing the date in place (rather than creating a new date):

var dt = new Date();
dt.setTime(dt.getTime() + (24 * 60 * 60 * 1000));

Edit: See also Jigar's answer and David's comment below: var tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1);

Using MomentJS:

var today = moment();
var tomorrow = moment(today).add(1, 'days');

(Beware that add modifies the instance you call it on, rather than returning a new instance, so today.add(1, 'days') would modify today. That's why we start with a cloning op on var tomorrow = ....)

Using DateJS, but it hasn't been updated in a long time:

var today = new Date(); // Or Date.today()
var tomorrow = today.add(1).day();

intellij incorrectly saying no beans of type found for autowired repository

I had this same issue when creating a Spring Boot application using their @SpringBootApplication annotation. This annotation represents @Configuration, @EnableAutoConfiguration and @ComponentScan according to the spring reference.

As expected, the new annotation worked properly and my application ran smoothly but, Intellij kept complaining about unfulfilled @Autowire dependencies. As soon as I changed back to using @Configuration, @EnableAutoConfiguration and @ComponentScan separately, the errors ceased. It seems Intellij 14.0.3 (and most likely, earlier versions too) is not yet configured to recognise the @SpringBootApplication annotation.

For now, if the errors disturb you that much, then revert back to those three separate annotations. Otherwise, ignore Intellij...your dependency resolution is correctly configured, since your test passes.

Always remember...

Man is always greater than machine.

How to set image button backgroundimage for different state?

i think you problem is not the selector file.

you have to add

<imagebutton ..
    android:clickable="true"
/>

to your image buttons.

by default the onClick is handled at the listitem level (parent). and the imageButtons dont recieve the onClick.

when you add the above attribute the image button will receive the event and the selector will be used.

check this POST which explains the same for checkbox.

How to add font-awesome to Angular 2 + CLI project

To use Font Awesome 5 in your Angular project, insert the code below in the of the src/index.html file.

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous">

Good luck!

How to hide only the Close (x) button?

We can hide close button on form by setting this.ControlBox=false;

Note that this hides all of those sizing buttons. Not just the X. In some cases that may be fine.

Where should I put <script> tags in HTML markup?

Non-blocking script tags can be placed just about anywhere:

<script src="script.js" async></script>
<script src="script.js" defer></script>
<script src="script.js" async defer></script>
  • async script will be executed asynchronously as soon as it is available
  • defer script is executed when the document has finished parsing
  • async defer script falls back to the defer behavior if async is not supported

Such scripts will be executed asynchronously/after document ready, which means you cannot do this:

<script src="jquery.js" async></script>
<script>jQuery(something);</script>
<!--
  * might throw "jQuery is not defined" error
  * defer will not work either
-->

Or this:

<script src="document.write(something).js" async></script>
<!--
  * might issue "cannot write into document from an asynchronous script" warning
  * defer will not work either
-->

Or this:

<script src="jquery.js" async></script>
<script src="jQuery(something).js" async></script>
<!--
  * might throw "jQuery is not defined" error (no guarantee which script runs first)
  * defer will work in sane browsers
-->

Or this:

<script src="document.getElementById(header).js" async></script>
<div id="header"></div>
<!--
  * might not locate #header (script could fire before parser looks at the next line)
  * defer will work in sane browsers
-->

Having said that, asynchronous scripts offer these advantages:

  • Parallel download of resources:
    Browser can download stylesheets, images and other scripts in parallel without waiting for a script to download and execute.
  • Source order independence:
    You can place the scripts inside head or body without worrying about blocking (useful if you are using a CMS). Execution order still matters though.

It is possible to circumvent the execution order issues by using external scripts that support callbacks. Many third party JavaScript APIs now support non-blocking execution. Here is an example of loading the Google Maps API asynchronously.

How do I replace a character in a string in Java?

Try using String.replace() or String.replaceAll() instead.

String my_new_str = my_str.replace("&", "&amp;");

(Both replace all occurrences; replaceAll allows use of regex.)

How do you set a default value for a MySQL Datetime column?

If you are trying to set default value as NOW(),MySQL supports that you have to change the type of that column TIMESTAMP instead of DATETIME. TIMESTAMP have current date and time as default..i think it will resolved your problem..

AJAX POST and Plus Sign ( + ) -- How to Encode?

If you have to do a curl in php, you should use urlencode() from PHP but individually!

strPOST = "Item1=" . $Value1 . "&Item2=" . urlencode("+")

If you do urlencode(strPOST), you will bring you another problem, you will have one Item1 and & will be change %xx value and be as one value, see down here the return!

Example 1

$strPOST = "Item1=" . $Value1 . "&Item2=" . urlencode("+") will give Item1=Value1&Item2=%2B

Example 2

$strPOST = urlencode("Item1=" . $Value1 . "&Item2=+") will give Item1%3DValue1%26Item2%3D%2B

Example 1 is the good way to prepare string for POST in curl

Example 2 show that the receptor will not see the equal and the ampersand to distinguish both value!

How do I convert a list into a string with spaces in Python?

"".join([i for i in my_list])

This should work just like you asked!

Convert pandas dataframe to NumPy array

I would just chain the DataFrame.reset_index() and DataFrame.values functions to get the Numpy representation of the dataframe, including the index:

In [8]: df
Out[8]: 
          A         B         C
0 -0.982726  0.150726  0.691625
1  0.617297 -0.471879  0.505547
2  0.417123 -1.356803 -1.013499
3 -0.166363 -0.957758  1.178659
4 -0.164103  0.074516 -0.674325
5 -0.340169 -0.293698  1.231791
6 -1.062825  0.556273  1.508058
7  0.959610  0.247539  0.091333

[8 rows x 3 columns]

In [9]: df.reset_index().values
Out[9]:
array([[ 0.        , -0.98272574,  0.150726  ,  0.69162512],
       [ 1.        ,  0.61729734, -0.47187926,  0.50554728],
       [ 2.        ,  0.4171228 , -1.35680324, -1.01349922],
       [ 3.        , -0.16636303, -0.95775849,  1.17865945],
       [ 4.        , -0.16410334,  0.0745164 , -0.67432474],
       [ 5.        , -0.34016865, -0.29369841,  1.23179064],
       [ 6.        , -1.06282542,  0.55627285,  1.50805754],
       [ 7.        ,  0.95961001,  0.24753911,  0.09133339]])

To get the dtypes we'd need to transform this ndarray into a structured array using view:

In [10]: df.reset_index().values.ravel().view(dtype=[('index', int), ('A', float), ('B', float), ('C', float)])
Out[10]:
array([( 0, -0.98272574,  0.150726  ,  0.69162512),
       ( 1,  0.61729734, -0.47187926,  0.50554728),
       ( 2,  0.4171228 , -1.35680324, -1.01349922),
       ( 3, -0.16636303, -0.95775849,  1.17865945),
       ( 4, -0.16410334,  0.0745164 , -0.67432474),
       ( 5, -0.34016865, -0.29369841,  1.23179064),
       ( 6, -1.06282542,  0.55627285,  1.50805754),
       ( 7,  0.95961001,  0.24753911,  0.09133339),
       dtype=[('index', '<i8'), ('A', '<f8'), ('B', '<f8'), ('C', '<f8')])

System.Threading.Timer in C# it seems to be not working. It runs very fast every 3 second

 var span = TimeSpan.FromMinutes(2);
 var t = Task.Factory.StartNew(async delegate / () =>
   {
        this.SomeAsync();
        await Task.Delay(span, source.Token);
  }, source.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);

source.Cancel(true/or not);

// or use ThreadPool(whit defaul options thread) like this
Task.Start(()=>{...}), source.Token)

if u like use some loop thread inside ...

public async void RunForestRun(CancellationToken token)
{
  var t = await Task.Factory.StartNew(async delegate
   {
       while (true)
       {
           await Task.Delay(TimeSpan.FromSeconds(1), token)
                 .ContinueWith(task => { Console.WriteLine("End delay"); });
           this.PrintConsole(1);
        }
    }, token) // drop thread options to default values;
}

// And somewhere there
source.Cancel();
//or
token.ThrowIfCancellationRequested(); // try/ catch block requred.

"Could not find the main class" error when running jar exported by Eclipse

Verify that you can start your application like that:

java -cp myjarfile.jar snake.Controller

I just read when I double click on it - this sounds like a configuration issue with your operating system. You're double-clicking the file on a windows explorer window? Try to run it from a console/terminal with the command

java -jar myjarfile.jar

Further Reading


The manifest has to end with a new line. Please check your file, a missing new line will cause trouble.

Disable keyboard on EditText

Just set:

 NoImeEditText.setInputType(0);

or in the constructor:

   public NoImeEditText(Context context, AttributeSet attrs) { 
          super(context, attrs);   
          setInputType(0);
       } 

How to change the color of an svg element?

the easiest way would be to create a font out of the SVG using a service like https://icomoon.io/app/#/select or such. upload your SVG, click "generate font", include font files and css into your side and just use and style it like any other text. I always use it like this because it makes styling much easier.

EDIT: As mentioned in the article commented by @CodeMouse92 icon fonts mess up screen readers (and are possibly bad for SEO). So rather stick to the SVGs.

When should I use a table variable vs temporary table in sql server?

Your question shows you have succumbed to some of the common misconceptions surrounding table variables and temporary tables.

I have written quite an extensive answer on the DBA site looking at the differences between the two object types. This also addresses your question about disk vs memory (I didn't see any significant difference in behaviour between the two).

Regarding the question in the title though as to when to use a table variable vs a local temporary table you don't always have a choice. In functions, for example, it is only possible to use a table variable and if you need to write to the table in a child scope then only a #temp table will do (table-valued parameters allow readonly access).

Where you do have a choice some suggestions are below (though the most reliable method is to simply test both with your specific workload).

  1. If you need an index that cannot be created on a table variable then you will of course need a #temporary table. The details of this are version dependant however. For SQL Server 2012 and below the only indexes that could be created on table variables were those implicitly created through a UNIQUE or PRIMARY KEY constraint. SQL Server 2014 introduced inline index syntax for a subset of the options available in CREATE INDEX. This has been extended since to allow filtered index conditions. Indexes with INCLUDE-d columns or columnstore indexes are still not possible to create on table variables however.

  2. If you will be repeatedly adding and deleting large numbers of rows from the table then use a #temporary table. That supports TRUNCATE (which is more efficient than DELETE for large tables) and additionally subsequent inserts following a TRUNCATE can have better performance than those following a DELETE as illustrated here.

  3. If you will be deleting or updating a large number of rows then the temp table may well perform much better than a table variable - if it is able to use rowset sharing (see "Effects of rowset sharing" below for an example).
  4. If the optimal plan using the table will vary dependent on data then use a #temporary table. That supports creation of statistics which allows the plan to be dynamically recompiled according to the data (though for cached temporary tables in stored procedures the recompilation behaviour needs to be understood separately).
  5. If the optimal plan for the query using the table is unlikely to ever change then you may consider a table variable to skip the overhead of statistics creation and recompiles (would possibly require hints to fix the plan you want).
  6. If the source for the data inserted to the table is from a potentially expensive SELECT statement then consider that using a table variable will block the possibility of this using a parallel plan.
  7. If you need the data in the table to survive a rollback of an outer user transaction then use a table variable. A possible use case for this might be logging the progress of different steps in a long SQL batch.
  8. When using a #temp table within a user transaction locks can be held longer than for table variables (potentially until the end of transaction vs end of statement dependent on the type of lock and isolation level) and also it can prevent truncation of the tempdb transaction log until the user transaction ends. So this might favour the use of table variables.
  9. Within stored routines, both table variables and temporary tables can be cached. The metadata maintenance for cached table variables is less than that for #temporary tables. Bob Ward points out in his tempdb presentation that this can cause additional contention on system tables under conditions of high concurrency. Additionally, when dealing with small quantities of data this can make a measurable difference to performance.

Effects of rowset sharing

DECLARE @T TABLE(id INT PRIMARY KEY, Flag BIT);

CREATE TABLE #T (id INT PRIMARY KEY, Flag BIT);

INSERT INTO @T 
output inserted.* into #T
SELECT TOP 1000000 ROW_NUMBER() OVER (ORDER BY @@SPID), 0
FROM master..spt_values v1, master..spt_values v2

SET STATISTICS TIME ON

/*CPU time = 7016 ms,  elapsed time = 7860 ms.*/
UPDATE @T SET Flag=1;

/*CPU time = 6234 ms,  elapsed time = 7236 ms.*/
DELETE FROM @T

/* CPU time = 828 ms,  elapsed time = 1120 ms.*/
UPDATE #T SET Flag=1;

/*CPU time = 672 ms,  elapsed time = 980 ms.*/
DELETE FROM #T

DROP TABLE #T

Mysql select distinct

You can use group by instead of distinct. Because when you use distinct, you'll get struggle to select all values from table. Unlike when you use group by, you can get distinct values and also all fields in table.

Deleting array elements in JavaScript - delete vs splice

As stated many times above, using splice() seems like a perfect fit. Documentation at Mozilla:

The splice() method changes the content of an array by removing existing elements and/or adding new elements.

var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];

myFish.splice(2, 0, 'drum'); 
// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]

myFish.splice(2, 1); 
// myFish is ["angel", "clown", "mandarin", "sturgeon"]

Syntax

array.splice(start)
array.splice(start, deleteCount)
array.splice(start, deleteCount, item1, item2, ...)

Parameters

start

Index at which to start changing the array. If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end.

deleteCount

An integer indicating the number of old array elements to remove. If deleteCount is 0, no elements are removed. In this case, you should specify at least one new element. If deleteCount is greater than the number of elements left in the array starting at start, then all of the elements through the end of the array will be deleted.

If deleteCount is omitted, deleteCount will be equal to (arr.length - start).

item1, item2, ...

The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.

Return value

An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

[...]

How do I sort a list of dictionaries by a value of the dictionary?

If you do not need the original list of dictionaries, you could modify it in-place with sort() method using a custom key function.

Key function:

def get_name(d):
    """ Return the value of a key in a dictionary. """

    return d["name"]

The list to be sorted:

data_one = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]

Sorting it in-place:

data_one.sort(key=get_name)

If you need the original list, call the sorted() function passing it the list and the key function, then assign the returned sorted list to a new variable:

data_two = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
new_data = sorted(data_two, key=get_name)

Printing data_one and new_data.

>>> print(data_one)
[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
>>> print(new_data)
[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]

Another Repeated column in mapping for entity error

@Id
@Column(name = "COLUMN_NAME", nullable = false)
public Long getId() {
    return id;
}

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, targetEntity = SomeCustomEntity.class)
@JoinColumn(name = "COLUMN_NAME", referencedColumnName = "COLUMN_NAME", nullable = false, updatable = false, insertable = false)
@org.hibernate.annotations.Cascade(value = org.hibernate.annotations.CascadeType.ALL)
public List<SomeCustomEntity> getAbschreibareAustattungen() {
    return abschreibareAustattungen;
}

If you have already mapped a column and have accidentaly set the same values for name and referencedColumnName in @JoinColumn hibernate gives the same stupid error

Error:

Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: com.testtest.SomeCustomEntity column: COLUMN_NAME (should be mapped with insert="false" update="false")

Understanding string reversal via slicing

You can use reversed() function. For example

x = "abcd"
for i in reversed(x):
        print(i, end="")
print("\n")
L = [1,2,3]
for i in reversed(L):
        print(i, end="")

prints dcba and 321

Entity Framework - Include Multiple Levels of Properties

If I understand you correctly you are asking about including nested properties. If so :

.Include(x => x.ApplicationsWithOverrideGroup.NestedProp)

or

.Include("ApplicationsWithOverrideGroup.NestedProp")  

or

.Include($"{nameof(ApplicationsWithOverrideGroup)}.{nameof(NestedProp)}")  

When to use 'npm start' and when to use 'ng serve'?

There are more than that. The executed executables are different.

npm run start

will run your projects local executable which is located in your node_modules/.bin.

ng serve

will run another executable which is global.

It means if you clone and install an Angular project which is created with angular-cli version 5 and your global cli version is 7, then you may have problems with ng build.

How can we run a test method with multiple parameters in MSTest?

EDIT 4: Looks like this is completed in MSTest V2 June 17, 2016: https://blogs.msdn.microsoft.com/visualstudioalm/2016/06/17/taking-the-mstest-framework-forward-with-mstest-v2/

Original Answer:

As of about a week ago in Visual Studio 2012 Update 1 something similar is now possible:

[DataTestMethod]
[DataRow(12,3,4)]
[DataRow(12,2,6)]
[DataRow(12,4,3)]
public void DivideTest(int n, int d, int q)
{
  Assert.AreEqual( q, n / d );
}

EDIT: It appears this is only available within the unit testing project for WinRT/Metro. Bummer

EDIT 2: The following is the metadata found using "Go To Definition" within Visual Studio:

#region Assembly Microsoft.VisualStudio.TestPlatform.UnitTestFramework.dll, v11.0.0.0
// C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0\ExtensionSDKs\MSTestFramework\11.0\References\CommonConfiguration\neutral\Microsoft.VisualStudio.TestPlatform.UnitTestFramework.dll
#endregion

using System;

namespace Microsoft.VisualStudio.TestPlatform.UnitTestFramework
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class DataTestMethodAttribute : TestMethodAttribute
    {
        public DataTestMethodAttribute();

        public override TestResult[] Execute(ITestMethod testMethod);
    }
}

EDIT 3: This issue was brought up in Visual Studio's UserVoice forums. Last Update states:

STARTED · Visual Studio Team ADMIN Visual Studio Team (Product Team, Microsoft Visual Studio) responded · April 25, 2016 Thank you for the feedback. We have started working on this.

Pratap Lakshman Visual Studio

https://visualstudio.uservoice.com/forums/330519-team-services/suggestions/3865310-allow-use-of-datatestmethod-datarow-in-all-unit

What is a deadlock?

A classic and very simple program for understanding Deadlock situation :-

public class Lazy {

    private static boolean initialized = false;

    static {
        Thread t = new Thread(new Runnable() {
            public void run() {
                initialized = true;
            }
        });

        t.start();

        try {
            t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        System.out.println(initialized);
    }
}

When the main thread invokes Lazy.main, it checks whether the class Lazy has been initialized and begins to initialize the class. The main thread now sets initialized to false , creates and starts a background thread whose run method sets initialized to true , and waits for the background thread to complete.

This time, the class is currently being initialized by another thread. Under these circumstances, the current thread, which is the background thread, waits on the Class object until initialization is complete. Unfortunately, the thread that is doing the initialization, the main thread, is waiting for the background thread to complete. Because the two threads are now waiting for each other, the program is DEADLOCKED.

How to write some data to excel file(.xlsx)

You can use ClosedXML for this.

Store your table in a DataTable and you can export the table to excel by this simple snippet:

XLWorkbook workbook = new XLWorkbook();
DataTable table = GetYourTable();
workbook.Worksheets.Add(table );

You can read the documentation of ClosedXML to learn more. Hope this helps!

CSV API for Java

Update: The code in this answer is for Super CSV 1.52. Updated code examples for Super CSV 2.4.0 can be found at the project website: http://super-csv.github.io/super-csv/index.html


The SuperCSV project directly supports the parsing and structured manipulation of CSV cells. From http://super-csv.github.io/super-csv/examples_reading.html you'll find e.g.

given a class

public class UserBean {
    String username, password, street, town;
    int zip;

    public String getPassword() { return password; }
    public String getStreet() { return street; }
    public String getTown() { return town; }
    public String getUsername() { return username; }
    public int getZip() { return zip; }
    public void setPassword(String password) { this.password = password; }
    public void setStreet(String street) { this.street = street; }
    public void setTown(String town) { this.town = town; }
    public void setUsername(String username) { this.username = username; }
    public void setZip(int zip) { this.zip = zip; }
}

and that you have a CSV file with a header. Let's assume the following content

username, password,   date,        zip,  town
Klaus,    qwexyKiks,  17/1/2007,   1111, New York
Oufu,     bobilop,    10/10/2007,  4555, New York

You can then create an instance of the UserBean and populate it with values from the second line of the file with the following code

class ReadingObjects {
  public static void main(String[] args) throws Exception{
    ICsvBeanReader inFile = new CsvBeanReader(new FileReader("foo.csv"), CsvPreference.EXCEL_PREFERENCE);
    try {
      final String[] header = inFile.getCSVHeader(true);
      UserBean user;
      while( (user = inFile.read(UserBean.class, header, processors)) != null) {
        System.out.println(user.getZip());
      }
    } finally {
      inFile.close();
    }
  }
}

using the following "manipulation specification"

final CellProcessor[] processors = new CellProcessor[] {
    new Unique(new StrMinMax(5, 20)),
    new StrMinMax(8, 35),
    new ParseDate("dd/MM/yyyy"),
    new Optional(new ParseInt()),
    null
};

Permission is only granted to system app

In Eclipse:

Window -> Preferences -> Android -> Lint Error Checking.

In the list find an entry with ID = ProtectedPermission. Set the Severity to something lower than Error. This way you can still compile the project using Eclipse.

In Android Studio:

File -> Settings -> Editor -> Inspections

Under Android Lint, locate Using system app permission. Either uncheck the checkbox or choose a Severity lower than Error.

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

A query may fail for various reasons in which case both the mysql_* and the mysqli extension will return false from their respective query functions/methods. You need to test for that error condition and handle it accordingly.

mysql_* extension:

NOTE The mysql_ functions are deprecated and have been removed in php version 7.

Check $result before passing it to mysql_fetch_array. You'll find that it's false because the query failed. See the mysql_query documentation for possible return values and suggestions for how to deal with them.

$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");

if($result === FALSE) { 
    die(mysql_error()); // TODO: better error handling
}

while($row = mysql_fetch_array($result))
{
    echo $row['FirstName'];
}

mysqli extension
procedural style:

$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$result = mysqli_query($mysqli, "SELECT * FROM Users WHERE UserName LIKE '$username'");

// mysqli_query returns false if something went wrong with the query
if($result === FALSE) { 
    yourErrorHandler(mysqli_error($mysqli));
}
else {
    // as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
    foreach( $result as $row ) {
        ...

oo-style:

$username = $mysqli->escape_string($_POST['username']);
$result = $mysqli->query("SELECT * FROM Users WHERE UserName LIKE '$username'");

if($result === FALSE) { 
    yourErrorHandler($mysqli->error); // or $mysqli->error_list
}
else {
    // as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
    foreach( $result as $row ) {
      ...

using a prepared statement:

$stmt = $mysqli->prepare('SELECT * FROM Users WHERE UserName LIKE ?');
if ( !$stmt ) {
    yourErrorHandler($mysqli->error); // or $mysqli->error_list
}
else if ( !$stmt->bind_param('s', $_POST['username']) ) {
    yourErrorHandler($stmt->error); // or $stmt->error_list
}
else if ( !$stmt->execute() ) {
    yourErrorHandler($stmt->error); // or $stmt->error_list
}
else {
    $result = $stmt->get_result();
    // as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
    foreach( $result as $row ) {
      ...

These examples only illustrate what should be done (error handling), not how to do it. Production code shouldn't use or die when outputting HTML, else it will (at the very least) generate invalid HTML. Also, database error messages shouldn't be displayed to non-admin users, as it discloses too much information.

How to determine if Javascript array contains an object with an attribute that equals a given value?

May be too late, but javascript array has two methods some and every method that returns a boolean and can help you achieve this.

I think some would be most appropriate for what you intend to achieve.

vendors.some( vendor => vendor['Name'] !== 'Magenic' )

Some validates that any of the objects in the array satisfies the given condition.

vendors.every( vendor => vendor['Name'] !== 'Magenic' )

Every validates that all the objects in the array satisfies the given condition.

Negative regex for Perl string pattern match

Your regex does not work because [] defines a character class, but what you want is a lookahead:

(?=) - Positive look ahead assertion foo(?=bar) matches foo when followed by bar
(?!) - Negative look ahead assertion foo(?!bar) matches foo when not followed by bar
(?<=) - Positive look behind assertion (?<=foo)bar matches bar when preceded by foo
(?<!) - Negative look behind assertion (?<!foo)bar matches bar when NOT preceded by foo
(?>) - Once-only subpatterns (?>\d+)bar Performance enhancing when bar not present
(?(x)) - Conditional subpatterns
(?(3)foo|fu)bar - Matches foo if 3rd subpattern has matched, fu if not
(?#) - Comment (?# Pattern does x y or z)

So try: (?!bush)

how to check if a form is valid programmatically using jQuery Validation Plugin

For a group of inputs you can use an improved version based in @mikemaccana's answer

$.fn.isValid = function(){
    var validate = true;
    this.each(function(){
        if(this.checkValidity()==false){
            validate = false;
        }
    });
};

now you can use this to verify if the form is valid:

if(!$(".form-control").isValid){
    return;
}

You could use the same technique to get all the error messages:

$.fn.getVelidationMessage = function(){
    var message = "";
    var name = "";
    this.each(function(){
        if(this.checkValidity()==false){
            name = ($( "label[for=" + this.id + "] ").html() || this.placeholder || this.name || this.id);
            message = message + name +":"+ (this.validationMessage || 'Invalid value.')+"\n<br>";
        }
    })
    return message;
}

How to var_dump variables in twig templates?

If you are using Twig in your application as a component you can do this:

$twig = new Twig_Environment($loader, array(
    'autoescape' => false
));

$twig->addFilter('var_dump', new Twig_Filter_Function('var_dump'));

Then in your templates:

{{ my_variable | var_dump }}

Links in <select> dropdown options

You can use this code:

<select id="menu" name="links" size="1" onchange="window.location.href=this.value;">
    <option value="URL">Book</option>
    <option value="URL">Pen</option>
    <option value="URL">Read</option>
    <option value="URL">Apple</option>
</select>

Android ListView Divider

Some people might be experiencing a solid line. I got around this by adding android:layerType="software" to the view referencing the drawable.

Changing the URL in react-router v4 without using Redirect or Link

Try this,

this.props.router.push('/foo')

warning works for versions prior to v4

and

this.props.history.push('/foo')

for v4 and above

Remove Item from ArrayList

In this specific case, you should remove the elements in descending order. First index 5, then 3, then 1. This will remove the elements from the list without undesirable side effects.

for (int j = i.length-1; j >= 0; j--) {
    list.remove(i[j]);
}

How do I set up Android Studio to work completely offline?

On Android 0.5.1 you can find the offline option in the File / Settings / Gradle (in the Project Settings section)/ Offline work

MYSQL order by both Ascending and Descending sorting

You can do that in this way:

ORDER BY `products`.`product_category_id` DESC ,`naam` ASC

Have a look at ORDER BY Optimization

Convert String to Carbon

Why not try using the following:

$dateTimeString = $aDateString." ".$aTimeString;
$dueDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/London');   

Disable output buffering

From Magnus Lycka answer on a mailing list:

You can skip buffering for a whole python process using "python -u" (or#!/usr/bin/env python -u etc) or by setting the environment variable PYTHONUNBUFFERED.

You could also replace sys.stdout with some other stream like wrapper which does a flush after every call.

class Unbuffered(object):
   def __init__(self, stream):
       self.stream = stream
   def write(self, data):
       self.stream.write(data)
       self.stream.flush()
   def writelines(self, datas):
       self.stream.writelines(datas)
       self.stream.flush()
   def __getattr__(self, attr):
       return getattr(self.stream, attr)

import sys
sys.stdout = Unbuffered(sys.stdout)
print 'Hello'

What is the difference between \r and \n?

In short \r has ASCII value 13 (CR) and \n has ASCII value 10 (LF). Mac uses CR as line delimiter (at least, it did before, I am not sure for modern macs), *nix uses LF and Windows uses both (CRLF).

How can I delete a user in linux when the system says its currently used in a process

restart your computer and run $sudo deluser username... worked for me

How to print last two columns using awk

using gawk exhibits the problem:

 gawk '{ print $NF-1, $NF}' filename
1 2
2 3
-1 one
-1 three
# cat filename
1 2
2 3
one
one two three

I just put gawk on Solaris 10 M4000: So, gawk is the cuplrit on the $NF-1 vs. $(NF-1) issue. Next question what does POSIX say? per:

http://www.opengroup.org/onlinepubs/009695399/utilities/awk.html

There is no direction one way or the other. Not good. gawk implies subtraction, other awks imply field number or subtraction. hmm.

C# delete a folder and all files and folders within that folder

Try This:

foreach (string files in Directory.GetFiles(SourcePath))
{
   FileInfo fileInfo = new FileInfo(files);
   fileInfo.Delete(); //delete the files first. 
}
Directory.Delete(SourcePath);// delete the directory as it is empty now.

Easy way to pull latest of all git submodules

As it may happens that the default branch of your submodules is not master, this is how I automate the full Git submodules upgrades:

git submodule init
git submodule update
git submodule foreach 'git fetch origin; git checkout $(git rev-parse --abbrev-ref HEAD); git reset --hard origin/$(git rev-parse --abbrev-ref HEAD); git submodule update --recursive; git clean -dfx'

Why are Python's 'private' methods not actually private?

With Python 3.4 this is the behaviour:

>>> class Foo:
        def __init__(self):
                pass
        def __privateMethod(self):
                return 3
        def invoke(self):
                return self.__privateMethod()


>>> help(Foo)
Help on class Foo in module __main__:

class Foo(builtins.object)
 |  Methods defined here:
 |
 |  __init__(self)
 |
 |  invoke(self)
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables (if defined)
 |
 |  __weakref__
 |      list of weak references to the object (if defined)

 >>> f = Foo()
 >>> f.invoke()
 3
 >>> f.__privateMethod()
 Traceback (most recent call last):
   File "<pyshell#47>", line 1, in <module>
     f.__privateMethod()
 AttributeError: 'Foo' object has no attribute '__privateMethod'

https://docs.python.org/3/tutorial/classes.html#tut-private

Note that the mangling rules are designed mostly to avoid accidents; it still is possible to access or modify a variable that is considered private. This can even be useful in special circumstances, such as in the debugger.

Even if the question is old I hope my snippet could be helpful.

node.js Error: connect ECONNREFUSED; response from server

From your code, It looks like your file contains code that makes get request to localhost (127.0.0.1:8000).

The problem might be you have not created server on your local machine which listens to port 8000.

For that you have to set up server on localhost which can serve your request.

  1. Create server.js

    var express = require('express');
    var app = express();
    
    app.get('/', function (req, res) {
      res.send('Hello World!'); // This will serve your request to '/'.
    });
    
    app.listen(8000, function () {
      console.log('Example app listening on port 8000!');
     });
    
  2. Run server.js : node server.js

  3. Run file that contains code to make request.

Non-static variable cannot be referenced from a static context

Now you can add/use instances with in the method

public class Myprogram7 {

  Scanner scan;
  int compareCount = 0;
  int low = 0;
  int high = 0;
  int mid = 0;  
  int key = 0;  
  Scanner temp;  
  int[]list;  
  String menu, outputString;  
  int option = 1;  
  boolean found = false;  

  private void readLine() {

  }

  private void findkey() {

  }

  private void printCount() {

  }
  public static void main(String[] args){

    Myprogram7 myprg=new Myprogram7();
    myprg.readLine();
    myprg.findkey();
    myprg.printCount();
  }
}

How can I check for "undefined" in JavaScript?

Personally, I always use the following:

var x;
if( x === undefined) {
    //Do something here
}
else {
   //Do something else here
}

The window.undefined property is non-writable in all modern browsers (JavaScript 1.8.5 or later). From Mozilla's documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined, I see this: One reason to use typeof() is that it does not throw an error if the variable has not been defined.

I prefer to have the approach of using

x === undefined 

because it fails and blows up in my face rather than silently passing/failing if x has not been declared before. This alerts me that x is not declared. I believe all variables used in JavaScript should be declared.

Does C# support multiple inheritance?

Multiple inheritance is not supported in C#.

But if you want to "inherit" behavior from two sources why not use the combination of:

  • Composition
  • Dependency Injection

There is a basic but important OOP principle that says: "Favor composition over inheritance".

You can create a class like this:

public class MySuperClass
{
    private IDependencyClass1 mDependency1;
    private IDependencyClass2 mDependency2;

    public MySuperClass(IDependencyClass1 dep1, IDependencyClass2 dep2)
    {
        mDependency1 = dep1;
        mDependency2 = dep2;
    }

    private void MySuperMethodThatDoesSomethingComplex()
    {
        string s = mDependency1.GetMessage();
        mDependency2.PrintMessage(s);
    }
}

As you can see the dependecies (actual implementations of the interfaces) are injected via the constructor. You class does not know how each class is implemented but it knows how to use them. Hence, a loose coupling between the classes involved here but the same power of usage.

Today's trends show that inheritance is kind of "out of fashion".

Random string generation with upper case letters and digits

Two methods :

import random, math

def randStr_1(chars:str, length:int) -> str:
    chars *= math.ceil(length / len(chars))
    chars = letters[0:length]
    chars = list(chars)
    random.shuffle(characters)

    return ''.join(chars)

def randStr_2(chars:str, length:int) -> str:
    return ''.join(random.choice(chars) for i in range(chars))


Benchmark :

from timeit import timeit

setup = """
import os, subprocess, time, string, random, math

def randStr_1(letters:str, length:int) -> str:
    letters *= math.ceil(length / len(letters))
    letters = letters[0:length]
    letters = list(letters)
    random.shuffle(letters)
    return ''.join(letters)

def randStr_2(letters:str, length:int) -> str:
    return ''.join(random.choice(letters) for i in range(length))
"""

print('Method 1 vs Method 2', ', run 10 times each.')

for length in [100,1000,10000,50000,100000,500000,1000000]:
    print(length, 'characters:')

    eff1 = timeit("randStr_1(string.ascii_letters, {})".format(length), setup=setup, number=10)
    eff2 = timeit("randStr_2(string.ascii_letters, {})".format(length), setup=setup, number=10)
    print('\t{}s : {}s'.format(round(eff1, 6), round(eff2, 6)))
    print('\tratio = {} : {}\n'.format(eff1/eff1, round(eff2/eff1, 2)))

Output :

Method 1 vs Method 2 , run 10 times each.

100 characters:
    0.001411s : 0.00179s
    ratio = 1.0 : 1.27

1000 characters:
    0.013857s : 0.017603s
    ratio = 1.0 : 1.27

10000 characters:
    0.13426s : 0.151169s
    ratio = 1.0 : 1.13

50000 characters:
    0.709403s : 0.855136s
    ratio = 1.0 : 1.21

100000 characters:
    1.360735s : 1.674584s
    ratio = 1.0 : 1.23

500000 characters:
    6.754923s : 7.160508s
    ratio = 1.0 : 1.06

1000000 characters:
    11.232965s : 14.223914s
    ratio = 1.0 : 1.27

The performance of first method is better.

How to compare a local git branch with its remote branch?

In android studio, it is possible to see the difference between branches using graphical interface. Select your remote branch and and "Compare with current" from the list. From then you can select the files tab to see if there are any files that have content difference between both branches. If no file is seen, then both branches are up-to-date with each other.

Text size and different android screen sizes

I know it's late but this might help someone...

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:autoSizeTextType="uniform"
        android:gravity="center_horizontal|bottom"
        android:text="Your text goes here!"
        android:layout_centerInParent="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_percent="0.05"
        app:layout_constraintHorizontal_bias="0.50"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.50"
        app:layout_constraintWidth_percent="0.50" />
</androidx.constraintlayout.widget.ConstraintLayout>

Also, if you want to adjust the text size then try changing

app:layout_constraintWidth_percent="0.50" 
app:layout_constraintHeight_percent="0.05"

That's all.

What file uses .md extension and how should I edit them?

BBEdit will also display MD on the mac.

and here is a quicklook plugin to display them when you preview them.

C++ variable has initializer but incomplete type?

It's not related to Ken's case directly, but such an error also can occur if you copied .h file and forgot to change #ifndef directive. In this case compiler will just skip definition of the class thinking that it's a duplication.

Test if a string contains any of the strings from an array

Since version 3.4 Apache Common Lang 3 implement the containsAny method.

The name 'ConfigurationManager' does not exist in the current context

In NetCore 3.1 I had to use Microsoft.Extensions.Configuration instead:

    public static async Task Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
            .Build();

...

Access host database from a docker container

From the 18.03 docs:

I want to connect from a container to a service on the host

The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host.

The gateway is also reachable as gateway.docker.internal.

EXAMPLE: Here's what I use for my MySQL connection string inside my container to access the MySQL instance on my host:

mysql://host.docker.internal:3306/my_awesome_database

C++ Remove new line from multiline string

All these answers seem a bit heavy to me.

If you just flat out remove the '\n' and move everything else back a spot, you are liable to have some characters slammed together in a weird-looking way. So why not just do the simple (and most efficient) thing: Replace all '\n's with spaces?

for (int i = 0; i < str.length();i++) {
   if (str[i] == '\n') {
      str[i] = ' ';
   }
}

There may be ways to improve the speed of this at the edges, but it will be way quicker than moving whole chunks of the string around in memory.

Why do some functions have underscores "__" before and after the function name?

This convention is used for special variables or methods (so-called “magic method”) such as __init__ and __len__. These methods provides special syntactic features or do special things.

For example, __file__ indicates the location of Python file, __eq__ is executed when a == b expression is executed.

A user of course can make a custom special method, which is a very rare case, but often might modify some of the built-in special methods (e.g. you should initialize the class with __init__ that will be executed at first when an instance of a class is created).

class A:
    def __init__(self, a):  # use special method '__init__' for initializing
        self.a = a
    def __custom__(self):  # custom special method. you might almost do not use it
        pass

REST API error code 500 handling

You suggested "Catching any unexpected errors and return some error code signaling "unexpected situation" " but couldn't find an appropriate error code.

Guess what: That's what 5xx is there for.

Where is the visual studio HTML Designer?

Go to [Tools, Options], section "Web Forms Designer" and enable the option "Enable Web Forms Designer". That should give you the Design and Split option again.

Best way to test exceptions with Assert to ensure they will be thrown

Mark the test with the ExpectedExceptionAttribute (this is the term in NUnit or MSTest; users of other unit testing frameworks may need to translate).

How do I fix the npm UNMET PEER DEPENDENCY warning?

In case you wish to keep the current version of angular, you can visit this version compatibility checker to check which version of angular-material is best for your current angular version. You can also check peer dependencies of angular-material using angular-material compatibility.

How can I read comma separated values from a text file in Java?

To split your String by comma(,) use str.split(",") and for tab use str.split("\\t")

    try {
        BufferedReader in = new BufferedReader(
                               new FileReader("G:\\RoutePPAdvant2.txt"));
        String str;

        while ((str = in.readLine())!= null) {
            String[] ar=str.split(",");
            ...
        }
        in.close();
    } catch (IOException e) {
        System.out.println("File Read Error");
    }

Help needed with Median If in Excel

Make a third column that has values like:

=IF(A1="Airline",B1)

=IF(A2="Airline",B2) etc

Then just perform a median on the new column.

Difference between $(document.body) and $('body')

Outputwise both are equivalent. Though the second expression goes through a top down lookup from the DOM root. You might want to avoid the additional overhead (however minuscule it may be) if you already have document.body object in hand for JQuery to wrap over. See http://api.jquery.com/jQuery/ #Selector Context

How to set selected value of jquery select2?

var $option = $("<option selected></option>").val('1').text("Pick me");

$('#select_id').append($option).trigger('change');

Try this append then select. Doesn't duplicate the option upon AJAX call.

Cannot get Kerberos service ticket: KrbException: Server not found in Kerberos database (7)

"Server not found in Kerberos database" error can happen if you have registered the SPN to multiple users/computers.

You can check that with:

$ SetSPN -Q ServicePrincipalName
( SetSPN -Q HTTP/my.server.local@MYDOMAIN )

Define a fixed-size list in Java

If you want to use ArrayList or LinkedList, it seems that the answer is no. Although there are some classes in java that you can set them fixed size, like PriorityQueue, ArrayList and LinkedList can't, because there is no constructor for these two to specify capacity.

If you want to stick to ArrayList/LinkedList, one easy solution is to check the size manually each time.

public void fixedAdd(List<Integer> list, int val, int size) {
    list.add(val);
    if(list.size() > size) list.remove(0);
}

LinkedList is better than ArrayList in this situation. Suppose there are many values to be added but the list size is quite samll, there will be many remove operations. The reason is that the cost of removing from ArrayList is O(N), but only O(1) for LinkedList.

How to use <DllImport> in VB.NET?

You can also try this

Private Declare Function GetWindowText Lib "user32.dll" (ByVal hwnd As IntPtr, ByVal lpString As StringBuilder, ByVal cch As Integer) As Integer

I always use Declare Function instead of DllImport... Its more simply, its shorter and does the same

Python error "ImportError: No module named"

To mark a directory as a package you need a file named __init__.py, does this help?

<ng-container> vs <template>

Edit : Now it is documented

<ng-container> to the rescue

The Angular <ng-container> is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.

(...)

The <ng-container> is a syntax element recognized by the Angular parser. It's not a directive, component, class, or interface. It's more like the curly braces in a JavaScript if-block:

  if (someCondition) {
      statement1; 
      statement2;
      statement3;
     }

Without those braces, JavaScript would only execute the first statement when you intend to conditionally execute all of them as a single block. The <ng-container> satisfies a similar need in Angular templates.

Original answer:

According to this pull request :

<ng-container> is a logical container that can be used to group nodes but is not rendered in the DOM tree as a node.

<ng-container> is rendered as an HTML comment.

so this angular template :

<div>
    <ng-container>foo</ng-container>
<div>

will produce this kind of output :

<div>
    <!--template bindings={}-->foo
<div>

So ng-container is useful when you want to conditionaly append a group of elements (ie using *ngIf="foo") in your application but don't want to wrap them with another element.

<div>
    <ng-container *ngIf="true">
        <h2>Title</h2>
        <div>Content</div>
    </ng-container>
</div>

will then produce :

<div>
    <h2>Title</h2>
    <div>Content</div>
</div>

How to get HttpClient returning status code and response body?

If you are using Spring

return new ResponseEntity<String>("your response", HttpStatus.ACCEPTED);

Android: Rotate image in imageview by an angle

Rotate an image in android with delay:

imgSplash.animate().rotationBy(360f).setDuration(3000).setInterpolator(new LinearInterpolator()).start();

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

how to compare two string dates in javascript?

If your date is not in format standar yyyy-mm-dd (2017-02-06) for example 20/06/2016. You can use this code

var parts ='01/07/2016'.val().split('/');
var d1 = Number(parts[2] + parts[1] + parts[0]);
parts ='20/06/2016'.val().split('/');
var d2 = Number(parts[2] + parts[1] + parts[0]);
return d1 > d2

Writing data into CSV file in C#

Writing csv files by hand can be difficult because your data might contain commas and newlines. I suggest you use an existing library instead.

This question mentions a few options.

Are there any CSV readers/writer libraries in C#?

#1214 - The used table type doesn't support FULLTEXT indexes

Simply do the following:

  1. Open your .sql file with Notepad or Notepad ++

  2. Find InnoDB and Replace all (around 87) with MyISAM

  3. Save and now you can import your database with out error.

Android SDK is missing, out of date, or is missing templates. Please ensure you are using SDK version 22 or later

Click on Tools > SDK Manager or click SDK Manager after If you are unable to see the location of your Android SDK Location, click on edit and create a folder where you want to keep it and then click Next and Finish enter image description here

How do you count the elements of an array in java

What I think you may want is an ArrayList<Integer> instead of an array. This will allow you do to:

ArrayList<Integer> arr = new ArrayList<Integer>(20);
System.out.println(arr.size());

The output will be 0.

Then, you can add things to the list, and it will keep track of the count for you. (It will also grow the size of the backing storage as you need as well.)

Java: Add elements to arraylist with FOR loop where element name has increasing number

If you simply need a list, you could use:

List<Answer> answers = Arrays.asList(answer1, answer2, answer3);

If you specifically require an ArrayList, you could use:

ArrayList<Answer> answers = new ArrayList(Arrays.asList(answer1, answer2, answer3));

How Can I Resolve:"can not open 'git-upload-pack' " error in eclipse?

I was getting the same issue "Cannot open git-upload-pack" in eclipse Juno while trying to clone ('Git Repository Exploring' perspective). https://[username]@[hostName]:[portNumber]/scm/TestRepo.git

Solution : Issue got solved after adding "-Dhttps.protocols=TLSv1" to the eclipse.ini file.

Possible Reason for Error : Some servers does not support TLSv1.2, or TLSv1.1, they might support only TLSv1.0. Java 8 default TLS protocol is 1.2 whereas it is 1.0 with Java 7. For an unknown reason, when Egit connects to the server, it does not fallback to TLSv1.1 after TLS1.2 fails to establish the connection. Don't know if it's an Egit or a Java 8 issue Courtesy : https://www.eclipse.org/forums/index.php/t/1065782/

What is the difference between H.264 video and MPEG-4 video?

H.264 is a new standard for video compression which has more advanced compression methods than the basic MPEG-4 compression. One of the advantages of H.264 is the high compression rate. It is about 1.5 to 2 times more efficient than MPEG-4 encoding. This high compression rate makes it possible to record more information on the same hard disk.
The image quality is also better and playback is more fluent than with basic MPEG-4 compression. The most interesting feature however is the lower bit-rate required for network transmission.
So the 3 main advantages of H.264 over MPEG-4 compression are:
- Small file size for longer recording time and better network transmission.
- Fluent and better video quality for real time playback
- More efficient mobile surveillance application

H264 is now enshrined in MPEG4 as part 10 also known as AVC

Refer to: http://www.velleman.eu/downloads/3/h264_vs_mpeg4_en.pdf

Hope this helps.

Get a list of distinct values in List

public class KeyNote
{
    public long KeyNoteId { get; set; }
    public long CourseId { get; set; }
    public string CourseName { get; set; }
    public string Note { get; set; }
    public DateTime CreatedDate { get; set; }
}

public List<KeyNote> KeyNotes { get; set; }
public List<RefCourse> GetCourses { get; set; }    

List<RefCourse> courses = KeyNotes.Select(x => new RefCourse { CourseId = x.CourseId, Name = x.CourseName }).Distinct().ToList();

By using the above logic, we can get the unique Courses.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 23: ordinal not in range(128)

I was getting this error when executing in python3,I got the same program working by simply executing in python2

How do I uninstall a Windows service if the files do not exist anymore?

You can try running Autoruns, which would save you from having to edit the registry by hand. This is especially useful when you don't have the needed permissions.

rotate image with css

Perform rotation using transform: rotate(xdeg) and also apply overflow: hidden to the parent component to avoid overlapping effect

.div-parent {
   overflow: hidden
}

.div-child {
   transform: rotate(270deg);
}

Pandas DataFrame concat vs append

Pandas concat vs append vs join vs merge

  • Concat gives the flexibility to join based on the axis( all rows or all columns)

  • Append is the specific case(axis=0, join='outer') of concat

  • Join is based on the indexes (set by set_index) on how variable =['left','right','inner','couter']

  • Merge is based on any particular column each of the two dataframes, this columns are variables on like 'left_on', 'right_on', 'on'

Does JavaScript have a built in stringbuilder class?

No, there is no built-in support for building strings. You have to use concatenation instead.

You can, of course, make an array of different parts of your string and then call join() on that array, but it then depends on how the join is implemented in the JavaScript interpreter you are using.

I made an experiment to compare the speed of str1+str2 method versus array.push(str1, str2).join() method. The code was simple:

var iIterations =800000;
var d1 = (new Date()).valueOf();
str1 = "";
for (var i = 0; i<iIterations; i++)
    str1 = str1 + Math.random().toString();
var d2 = (new Date()).valueOf();
log("Time (strings): " + (d2-d1));

var d3 = (new Date()).valueOf();
arr1 = [];
for (var i = 0; i<iIterations; i++)
    arr1.push(Math.random().toString());
var str2 = arr1.join("");
var d4 = (new Date()).valueOf();
log("Time (arrays): " + (d4-d3));

I tested it in Internet Explorer 8 and Firefox 3.5.5, both on a Windows 7 x64.

In the beginning I tested on small number of iterations (some hundred, some thousand items). The results were unpredictable (sometimes string concatenation took 0 milliseconds, sometimes it took 16 milliseconds, the same for array joining).

When I increased the count to 50,000, the results were different in different browsers - in Internet Explorer the string concatenation was faster (94 milliseconds) and join was slower(125 milliseconds), while in Firefox the array join was faster (113 milliseconds) than string joining (117 milliseconds).

Then I increased the count to 500'000. Now the array.join() was slower than string concatenation in both browsers: string concatenation was 937 ms in Internet Explorer, 1155 ms in Firefox, array join 1265 in Internet Explorer, and 1207 ms in Firefox.

The maximum iteration count I could test in Internet Explorer without having "the script is taking too long to execute" was 850,000. Then Internet Explorer was 1593 for string concatenation and 2046 for array join, and Firefox had 2101 for string concatenation and 2249 for array join.

Results - if the number of iterations is small, you can try to use array.join(), as it might be faster in Firefox. When the number increases, the string1+string2 method is faster.

UPDATE

I performed the test on Internet Explorer 6 (Windows XP). The process stopped to respond immediately and never ended, if I tried the test on more than 100,000 iterations. On 40,000 iterations the results were

Time (strings): 59175 ms
Time (arrays): 220 ms

This means - if you need to support Internet Explorer 6, choose array.join() which is way faster than string concatenation.

Utilizing multi core for tar+gzip/bzip compression/decompression

You can also use the tar flag "--use-compress-program=" to tell tar what compression program to use.

For example use:

tar -c --use-compress-program=pigz -f tar.file dir_to_zip 

What's the reason I can't create generic array types in Java?

Quote:

Arrays of generic types are not allowed because they're not sound. The problem is due to the interaction of Java arrays, which are not statically sound but are dynamically checked, with generics, which are statically sound and not dynamically checked. Here is how you could exploit the loophole:

class Box<T> {
    final T x;
    Box(T x) {
        this.x = x;
    }
}

class Loophole {
    public static void main(String[] args) {
        Box<String>[] bsa = new Box<String>[3];
        Object[] oa = bsa;
        oa[0] = new Box<Integer>(3); // error not caught by array store check
        String s = bsa[0].x; // BOOM!
    }
}

We had proposed to resolve this problem using statically safe arrays (aka Variance) bute that was rejected for Tiger.

-- gafter

(I believe it is Neal Gafter, but am not sure)

See it in context here: http://forums.sun.com/thread.jspa?threadID=457033&forumID=316

Read input stream twice

You can wrap input stream with PushbackInputStream. PushbackInputStream allows to unread ("write back") bytes which were already read, so you can do like this:

public class StreamTest {
  public static void main(String[] args) throws IOException {
    byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    InputStream originalStream = new ByteArrayInputStream(bytes);

    byte[] readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 1 2 3

    readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 4 5 6

    // now let's wrap it with PushBackInputStream

    originalStream = new ByteArrayInputStream(bytes);

    InputStream wrappedStream = new PushbackInputStream(originalStream, 10); // 10 means that maximnum 10 characters can be "written back" to the stream

    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 1 2 3

    ((PushbackInputStream) wrappedStream).unread(readBytes, 0, readBytes.length);

    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 1 2 3


  }

  private static byte[] getBytes(InputStream is, int howManyBytes) throws IOException {
    System.out.print("Reading stream: ");

    byte[] buf = new byte[howManyBytes];

    int next = 0;
    for (int i = 0; i < howManyBytes; i++) {
      next = is.read();
      if (next > 0) {
        buf[i] = (byte) next;
      }
    }
    return buf;
  }

  private static void printBytes(byte[] buffer) throws IOException {
    System.out.print("Reading stream: ");

    for (int i = 0; i < buffer.length; i++) {
      System.out.print(buffer[i] + " ");
    }
    System.out.println();
  }


}

Please note that PushbackInputStream stores internal buffer of bytes so it really creates a buffer in memory which holds bytes "written back".

Knowing this approach we can go further and combine it with FilterInputStream. FilterInputStream stores original input stream as a delegate. This allows to create new class definition which allows to "unread" original data automatically. The definition of this class is following:

public class TryReadInputStream extends FilterInputStream {
  private final int maxPushbackBufferSize;

  /**
  * Creates a <code>FilterInputStream</code>
  * by assigning the  argument <code>in</code>
  * to the field <code>this.in</code> so as
  * to remember it for later use.
  *
  * @param in the underlying input stream, or <code>null</code> if
  *           this instance is to be created without an underlying stream.
  */
  public TryReadInputStream(InputStream in, int maxPushbackBufferSize) {
    super(new PushbackInputStream(in, maxPushbackBufferSize));
    this.maxPushbackBufferSize = maxPushbackBufferSize;
  }

  /**
   * Reads from input stream the <code>length</code> of bytes to given buffer. The read bytes are still avilable
   * in the stream
   *
   * @param buffer the destination buffer to which read the data
   * @param offset  the start offset in the destination <code>buffer</code>
   * @aram length how many bytes to read from the stream to buff. Length needs to be less than
   *        <code>maxPushbackBufferSize</code> or IOException will be thrown
   *
   * @return number of bytes read
   * @throws java.io.IOException in case length is
   */
  public int tryRead(byte[] buffer, int offset, int length) throws IOException {
    validateMaxLength(length);

    // NOTE: below reading byte by byte instead of "int bytesRead = is.read(firstBytes, 0, maxBytesOfResponseToLog);"
    // because read() guarantees to read a byte

    int bytesRead = 0;

    int nextByte = 0;

    for (int i = 0; (i < length) && (nextByte >= 0); i++) {
      nextByte = read();
      if (nextByte >= 0) {
        buffer[offset + bytesRead++] = (byte) nextByte;
      }
    }

    if (bytesRead > 0) {
      ((PushbackInputStream) in).unread(buffer, offset, bytesRead);
    }

    return bytesRead;

  }

  public byte[] tryRead(int maxBytesToRead) throws IOException {
    validateMaxLength(maxBytesToRead);

    ByteArrayOutputStream baos = new ByteArrayOutputStream(); // as ByteArrayOutputStream to dynamically allocate internal bytes array instead of allocating possibly large buffer (if maxBytesToRead is large)

    // NOTE: below reading byte by byte instead of "int bytesRead = is.read(firstBytes, 0, maxBytesOfResponseToLog);"
    // because read() guarantees to read a byte

    int nextByte = 0;

    for (int i = 0; (i < maxBytesToRead) && (nextByte >= 0); i++) {
      nextByte = read();
      if (nextByte >= 0) {
        baos.write((byte) nextByte);
      }
    }

    byte[] buffer = baos.toByteArray();

    if (buffer.length > 0) {
      ((PushbackInputStream) in).unread(buffer, 0, buffer.length);
    }

    return buffer;

  }

  private void validateMaxLength(int length) throws IOException {
    if (length > maxPushbackBufferSize) {
      throw new IOException(
        "Trying to read more bytes than maxBytesToRead. Max bytes: " + maxPushbackBufferSize + ". Trying to read: " +
        length);
    }
  }

}

This class has two methods. One for reading into existing buffer (defintion is analogous to calling public int read(byte b[], int off, int len) of InputStream class). Second which returns new buffer (this may be more effective if the size of buffer to read is unknown).

Now let's see our class in action:

public class StreamTest2 {
  public static void main(String[] args) throws IOException {
    byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    InputStream originalStream = new ByteArrayInputStream(bytes);

    byte[] readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 1 2 3

    readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 4 5 6

    // now let's use our TryReadInputStream

    originalStream = new ByteArrayInputStream(bytes);

    InputStream wrappedStream = new TryReadInputStream(originalStream, 10);

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); // NOTE: no manual call to "unread"(!) because TryReadInputStream handles this internally
    printBytes(readBytes); // prints 1 2 3

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); 
    printBytes(readBytes); // prints 1 2 3

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3);
    printBytes(readBytes); // prints 1 2 3

    // we can also call normal read which will actually read the bytes without "writing them back"
    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 1 2 3

    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 4 5 6

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); // now we can try read next bytes
    printBytes(readBytes); // prints 7 8 9

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); 
    printBytes(readBytes); // prints 7 8 9


  }



}

How can I listen for keypress event on the whole page?

I would use @HostListener decorator within your component:

import { HostListener } from '@angular/core';

@Component({
  ...
})
export class AppComponent {

  @HostListener('document:keypress', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) { 
    this.key = event.key;
  }
}

There are also other options like:

host property within @Component decorator

Angular recommends using @HostListener decorator over host property https://angular.io/guide/styleguide#style-06-03

@Component({
  ...
  host: {
    '(document:keypress)': 'handleKeyboardEvent($event)'
  }
})
export class AppComponent {
  handleKeyboardEvent(event: KeyboardEvent) {
    console.log(event);
  }
}

renderer.listen

import { Component, Renderer2 } from '@angular/core';

@Component({
  ...
})
export class AppComponent {
  globalListenFunc: Function;

  constructor(private renderer: Renderer2) {}

  ngOnInit() {
    this.globalListenFunc = this.renderer.listen('document', 'keypress', e => {
      console.log(e);
    });
  }

  ngOnDestroy() {
    // remove listener
    this.globalListenFunc();
  }
}

Observable.fromEvent

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import { Subscription } from 'rxjs/Subscription';

@Component({
  ...
})
export class AppComponent {
  subscription: Subscription;

  ngOnInit() {
    this.subscription = Observable.fromEvent(document, 'keypress').subscribe(e => {
      console.log(e);
    })
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

Windows task scheduler error 101 launch failure code 2147943785

Had the same issue today. I added the user to:

Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Log on as a batch job

But was still getting the error. I found this post, and it turns out there's also this setting that I had to remove the user from (not sure how it got in there):

Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Deny log on as a batch job

So just be aware that you may need to check both policies for the user.

jQuery looping .each() JSON key/value not working

With a simple JSON object, you don't need jQuery:

for (var i in json) {
   for (var j in json[i]) {
     console.log(json[i][j]);
   }
}

How to detect idle time in JavaScript elegantly?

Pure JavaScript with properly set reset time and bindings via addEventListener

(function() {

  var t,
    timeout = 5000;

  function resetTimer() {
    console.log("reset: " + new Date().toLocaleString());
    if (t) { 
      window.clearTimeout(t); 
    }
    t = window.setTimeout(logout, timeout);
  }

  function logout() {
    console.log("done: " + new Date().toLocaleString());
  }
  resetTimer();

  //And bind the events to call `resetTimer()`
  ["click", "mousemove", "keypress"].forEach(function(name) {
    console.log(name);
    document.addEventListener(name, resetTimer);
  });

}());

Read tab-separated file line into array

You're very close:

while IFS=$'\t' read -r -a myArray
do
 echo "${myArray[0]}"
 echo "${myArray[1]}"
 echo "${myArray[2]}"
done < myfile

(The -r tells read that \ isn't special in the input data; the -a myArray tells it to split the input-line into words and store the results in myArray; and the IFS=$'\t' tells it to use only tabs to split words, instead of the regular Bash default of also allowing spaces to split words as well. Note that this approach will treat one or more tabs as the delimiter, so if any field is blank, later fields will be "shifted" into earlier positions in the array. Is that O.K.?)

Button inside of anchor link works in Firefox but not in Internet Explorer?

Since this is only an issue in IE, to resolve this, I'm first detecting if the browser is IE and if so, use a jquery click event. I put this code into a global file so it's fixed throughout the site.

if (navigator.appName === 'Microsoft Internet Explorer')
{
    $('a input.button').click(function()
    {
        window.location = $(this).closest('a').attr('href');
    });
}

This way we only have the overhead of assigning click events to linked input buttons for IE. note: The above code is inside a document ready function to make sure the page is completely loaded before assigning click events.

I also assigned class names to my input buttons to save some overhead when using IE so I can search for

$('a input.button')

instead of

$('a input[type=button]')

.

<a href="some_link"><input type="button" class="button" value="some value" /></a>

On top of all that, I'm also utilizing CSS to make the buttons look clickable when your mouse hovers over it:

input.button {cursor: pointer}

How to display my application's errors in JSF?

In case anyone was curious, I was able to figure this out based on all of your responses combined!

This is in the Facelet:

<h:form id="myform">
  <h:inputSecret value="#{createNewPassword.newPassword1}" id="newPassword1" />
  <h:message class="error" for="newPassword1" id="newPassword1Error" />
  <h:inputSecret value="#{createNewPassword.newPassword2}" id="newPassword2" />
  <h:message class="error" for="newPassword2" id="newPassword2Error" />
  <h:commandButton value="Continue" action="#{createNewPassword.continueButton}" />
</h:form>

This is in the continueButton() method:

FacesContext.getCurrentInstance().addMessage("myForm:newPassword1", new FacesMessage(PASSWORDS_DONT_MATCH, PASSWORDS_DONT_MATCH));

And it works! Thanks for the help!

Session only cookies with Javascript

A simpler solution would be to use sessionStorage, in this case:

var myVariable = "Hello World";

sessionStorage['myvariable'] = myVariable;

var readValue = sessionStorage['myvariable'];
console.log(readValue);

However, keep in mind that sessionStorage saves everything as a string, so when working with arrays / objects, you can use JSON to store them:

var myVariable = {a:[1,2,3,4], b:"some text"};

sessionStorage['myvariable'] = JSON.stringify(myVariable);
var readValue = JSON.parse(sessionStorage['myvariable']);

A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.

So, when you close the page / tab, the data is lost.

Using routes in Express-js

The route-map express example matches url paths with objects which in turn matches http verbs with functions. This lays the routing out in a tree, which is concise and easy to read. The apps's entities are also written as objects with the functions as enclosed methods.

var express = require('../../lib/express')
  , verbose = process.env.NODE_ENV != 'test'
  , app = module.exports = express();

app.map = function(a, route){
  route = route || '';
  for (var key in a) {
    switch (typeof a[key]) {
      // { '/path': { ... }}
      case 'object':
        app.map(a[key], route + key);
        break;
      // get: function(){ ... }
      case 'function':
        if (verbose) console.log('%s %s', key, route);
        app[key](route, a[key]);
        break;
    }
  }
};

var users = {
  list: function(req, res){
    res.send('user list');
  },

  get: function(req, res){
    res.send('user ' + req.params.uid);
  },

  del: function(req, res){
    res.send('delete users');
  }
};

var pets = {
  list: function(req, res){
    res.send('user ' + req.params.uid + '\'s pets');
  },

  del: function(req, res){
    res.send('delete ' + req.params.uid + '\'s pet ' + req.params.pid);
  }
};

app.map({
  '/users': {
    get: users.list,
    del: users.del,
    '/:uid': {
      get: users.get,
      '/pets': {
        get: pets.list,
        '/:pid': {
          del: pets.del
        }
      }
    }
  }
});

app.listen(3000);

How to catch curl errors in PHP

    $responseInfo = curl_getinfo($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $body = substr($response, $header_size);
    $result=array();
    $result['httpCode']=$httpCode;
    $result['body']=json_decode($body);
    $result['responseInfo']=$responseInfo;
    print_r($httpCode); 
     print_r($result['body']); exit;
    curl_close($ch);
    if($httpCode == 403)
    {
        print_r("Access denied");
        exit;
    }   
    else
     {
         //catch more errors 
     }

GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

Just want to add another way of doing this. I've seen multiple people on various related threads ask if you can use VerifyRenderingInServerForm without adding it to the parent page.

You actually can do this but it's a bit of a bodge.

First off create a new Page class which looks something like the following:

public partial class NoRenderPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    { }

    public override void VerifyRenderingInServerForm(Control control)
    {
        //Allows for printing
    }

    public override bool EnableEventValidation
    {
        get { return false; }
        set { /*Do nothing*/ }
    }
}

Does not need to have an .ASPX associated with it.

Then in the control you wish to render you can do something like the following.

    StringWriter tw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(tw);

    var page = new NoRenderPage();
    page.DesignerInitialize();
    var form = new HtmlForm();
    page.Controls.Add(form);
    form.Controls.Add(pnl);
    controlToRender.RenderControl(hw);

Now you've got your original control rendered as HTML. If you need to, add the control back into it's original position. You now have the HTML rendered, the page as normal and no changes to the page itself.

curl: (60) SSL certificate problem: unable to get local issuer certificate

So far, I've seen this issue happen within corporate networks because of two reasons, one or both of which may be happening in your case:

  1. Because of the way network proxies work, they have their own SSL certificates, thereby altering the certificates that curl sees. Many or most enterprise networks force you to use these proxies.
  2. Some antivirus programs running on client PCs also act similarly to an HTTPS proxy, so that they can scan your network traffic. Your antivirus program may have an option to disable this function (assuming your administrators will allow it).

As a side note, No. 2 above may make you feel uneasy about your supposedly secure TLS traffic being scanned. That's the corporate world for you.

How to call a method defined in an AngularJS directive?

Just use scope.$parent to associate function called to directive function

angular.module('myApp', [])
.controller('MyCtrl',['$scope',function($scope) {

}])
.directive('mydirective',function(){
 function link(scope, el, attr){
   //use scope.$parent to associate the function called to directive function
   scope.$parent.myfunction = function directivefunction(parameter){
     //do something
}
}
return {
        link: link,
        restrict: 'E'   
      };
});

in HTML

<div ng-controller="MyCtrl">
    <mydirective></mydirective>
    <button ng-click="myfunction(parameter)">call()</button>
</div>

Role/Purpose of ContextLoaderListener in Spring?

In the context of spring framework purpose of ContextLoaderListener is to load the other beans in your application such as the middle-tier and data-tier components that drive the back end of the application.

rm: cannot remove: Permission denied

The code says everything:

max@serv$ chmod 777 .

Okay, it doesn't say everything.

In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.

Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.

How do I add multiple conditions to "ng-disabled"?

Make sure you wrap the condition in the correct precedence

ng-disabled="((!product.img) || (!product.name))"

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

I would like to quote an answer given by Microsoft support engineer at here:-

http://answers.microsoft.com/en-us/windows/forum/windows_8-winapps/the-program-cant-start-because-msvcr110dll-is/f052d325-3af9-4ae5-990b-b080799724db

Hi Henny, MSVCR110.dll is the Microsoft Visual C++ Redistributable dll that is needed for projects built with Visual Studio 2011. The dll letters spell this out. MS = Microsoft, V = Visual, C = C++, R = Redistributable For Winroy to get started, this file is probably needed. This error appears when you wish to run a software which require the Microsoft Visual C++ Redistributable 2012. The redistributable can easily be downloaded on the Microsoft website as x86 or x64 edition. Depending on the software you wish to install you need to install either the 32 bit or the 64 bit version. Refer the following link: http://www.microsoft.com/en-us/download/details.aspx?id=30679# Please let us know if the issue persists. We will be happy to assist you further. Thanks, Yaqub Khan - Microsoft Support Engineer

htons() function in socket programing

htons is host-to-network short

This means it works on 16-bit short integers. i.e. 2 bytes.

This function swaps the endianness of a short.

Your number starts out at:

0001 0011 1000 1001 = 5001

When the endianness is changed, it swaps the two bytes:

1000 1001 0001 0011 = 35091

Change the background color of a pop-up dialog

Only update your import.

import android.app.AlertDialog;

to

import android.support.v7.app.AlertDialog;

It will be fixed.

How do I get total physical memory size using PowerShell without WMI?

I'd like to make a note of this for people referencing in the future.

I wanted to avoid WMI because it uses a DCOM protocol, requiring the remote computer to have the necessary permissions, which could only be setup manually on that remote computer.

So, I wanted to avoid using WMI, but using get-counter often times didn't have the performance counter I wanted.

The solution I used was the Common Information Model (CIM). Unlike WMI, CIM doesn't use DCOM by default. Instead of returning WMI objects, CIM cmdlets return PowerShell objects.

CIM uses the Ws-MAN protocol by default, but it only works with computers that have access to Ws-Man 3.0 or later. So, earlier versions of PowerShell wouldn't be able to issue CIM cmdlets.

The cmdlet I ended up using to get total physical memory size was:

get-ciminstance -class "cim_physicalmemory" | % {$_.Capacity}

How can I make a button have a rounded border in Swift?

Use button.layer.cornerRadius, button.layer.borderColor and button.layer.borderWidth. Note that borderColor requires a CGColor, so you could say (Swift 3/4):

button.backgroundColor = .clear
button.layer.cornerRadius = 5
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.black.cgColor

Creating a list/array in excel using VBA to get a list of unique names in a column

You can try my suggestion for a work around in Doug's approach.
But if you want to stick with your logic though, you can try this:

Option Explicit

Sub GetUnique()

Dim rng As Range
Dim myarray, myunique
Dim i As Integer

ReDim myunique(1)

With ThisWorkbook.Sheets("Sheet1")
    Set rng = .Range(.Range("A1"), .Range("A" & .Rows.Count).End(xlUp))
    myarray = Application.Transpose(rng)
    For i = LBound(myarray) To UBound(myarray)
        If IsError(Application.Match(myarray(i), myunique, 0)) Then
            myunique(UBound(myunique)) = myarray(i)
            ReDim Preserve myunique(UBound(myunique) + 1)
        End If
    Next
End With

For i = LBound(myunique) To UBound(myunique)
    Debug.Print myunique(i)
Next

End Sub

This uses array instead of range.
It also uses Match function instead of a nested For Loop.
I didn't have the time to check the time difference though.
So I leave the testing to you.

raw vs. html_safe vs. h to unescape html

The best safe way is: <%= sanitize @x %>

It will avoid XSS!

Using putty to scp from windows to Linux

Use scp priv_key.pem source user@host:target if you need to connect using a private key.

or if using pscp then use pscp -i priv_key.ppk source user@host:target

How to create a file in Linux from terminal window?

Depending on what you want the file to contain:

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.

      eg: grep --help > randomtext.txt
          echo "This is some text" > randomtext.txt
    
  • nano /path/to/file or vi /path/to/file (or any other editor emacs,gedit etc)
    It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist


Create the file using cat

$ cat > myfile.txt

Now, just type whatever you want in the file:

Hello World!

CTRL-D to save and exit


There are several possible solutions:

Create an empty file

touch file

>file

echo -n > file

printf '' > file

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file

printf '\n' > file

This is a valid "text file" because it ends in a newline.

Write text into a file

"$EDITOR" file

echo 'text' > file

cat > file <<END \
text
END

printf 'text\n' > file

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

For me the solution was to set the version of the maven compiler plugin to 3.8.0 and specify the release (9 for in your case, 11 in mine)

    <plugin>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.8.0</version>
      <configuration>
        <release>11</release>
      </configuration>
    </plugin>

How to use ES6 Fat Arrow to .filter() an array of objects

As simple as you can use const adults = family.filter(({ age }) => age > 18 );

_x000D_
_x000D_
const family =[{"name":"Jack",  "age": 26},_x000D_
              {"name":"Jill",  "age": 22},_x000D_
              {"name":"James", "age": 5 },_x000D_
              {"name":"Jenny", "age": 2 }];_x000D_
_x000D_
const adults = family.filter(({ age }) => age > 18 );_x000D_
_x000D_
console.log(adults)
_x000D_
_x000D_
_x000D_

How to compile python script to binary executable

Or use PyInstaller as an alternative to py2exe. Here is a good starting point. PyInstaller also lets you create executables for linux and mac...

Here is how one could fairly easily use PyInstaller to solve the issue at hand:

pyinstaller oldlogs.py

From the tool's documentation:

PyInstaller analyzes myscript.py and:

  • Writes myscript.spec in the same folder as the script.
  • Creates a folder build in the same folder as the script if it does not exist.
  • Writes some log files and working files in the build folder.
  • Creates a folder dist in the same folder as the script if it does not exist.
  • Writes the myscript executable folder in the dist folder.

In the dist folder you find the bundled app you distribute to your users.

Running AngularJS initialization code when view is loaded

Since AngularJS 1.5 we should use $onInit which is available on any AngularJS component. Taken from the component lifecycle documentation since v1.5 its the preffered way:

$onInit() - Called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions for the directives on this element). This is a good place to put initialization code for your controller.

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {

    //default state
    $scope.name = '';

    //all your init controller goodness in here
    this.$onInit = function () {
      $scope.name = 'Superhero';
    }
});

>> Fiddle Demo


An advanced example of using component lifecycle:

The component lifecycle gives us the ability to handle component stuff in a good way. It allows us to create events for e.g. "init", "change" or "destroy" of an component. In that way we are able to manage stuff which is depending on the lifecycle of an component. This little example shows to register & unregister an $rootScope event listener $on. By knowing, that an event $on binded on $rootScope will not be undinded when the controller loses its reference in the view or getting destroyed we need to destroy a $rootScope.$on listener manually. A good place to put that stuff is $onDestroy lifecycle function of an component:

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

myApp.controller('MyCtrl', function ($scope, $rootScope) {

  var registerScope = null;

  this.$onInit = function () {
    //register rootScope event
    registerScope = $rootScope.$on('someEvent', function(event) {
        console.log("fired");
    });
  }

  this.$onDestroy = function () {
    //unregister rootScope event by calling the return function
    registerScope();
  }
});

>> Fiddle demo

List of enum values in java

tl;dr

Can you make and edit a collection of objects from an enum? Yes.

If you do not care about the order, use EnumSet, an implementation of Set.

enum Animal{ DOG , CAT , BIRD , BAT ; }

Set<Animal> flyingAnimals = EnumSet.of( BIRD , BAT );

Set<Animal> featheredFlyingAnimals = flyingAnimals.clone().remove( BAT ) ;

If you care about order, use a List implementation such as ArrayList. For example, we can create a list of a person’s preference in choosing a pet, in the order of their most preferred.

List< Animal > favoritePets = new ArrayList<>() ;
favoritePets.add( CAT ) ;  // This person prefers cats over dogs…
favoritePets.add( DOG ) ;  // …but would accept either.
                           // This person would not accept a bird nor a bat.

For a non-modifiable ordered list, use List.of.

List< Animal > favoritePets = List.of( CAT , DOG ) ;  // This person prefers cats over dogs, but would accept either. This person would not accept a bird nor a bat. 

Details

The Answer (EnumSet) by Amit Deshpande and the Answer (.values) by Marko Topolnik are both correct. Here is a bit more info.

Enum.values

The .values() method is an implicitly declared method on Enum, added by the compiler. It produces a crude array rather than a Collection. Certainly usable.

Special note about documentation: Being unusual as an implicitly declared method, the .values() method is not listed among the methods on the Enum class. The method is defined in the Java Language Specification, and is mentioned in the doc for Enum.valueOf.

EnumSet – Fast & Small

The upsides to EnumSet include:

  • Extreme speed.
  • Compact use of memory.

To quote the class doc:

Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags." Even bulk operations (such as containsAll and retainAll) should run very quickly if their argument is also an enum set.

Given this enum:

enum Animal
{
    DOG , CAT , BIRD , BAT ;
}

Make an EnumSet in one line.

Set<Animal> allAnimals = EnumSet.allOf( Animal.class );

Dump to console.

System.out.println( "allAnimals : " + allAnimals );

allAnimals : [DOG, CAT, BIRD, BAT]

Make a set from a subset of the enum objects.

Set<Animal> flyingAnimals = EnumSet.of( BIRD , BAT );

Look at the class doc to see many ways to manipulate the collection including adding or removing elements.

Set<Animal> featheredFlyingAnimals = 
    EnumSet.copyOf( flyingAnimals ).remove( BAT );

Natural Order

The doc promises the Iterator for EnumSet is in natural order, the order in which the values of the enum were originally declared.

To quote the class doc:

The iterator returned by the iterator method traverses the elements in their natural order (the order in which the enum constants are declared).

Frankly, given this promise, I'm confused why this is not a SortedSet. But, oh well, good enough. We can create a List from the Set if desired. Pass any Collection to constructor of ArrayList and that collection’s Iterator is automatically called on your behalf.

List<Animal> list = new ArrayList<>( allAnimals );

Dump to console.

System.out.println("list : " + list );

When run.

list : [DOG, CAT, BIRD, BAT]

In Java 10 and later, you can conveniently create a non-modifiable List by passing the EnumSet. The order of the new list will be in the iterator order of the EnumSet. The iterator order of an EnumSet is the order in which the element objects of the enum were defined on that enum.

List< Animal > nonModList = List.copyOf( allAnimals ) ;  // Or pass Animals.values() 

How to increment an iterator by 2?

You could use the 'assignment by addition' operator

iter += 2;

Reducing video size with same format and reducing frame size

I found myself wanting to do this too recently, so I created a tool called Shrinkwrap that uses FFmpeg to transcode videos, while preserving as much of the original metadata as possible (including file modification timestamps).

You can run it as a docker container:

docker run -v /path/to/your/videos:/vids bennetimo/shrinkwrap \
--input-extension mp4 --ffmpeg-opts crf=22,preset=fast /vids

Where:

  • /path/to/your/videos/ is where the videos are that you want to convert
  • --input-extension is the type of videos you want to process, here .mp4
  • --ffmpeg-opts is any arbitrary FFmpeg options you want to use to customise the transcode

Then it will recursively find all of the video files that match the extension and transcode them all into files of the same name with a -tc suffix.

For more configuration options, presets for GoPro etc, see the readme.

Hope this helps someone!

[Vue warn]: Cannot find element

You can solve it in two ways.

  1. Make sure you put the CDN into the end of html page and place your own script after that. Example:
    <body>
      <div id="main">
        <div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
      </div>
    </body>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
    <script src="js/app.js"></script>

where you need to put same javascript code you wrote in any other JavaScript file or in html file.

  1. Use window.onload function in your JavaScript file.

Insert HTML from CSS

No. The only you can do is to add content (and not an element) using :before or :after pseudo-element.

More information: http://www.w3.org/TR/CSS2/generate.html#before-after-content