Programs & Examples On #Start process

Start-Process is a powershell cmdlet that starts one or more processes on the local computer.

PowerShell - Start-Process and Cmdline Switches

I've found using cmd works well as an alternative, especially when you need to pipe the output from the called application (espeically when it doesn't have built in logging, unlike msbuild)

cmd /C "$msbuild $args" >> $outputfile

Capturing standard out and error with Start-Process

IMPORTANT:

We have been using the function as provided above by LPG.

However, this contains a bug you might encounter when you start a process that generates a lot of output. Due to this you might end up with a deadlock when using this function. Instead use the adapted version below:

Function Execute-Command ($commandTitle, $commandPath, $commandArguments)
{
  Try {
    $pinfo = New-Object System.Diagnostics.ProcessStartInfo
    $pinfo.FileName = $commandPath
    $pinfo.RedirectStandardError = $true
    $pinfo.RedirectStandardOutput = $true
    $pinfo.UseShellExecute = $false
    $pinfo.Arguments = $commandArguments
    $p = New-Object System.Diagnostics.Process
    $p.StartInfo = $pinfo
    $p.Start() | Out-Null
    [pscustomobject]@{
        commandTitle = $commandTitle
        stdout = $p.StandardOutput.ReadToEnd()
        stderr = $p.StandardError.ReadToEnd()
        ExitCode = $p.ExitCode
    }
    $p.WaitForExit()
  }
  Catch {
     exit
  }
}

Further information on this issue can be found at MSDN:

A deadlock condition can result if the parent process calls p.WaitForExit before p.StandardError.ReadToEnd and the child process writes enough text to fill the redirected stream. The parent process would wait indefinitely for the child process to exit. The child process would wait indefinitely for the parent to read from the full StandardError stream.

How do I assert equality on two classes without an equals method?

You can override the equals method of the class like:

@Override
public int hashCode() {
    int hash = 0;
    hash += (app != null ? app.hashCode() : 0);
    return hash;
}

@Override
public boolean equals(Object object) {
    HubRule other = (HubRule) object;

    if (this.app.equals(other.app)) {
        boolean operatorHubList = false;

        if (other.operator != null ? this.operator != null ? this.operator
                .equals(other.operator) : false : true) {
            operatorHubList = true;
        }

        if (operatorHubList) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

Well, if you want to compare two object from a class you must implement in some way the equals and the hash code method

SELECT query with CASE condition and SUM()

To get each sum in a separate column:

Select SUM(IF(CPaymentType='Check', CAmount, 0)) as PaymentAmountCheck,
       SUM(IF(CPaymentType='Cash', CAmount, 0)) as PaymentAmountCash
from TableOrderPayment
where CPaymentType IN ('Check','Cash') 
and CDate<=SYSDATETIME() 
and CStatus='Active';

Check if object is a jQuery object

You can check if the object is produced by JQuery with the jquery property:

myObject.jquery // 3.3.1

=> return the number of the JQuery version if the object produced by JQuery. => otherwise, it returns undefined

How would you count occurrences of a string (actually a char) within a string?

            var conditionalStatement = conditionSetting.Value;

            //order of replace matters, remove == before =, incase of ===
            conditionalStatement = conditionalStatement.Replace("==", "~").Replace("!=", "~").Replace('=', '~').Replace('!', '~').Replace('>', '~').Replace('<', '~').Replace(">=", "~").Replace("<=", "~");

            var listOfValidConditions = new List<string>() { "!=", "==", ">", "<", ">=", "<=" };

            if (conditionalStatement.Count(x => x == '~') != 1)
            {
                result.InvalidFieldList.Add(new KeyFieldData(batch.DECurrentField, "The IsDoubleKeyCondition does not contain a supported conditional statement. Contact System Administrator."));
                result.Status = ValidatorStatus.Fail;
                return result;
            }

Needed to do something similar to test conditional statements from a string.

Replaced what i was looking for with a single character and counted the instances of the single character.

Obviously the single character you're using will need to be checked to not exist in the string before this happens to avoid incorrect counts.

What's the difference between an element and a node in XML?

A node can be a number of different kinds of things: some text, a comment, an element, an entity, etc. An element is a particular kind of node.

Counting Chars in EditText Changed Listener

This is a slightly more general answer with more explanation for future viewers.

Add a text changed listener

If you want to find the text length or do something else after the text has been changed, you can add a text changed listener to your edit text.

EditText editText = (EditText) findViewById(R.id.testEditText);
editText.addTextChangedListener(new TextWatcher() {

    @Override
    public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int start, int before, int count)  {

    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
});

The listener needs a TextWatcher, which requires three methods to be overridden: beforeTextChanged, onTextChanged, and afterTextChanged.

Counting the characters

You can get the character count in onTextChanged or beforeTextChanged with

charSequence.length()

or in afterTextChanged with

editable.length()

Meaning of the methods

The parameters are a little confusing so here is a little extra explanation.

beforeTextChanged

beforeTextChanged(CharSequence charSequence, int start, int count, int after)

  • charSequence: This is the text content before the pending change is made. You should not try to change it.
  • start: This is the index of where the new text will be inserted. If a range is selected, then it is the beginning index of the range.
  • count: This is the length of selected text that is going to be replaced. If nothing is selected then count will be 0.
  • after: this is the length of the text to be inserted.

onTextChanged

onTextChanged(CharSequence charSequence, int start, int before, int count)

  • charSequence: This is the text content after the change was made. You should not try to modify this value here. Modify the editable in afterTextChanged if you need to.
  • start: This is the index of the start of where the new text was inserted.
  • before: This is the old value. It is the length of previously selected text that was replaced. This is the same value as count in beforeTextChanged.
  • count: This is the length of text that was inserted. This is the same value as after in beforeTextChanged.

afterTextChanged

afterTextChanged(Editable editable)

Like onTextChanged, this is called after the change has already been made. However, now the text may be modified.

  • editable: This is the editable text of the EditText. If you change it, though, you have to be careful not to get into an infinite loop. See the documentation for more details.

Supplemental image from this answer

enter image description here

PHP class not found but it's included

First of all check if $ENGINE."/classUser.php" is a valid name of existing file. Try this:

var_dump(file_exists($ENGINE."/classUser.php"));

Can I embed a custom font in an iPhone application?

Find the TTF in finder and "Get Info". Under the heading "Full name:" it gave me a name which I then used with fontWithName (I just copied and pasted the exact name, in this case no '.ttf' extension was necessary).

Get full path without filename from path that includes filename

    string fileAndPath = @"c:\webserver\public\myCompany\configs\promo.xml";

    string currentDirectory = Path.GetDirectoryName(fileAndPath);

    string fullPathOnly = Path.GetFullPath(currentDirectory);

currentDirectory: c:\webserver\public\myCompany\configs

fullPathOnly: c:\webserver\public\myCompany\configs

Can we install Android OS on any Windows Phone and vice versa, and same with iPhone and vice versa?

Android needs to be compiled for every hardware plattform / every device model seperatly with the specific drivers etc. If you manage to do that you need also break the security arrangements every manufacturer implements to prevent the installation of other software - these are also different between each model / manufacturer. So it is possible at in theory, but only there :-)

Find a file with a certain extension in folder

Use this code for read file with all type of extension file.

string[] sDirectoryInfo = Directory.GetFiles(SourcePath, "*.*");

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

It's the "frame" or "range" clause of window functions, which are part of the SQL standard and implemented in many databases, including Teradata.

A simple example would be to calculate the average amount in a frame of three days. I'm using PostgreSQL syntax for the example, but it will be the same for Teradata:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, avg(a) OVER (ORDER BY t ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
FROM data
ORDER BY t

... which yields:

t  a  avg
----------
1  1  3.00
2  5  3.00
3  3  4.33
4  5  4.00
5  4  6.67
6 11  7.50

As you can see, each average is calculated "over" an ordered frame consisting of the range between the previous row (1 preceding) and the subsequent row (1 following).

When you write ROWS UNBOUNDED PRECEDING, then the frame's lower bound is simply infinite. This is useful when calculating sums (i.e. "running totals"), for instance:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, sum(a) OVER (ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM data
ORDER BY t

yielding...

t  a  sum
---------
1  1    1
2  5    6
3  3    9
4  5   14
5  4   18
6 11   29

Here's another very good explanations of SQL window functions.

Adding options to select with javascript

When you create a new Option object, there are two parameters to pass: The first is the text you want to appear in the list, and the second the value to be assigned to the option.

var myNewOption = new Option("TheText", "TheValue");

You then simply assign this Option object to an empty array element, for example:

document.theForm.theSelectObject.options[0] = myNewOption;

Php artisan make:auth command is not defined

If you using >5 version of laravel then you will use.

composer require laravel/ui --dev **or** composer require laravel/ui

And then

php artisan ui:auth

What is the difference between "JPG" / "JPEG" / "PNG" / "BMP" / "GIF" / "TIFF" Image?

The file extension tells you how the image is saved. Some of those formats just save the bits as they are, some compress the image in different ways, including lossless and lossy methods. The Web can tell you, although I know some of the patient responders will outline them here.

The web favors gif, jpg, and png, mostly. JPEG is the same (or very close) to jpg.

Confirm deletion in modal / dialog using Twitter Bootstrap?

You can try more reusable my solution with callback function. In this function you can use POST request or some logic. Used libraries: JQuery 3> and Bootstrap 3>.

https://jsfiddle.net/axnikitenko/gazbyv8v/

Html code for test:

...
<body>
    <a href='#' id="remove-btn-a-id" class="btn btn-default">Test Remove Action</a>
</body>
...

Javascript:

$(function () {
    function remove() {
        alert('Remove Action Start!');
    }
    // Example of initializing component data
    this.cmpModalRemove = new ModalConfirmationComponent('remove-data', remove,
        'remove-btn-a-id', {
            txtModalHeader: 'Header Text For Remove', txtModalBody: 'Body For Text Remove',
            txtBtnConfirm: 'Confirm', txtBtnCancel: 'Cancel'
        });
    this.cmpModalRemove.initialize();
});

//----------------------------------------------------------------------------------------------------------------------
// COMPONENT SCRIPT
//----------------------------------------------------------------------------------------------------------------------
/**
 * Script processing data for confirmation dialog.
 * Used libraries: JQuery 3> and Bootstrap 3>.
 *
 * @param name unique component name at page scope
 * @param callback function which processing confirm click
 * @param actionBtnId button for open modal dialog
 * @param text localization data, structure:
 *              > txtModalHeader - text at header of modal dialog
 *              > txtModalBody - text at body of modal dialog
 *              > txtBtnConfirm - text at button for confirm action
 *              > txtBtnCancel - text at button for cancel action
 *
 * @constructor
 * @author Aleksey Nikitenko
 */
function ModalConfirmationComponent(name, callback, actionBtnId, text) {
    this.name = name;
    this.callback = callback;
    // Text data
    this.txtModalHeader =   text.txtModalHeader;
    this.txtModalBody =     text.txtModalBody;
    this.txtBtnConfirm =    text.txtBtnConfirm;
    this.txtBtnCancel =     text.txtBtnCancel;
    // Elements
    this.elmActionBtn = $('#' + actionBtnId);
    this.elmModalDiv = undefined;
    this.elmConfirmBtn = undefined;
}

/**
 * Initialize needed data for current component object.
 * Generate html code and assign actions for needed UI
 * elements.
 */
ModalConfirmationComponent.prototype.initialize = function () {
    // Generate modal html and assign with action button
    $('body').append(this.getHtmlModal());
    this.elmActionBtn.attr('data-toggle', 'modal');
    this.elmActionBtn.attr('data-target', '#'+this.getModalDivId());
    // Initialize needed elements
    this.elmModalDiv =  $('#'+this.getModalDivId());
    this.elmConfirmBtn = $('#'+this.getConfirmBtnId());
    // Assign click function for confirm button
    var object = this;
    this.elmConfirmBtn.click(function() {
        object.elmModalDiv.modal('toggle'); // hide modal
        object.callback(); // run callback function
    });
};

//----------------------------------------------------------------------------------------------------------------------
// HTML GENERATORS
//----------------------------------------------------------------------------------------------------------------------
/**
 * Methods needed for get html code of modal div.
 *
 * @returns {string} html code
 */
ModalConfirmationComponent.prototype.getHtmlModal = function () {
    var result = '<div class="modal fade" id="' + this.getModalDivId() + '"';
    result +=' tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">';
    result += '<div class="modal-dialog"><div class="modal-content"><div class="modal-header">';
    result += this.txtModalHeader + '</div><div class="modal-body">' + this.txtModalBody + '</div>';
    result += '<div class="modal-footer">';
    result += '<button type="button" class="btn btn-default" data-dismiss="modal">';
    result += this.txtBtnCancel + '</button>';
    result += '<button id="'+this.getConfirmBtnId()+'" type="button" class="btn btn-danger">';
    result += this.txtBtnConfirm + '</button>';
    return result+'</div></div></div></div>';
};

//----------------------------------------------------------------------------------------------------------------------
// UTILITY
//----------------------------------------------------------------------------------------------------------------------
/**
 * Get id element with name prefix for this component.
 *
 * @returns {string} element id
 */
ModalConfirmationComponent.prototype.getModalDivId = function () {
    return this.name + '-modal-id';
};

/**
 * Get id element with name prefix for this component.
 *
 * @returns {string} element id
 */
ModalConfirmationComponent.prototype.getConfirmBtnId = function () {
    return this.name + '-confirm-btn-id';
};

Kendo grid date column not formatting

Try formatting the date in the kendo grid as:

columns.Bound(x => x.LastUpdateDate).ClientTemplate("#= kendo.toString(LastUpdateDate, \"MM/dd/yyyy hh:mm tt\") #");

How to know the git username and email saved during configuration?

Considering what @Robert said, I tried to play around with the config command and it seems that there is a direct way to know both the name and email.

To know the username, type:

git config user.name

To know the email, type:

git config user.email

These two output just the name and email respectively and one doesn't need to look through the whole list. Comes in handy.

How to reverse a singly linked list using only two pointers?

To swap two variables without the use of a temporary variable,

a = a xor b
b = a xor b
a = a xor b

fastest way is to write it in one line

a = a ^ b ^ (b=a)

Similarly,

using two swaps

swap(a,b)
swap(b,c)

solution using xor

a = a^b^c
b = a^b^c
c = a^b^c
a = a^b^c

solution in one line

c = a ^ b ^ c ^ (a=b) ^ (b=c)
b = a ^ b ^ c ^ (c=a) ^ (a=b)
a = a ^ b ^ c ^ (b=c) ^ (c=a)

The same logic is used to reverse a linked list.

typedef struct List
{
 int info;
 struct List *next;
}List;


List* reverseList(List *head)
{
 p=head;
 q=p->next;
 p->next=NULL;
 while(q)
 {
    q = (List*) ((int)p ^ (int)q ^ (int)q->next ^ (int)(q->next=p) ^ (int)(p=q));
 }
 head = p;
 return head;
}  

How to Flatten a Multidimensional Array?

For php 5.2

function flatten(array $array) {
    $result = array();

    if (is_array($array)) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                $result = array_merge($result, flatten($v));
            } else {
                $result[] = $v;
            }
        }
    }

    return $result;
}

SQL Server - Create a copy of a database table and place it in the same database?

If you want to duplicate the table with all its constraints & keys follows this below steps:

  1. Open the database in SQL Management Studio.
  2. Right-click on the table that you want to duplicate.
  3. Select Script Table as -> Create to -> New Query Editor Window. This will generate a script to recreate the table in a new query window.
  4. Change the table name and relative keys & constraints in the script.
  5. Execute the script.

Then for copying the data run this below script:

SET IDENTITY_INSERT DuplicateTable ON

INSERT Into DuplicateTable ([Column1], [Column2], [Column3], [Column4],... ) 
SELECT [Column1], [Column2], [Column3], [Column4],... FROM MainTable

SET IDENTITY_INSERT DuplicateTable OFF

Getting a list of files in a directory with a glob

This works quite nicely for IOS, but should also work for cocoa.

NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSFileManager *manager = [NSFileManager defaultManager];
NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:bundleRoot];
NSString *filename;

while ((filename = [direnum nextObject] )) {

    //change the suffix to what you are looking for
    if ([filename hasSuffix:@".data"]) {   

        // Do work here
        NSLog(@"Files in resource folder: %@", filename);            
    }       
}

jquery $(this).id return Undefined

this : is the DOM Element $(this) : Jquery objct, which wrapped with Dom Element, you can check this answer also this vs $(this)

try like this Attr(). Get the value of an attribute for the first element in the set of matched elements.

$(document).ready(function () {
    $(".inputs").click(function () {
         alert(" or " + $(this).attr("id"));

    });
});

How to move text up using CSS when nothing is working

used the following snippet and it worked fine..

.smallText .bmv-disclaimer {
   height: 40px;
}

Tomcat 8 Maven Plugin for Java 8

An other solution (if possible) would be to use TomEE instead of Tomcat, which has a working maven plugin:

<plugin>
    <groupId>org.apache.tomee.maven</groupId>
    <artifactId>tomee-maven-plugin</artifactId>
    <version>7.1.1</version>
</plugin>

Version 7.1.1 wraps a Tomcat 8.5.41

Difference between opening a file in binary vs text

The most important difference to be aware of is that with a stream opened in text mode you get newline translation on non-*nix systems (it's also used for network communications, but this isn't supported by the standard library). In *nix newline is just ASCII linefeed, \n, both for internal and external representation of text. In Windows the external representation often uses a carriage return + linefeed pair, "CRLF" (ASCII codes 13 and 10), which is converted to a single \n on input, and conversely on output.


From the C99 standard (the N869 draft document), §7.19.2/2,

A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment. Thus, there need not be a one- to-one correspondence between the characters in a stream and those in the external representation. Data read in from a text stream will necessarily compare equal to the data that were earlier written out to that stream only if: the data consist only of printing characters and the control characters horizontal tab and new-line; no new-line character is immediately preceded by space characters; and the last character is a new-line character. Whether space characters that are written out immediately before a new-line character appear when read in is implementation-defined.

And in §7.19.3/2

Binary files are not truncated, except as defined in 7.19.5.3. Whether a write on a text stream causes the associated file to be truncated beyond that point is implementation- defined.

About use of fseek, in §7.19.9.2/4:

For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file and whence shall be SEEK_SET.

About use of ftell, in §17.19.9.4:

The ftell function obtains the current value of the file position indicator for the stream pointed to by stream. For a binary stream, the value is the number of characters from the beginning of the file. For a text stream, its file position indicator contains unspecified information, usable by the fseek function for returning the file position indicator for the stream to its position at the time of the ftell call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.

I think that’s the most important, but there are some more details.

this is error ORA-12154: TNS:could not resolve the connect identifier specified?

ORA-12154: TNS:could not resolve the connect identifier specified?

In case the TNS is not defined you can also try this one:

If you are using C#.net 2010 or other version of VS and oracle 10g express edition or lower version, and you make a connection string like this:

static string constr = @"Data Source=(DESCRIPTION=
    (ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=yourhostname )(PORT=1521)))
    (CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));
    User Id=system ;Password=yourpasswrd"; 

After that you get error message ORA-12154: TNS:could not resolve the connect identifier specified then first you have to do restart your system and run your project.

And if Your windows is 64 bit then you need to install oracle 11g 32 bit and if you installed 11g 64 bit then you need to Install Oracle 11g Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio version 11.2.0.1.2 or later from OTN and check it in Oracle Universal Installer Please be sure that the following are checked:

Oracle Data Provider for .NET 2.0

Oracle Providers for ASP.NET

Oracle Developer Tools for Visual Studio

Oracle Instant Client 

And then restart your Visual Studio and then run your project .... NOTE:- SYSTEM RESTART IS necessary TO SOLVE THIS TYPES OF ERROR.......

What is a 'workspace' in Visual Studio Code?

They call it a multi-root workspace, and with that you can do debugging easily because:

"With multi-root workspaces, Visual Studio Code searches across all folders for launch.json debug configuration files and displays them with the folder name as a suffix."

Say you have a server and a client folder inside your application folder. If you want to debug them together, without a workspace you have to start two Visual Studio Code instances, one for server, one for client and you need to switch back and forth.

But right now (1.24) you can't add a single file to a workspace, only folders, which is a little bit inconvenient.

IntelliJ: Error:java: error: release version 5 not supported

You need to set language level, release version and add maven compiler plugin to the pom.xml

<properties>
  <maven.compiler.source>1.8</maven.compiler.source>
  <maven.compiler.target>1.8</maven.compiler.target>
</properties>

<dependency>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>3.8.1</version>
</dependency>

How to animate CSS Translate

There are jQuery-plugins that help you achieve this like: http://ricostacruz.com/jquery.transit/

Control the size of points in an R scatterplot?

Try the cex argument:

?par

  • cex
    A numerical value giving the amount by which plotting text and symbols should be magnified relative to the default. Note that some graphics functions such as plot.default have an argument of this name which multiplies this graphical parameter, and some functions such as points accept a vector of values which are recycled. Other uses will take just the first value if a vector of length greater than one is supplied.

Storing image in database directly or as base64 data?

  • Pro base64: the encoded representation you handle is a pretty safe string. It contains neither control chars nor quotes. The latter point helps against SQL injection attempts. I wouldn't expect any problem to just add the value to a "hand coded" SQL query string.

  • Pro BLOB: the database manager software knows what type of data it has to expect. It can optimize for that. If you'd store base64 in a TEXT field it might try to build some index or other data structure for it, which would be really nice and useful for "real" text data but pointless and a waste of time and space for image data. And it is the smaller, as in number of bytes, representation.

ruby LoadError: cannot load such file

For security & other reasons, ruby does not by default include the current directory in the load_path. You may want to check this for more details - Why does Ruby 1.9.2 remove "." from LOAD_PATH, and what's the alternative?

What is bootstrapping?

IMHO there is not a better explanation than the fact about How was the first compiler written?

These days the Operating System loading is the most common process referred as Bootstrapping

Counting repeated elements in an integer array

package com.core_java;

import java.util.Arrays;
import java.util.Scanner;

public class Sim {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("Enter array size: ");
        int size = input.nextInt();

        int[] array = new int[size];

        // Read integers from the console
        System.out.println("Enter array elements: ");
        for (int i = 0; i < array.length; i++) {
            array[i] = input.nextInt();
        }
        Sim s = new Sim();
        s.find(array);
    }

    public void find(int[] arr) {
        int count = 1;
        Arrays.sort(arr);

        for (int i = 0; i < arr.length; i++) {

            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] == arr[j]) {
                    count++;
                }
            }
            if (count > 1) {
                System.out.println();
                System.out.println("repeated element in array " + arr[i] + ": " + count + " time(s)");
                i = i + count - 1;
            }
            count = 1;
        }
    }

}

What is the iPad user agent?

For iPad Only

Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10

g++ ld: symbol(s) not found for architecture x86_64

finally solved my problem.

I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.

Mail multipart/alternative vs multipart/mixed

Messages have content. Content can be text, html, a DataHandler or a Multipart, and there can only be one content. Multiparts only have BodyParts but can have more than one. BodyParts, like Messages, can have content which has already been described.

A message with HTML, text and an a attachment can be viewed hierarchically like this:

message
  mainMultipart (content for message, subType="mixed")
    ->htmlAndTextBodyPart (bodyPart1 for mainMultipart)
      ->htmlAndTextMultipart (content for htmlAndTextBodyPart, subType="alternative")
        ->textBodyPart (bodyPart2 for the htmlAndTextMultipart)
          ->text (content for textBodyPart)
        ->htmlBodyPart (bodyPart1 for htmlAndTextMultipart)
          ->html (content for htmlBodyPart)
    ->fileBodyPart1 (bodyPart2 for the mainMultipart)
      ->FileDataHandler (content for fileBodyPart1 )

And the code to build such a message:

    // the parent or main part if you will
    Multipart mainMultipart = new MimeMultipart("mixed");

    // this will hold text and html and tells the client there are 2 versions of the message (html and text). presumably text
    // being the alternative to html
    Multipart htmlAndTextMultipart = new MimeMultipart("alternative");

    // set text
    MimeBodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setText(text);
    htmlAndTextMultipart.addBodyPart(textBodyPart);

    // set html (set this last per rfc1341 which states last = best)
    MimeBodyPart htmlBodyPart = new MimeBodyPart();
    htmlBodyPart.setContent(html, "text/html; charset=utf-8");
    htmlAndTextMultipart.addBodyPart(htmlBodyPart);

    // stuff the multipart into a bodypart and add the bodyPart to the mainMultipart
    MimeBodyPart htmlAndTextBodyPart = new MimeBodyPart();
    htmlAndTextBodyPart.setContent(htmlAndTextMultipart);
    mainMultipart.addBodyPart(htmlAndTextBodyPart);

    // attach file body parts directly to the mainMultipart
    MimeBodyPart filePart = new MimeBodyPart();
    FileDataSource fds = new FileDataSource("/path/to/some/file.txt");
    filePart.setDataHandler(new DataHandler(fds));
    filePart.setFileName(fds.getName());
    mainMultipart.addBodyPart(filePart);

    // set message content
    message.setContent(mainMultipart);

set date in input type date

to me the shortest way to solve this problem is to use moment.js and solve this problem in just 2 lines.

var today = moment().format('YYYY-MM-DD');
$('#datePicker').val(today);

Getting output of system() calls in Ruby

puts `date`
puts $?


Mon Mar  7 19:01:15 PST 2016
pid 13093 exit 0

How do I count the number of rows and columns in a file using bash?

You can use bash. Note for very large files in terms of GB, use awk/wc. However it should still be manageable in performance for files with a few MB.

declare -i count=0
while read
do
    ((count++))
done < file    
echo "line count: $count"

Alternative to mysql_real_escape_string without connecting to DB

In direct opposition to my other answer, this following function is probably safe, even with multi-byte characters.

// replace any non-ascii character with its hex code.
function escape($value) {
    $return = '';
    for($i = 0; $i < strlen($value); ++$i) {
        $char = $value[$i];
        $ord = ord($char);
        if($char !== "'" && $char !== "\"" && $char !== '\\' && $ord >= 32 && $ord <= 126)
            $return .= $char;
        else
            $return .= '\\x' . dechex($ord);
    }
    return $return;
}

I'm hoping someone more knowledgeable than myself can tell me why the code above won't work ...

Spring Data JPA map the native query result to Non-Entity POJO

You can do something like

@NamedQuery(name="IssueDescriptor.findByIssueDescriptorId" ,

    query=" select new com.test.live.dto.IssuesDto (idc.id, dep.department, iss.issueName, 
               cat.issueCategory, idc.issueDescriptor, idc.description) 
            from Department dep 
            inner join dep.issues iss 
            inner join iss.category cat 
            inner join cat.issueDescriptor idc 
            where idc.id in(?1)")

And there must be Constructor like

public IssuesDto(long id, String department, String issueName, String issueCategory, String issueDescriptor,
            String description) {
        super();
        this.id = id;
        this.department = department;
        this.issueName = issueName;
        this.issueCategory = issueCategory;
        this.issueDescriptor = issueDescriptor;
        this.description = description;
    }

Comparing user-inputted characters in C

answer shouldn't be a pointer, the intent is obviously to hold a character. scanf takes the address of this character, so it should be called as

char answer;
scanf(" %c", &answer);

Next, your "or" statement is formed incorrectly.

if (answer == 'Y' || answer == 'y')

What you wrote originally asks to compare answer with the result of 'Y' || 'y', which I'm guessing isn't quite what you wanted to do.

Java double.MAX_VALUE?

Double.MAX_VALUE is the maximum value a double can represent (somewhere around 1.7*10^308).

This should end in some calculation problems, if you try to subtract the maximum possible value of a data type.

Even though when you are dealing with money you should never use floating point values especially while rounding this can cause problems (you will either have to much or less money in your system then).

How to create full compressed tar file using Python?

In this tar.gz file compress in open view directory In solve use os.path.basename(file_directory)

with tarfile.open("save.tar.gz","w:gz"):
      for file in ["a.txt","b.log","c.png"]:
           tar.add(os.path.basename(file))

its use in tar.gz file compress in directory

Create a directory if it does not exist and then create the files in that directory as well

code:

// Create Directory if not exist then Copy a file.


public static void copyFile_Directory(String origin, String destDir, String destination) throws IOException {

    Path FROM = Paths.get(origin);
    Path TO = Paths.get(destination);
    File directory = new File(String.valueOf(destDir));

    if (!directory.exists()) {
        directory.mkdir();
    }
        //overwrite the destination file if it exists, and copy
        // the file attributes, including the rwx permissions
     CopyOption[] options = new CopyOption[]{
                StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES

        };
        Files.copy(FROM, TO, options);


}

Converting string to tuple without splitting characters

Just in case someone comes here trying to know how to create a tuple assigning each part of the string "Quattro" and "TT" to an element of the list, it would be like this print tuple(a.split())

What are the use cases for selecting CHAR over VARCHAR in SQL?

There is some small processing overhead in calculating the actual needed size for a column value and allocating the space for a Varchar, so if you are definitely sure how long the value will always be, it is better to use Char and avoid the hit.

What do curly braces mean in Verilog?

As Matt said, the curly braces are for concatenation. The extra curly braces around 16{a[15]} are the replication operator. They are described in the IEEE Standard for Verilog document (Std 1364-2005), section "5.1.14 Concatenations".

{16{a[15]}}

is the same as

{ 
   a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15],
   a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15]
}

In bit-blasted form,

assign result = {{16{a[15]}}, {a[15:0]}};

is the same as:

assign result[ 0] = a[ 0];
assign result[ 1] = a[ 1];
assign result[ 2] = a[ 2];
assign result[ 3] = a[ 3];
assign result[ 4] = a[ 4];
assign result[ 5] = a[ 5];
assign result[ 6] = a[ 6];
assign result[ 7] = a[ 7];
assign result[ 8] = a[ 8];
assign result[ 9] = a[ 9];
assign result[10] = a[10];
assign result[11] = a[11];
assign result[12] = a[12];
assign result[13] = a[13];
assign result[14] = a[14];
assign result[15] = a[15];
assign result[16] = a[15];
assign result[17] = a[15];
assign result[18] = a[15];
assign result[19] = a[15];
assign result[20] = a[15];
assign result[21] = a[15];
assign result[22] = a[15];
assign result[23] = a[15];
assign result[24] = a[15];
assign result[25] = a[15];
assign result[26] = a[15];
assign result[27] = a[15];
assign result[28] = a[15];
assign result[29] = a[15];
assign result[30] = a[15];
assign result[31] = a[15];

Detect Close windows event by jQuery

There is no specific event for capturing browser close event. But we can detect by the browser positions XY.

<script type="text/javascript">
$(document).ready(function() {
  $(document).mousemove(function(e) {
    if(e.pageY <= 5)
    {
        //this condition would occur when the user brings their cursor on address bar 
        //do something here 
    }
  });
});
</script>

How to make connection to Postgres via Node.js

Connection String

The connection string is a string of the form:

postgres://[user[:password]@][host][:port][/dbname]

(where the parts in [...] can optionally be included or excluded)

Some examples of valid connection strings include:

postgres://localhost
postgres://localhost:5432
postgres://localhost/mydb
postgres://user@localhost
postgres://user:secret_password@localhost

If you've just started a database on your local machine, the connection string postgres://localhost will typically work, as that uses the default port number, username, and no password. If the database was started with a specific account, you might find you need to use postgres://pg@localhost or postgres://postgres@localhost

If none of these work, and you have installed docker, another option is to run npx @databases/pg-test start. This will start a postgres server in a docker container and then print out the connection string for you. The pg-test databases are only intended for testing though, so you will loose all your data if your computer restarts.

Connecting in node.js

You can connect to the database and issue queries using @databases/pg:

const createPool = require('@databases/pg');
const {sql} = require('@databases/pg');

// If you're using TypeScript or Babel, you can swap
// the two `require` calls for this import statement:

// import createPool, {sql} from '@databases/pg';

// create a "pool" of connections, you can think of this as a single
// connection, the pool is just used behind the scenes to improve
// performance
const db = createPool('postgres://localhost');

// wrap code in an `async` function so we can use `await`
async function run() {

  // we can run sql by tagging it as "sql" and then passing it to db.query
  await db.query(sql`
    CREATE TABLE IF NOT EXISTS beatles (
      name TEXT NOT NULL,
      height INT NOT NULL,
      birthday DATE NOT NULL
    );
  `);

  const beatle = {
    name: 'George',
    height: 70,
    birthday: new Date(1946, 02, 14),
  };

  // If we need to pass values, we can use ${...} and they will
  // be safely & securely escaped for us
  await db.query(sql`
    INSERT INTO beatles (name, height, birthday)
    VALUES (${beatle.name}, ${beatle.height}, ${beatle.birthday});
  `);

  console.log(
    await db.query(sql`SELECT * FROM beatles;`)
  );
}

run().catch(ex => {
  // It's a good idea to always report errors using
  // `console.error` and set the process.exitCode if
  // you're calling an async function at the top level
  console.error(ex);
  process.exitCode = 1;
}).then(() => {
  // For this little demonstration, we'll dispose of the
  // connection pool when we're done, so that the process
  // exists. If you're building a web server/backend API
  // you probably never need to call this.
  return db.dispose();
});

You can find a more complete guide to querying Postgres using node.js at https://www.atdatabases.org/docs/pg

How to parse a JSON object to a TypeScript Object

let employee = <Employee>JSON.parse(employeeString);

Remember: Strong typings is compile time only since javascript doesn't support it.

Ifelse statement in R with multiple conditions

another solution using dplyr is:

df <- ## your data ##
df <- df %>%
        mutate(Den = ifelse(any(is.na(Den)) | any(Den != 1), 0, 1))

Postgres integer arrays as parameters?

I realize this is an old question, but it took me several hours to find a good solution and thought I'd pass on what I learned here and save someone else the trouble. Try, for example,

SELECT * FROM some_table WHERE id_column = ANY(@id_list)

where @id_list is bound to an int[] parameter by way of

command.Parameters.Add("@id_list", NpgsqlDbType.Array | NpgsqlDbType.Integer).Value = my_id_list;

where command is a NpgsqlCommand (using C# and Npgsql in Visual Studio).

Ruby: How to convert a string to boolean

In rails, I've previously done something like this:

class ApplicationController < ActionController::Base
  # ...

  private def bool_from(value)
    !!ActiveRecord::Type::Boolean.new.type_cast_from_database(value)
  end
  helper_method :bool_from

  # ...
end

Which is nice if you're trying to match your boolean strings comparisons in the same manner as rails would for your database.

org.hibernate.MappingException: Could not determine type for: java.util.Set

I got the same problem with @ManyToOne column. It was solved... in stupid way. I had all other annotations for public getter methods, because they were overridden from parent class. But last field was annotated for private variable like in all other classes in my project. So I got the same MappingException without the reason.

Solution: I placed all annotations at public getter methods. I suppose, Hibernate can't handle cases, when annotations for private fields and public getters are mixed in one class.

Is there a good JavaScript minifier?

If you are using PHP you might also want to take a look at minify which can minify and combine JavaScript files. The integration is pretty easy and can be done by defined groups of files or an easy query string. Minified files are also cached to reduce the server load and you can add expire headers through minify.

How to get JSON objects value if its name contains dots?

Just to make use of updated solution try using lodash utility https://lodash.com/docs#get

Understanding React-Redux and mapStateToProps()

React-Redux connect is used to update store for every actions.

import { connect } from 'react-redux';

const AppContainer = connect(  
  mapStateToProps,
  mapDispatchToProps
)(App);

export default AppContainer;

It's very simply and clearly explained in this blog.

You can clone github project or copy paste the code from that blog to understand the Redux connect.

What's the -practical- difference between a Bare and non-Bare repository?

Non bare repository allows you to (into your working tree) capture changes by creating new commits.

Bare repositories are only changed by transporting changes from other repositories.

Is there any way to kill a Thread?

There is a library built for this purpose, stopit. Although some of the same cautions listed herein still apply, at least this library presents a regular, repeatable technique for achieving the stated goal.

Invoke-customs are only supported starting with android 0 --min-api 26

After hours of struggling, I solved it by including the following within app/build.gradle:

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

https://github.com/mapbox/mapbox-gl-native/issues/11378

Command to escape a string in bash

In Bash:

printf "%q" "hello\world" | someprog

for example:

printf "%q" "hello\world"
hello\\world

This could be used through variables too:

printf -v var "%q\n" "hello\world"
echo "$var"
hello\\world

Pass a datetime from javascript to c# (Controller)

var Ihours = Math.floor(TotMin / 60);          

var Iminutes = TotMin % 60; var TotalTime = Ihours+":"+Iminutes+':00';

   $.ajax({
            url: ../..,
            cache: false,
            type: "POST",                
            data: JSON.stringify({objRoot: TotalTime}) ,
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (response) {

            },
            error: function (er) {
                console.log(er);
            }
        });

Maven project version inheritance - do I have to specify the parent version?

As Yanflea mentioned, there is a way to go around this.

In Maven 3.5.0 you can use the following way of transferring the version down from the parent project:

Parent POM.xml

<project ...>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mydomain</groupId>
    <artifactId>myprojectparent</artifactId>
    <packaging>pom</packaging>
    <version>${myversion}</version>
    <name>MyProjectParent</name>

    <properties>
        <myversion>0.1-SNAPSHOT</myversion>
    </properties>

    <modules>
        <module>modulefolder</module>
    </modules>
    ...
</project>

Module POM.xml

<project ...>
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.mydomain</groupId>
        <artifactId>myprojectmodule</artifactId>
        <version>${myversion}</version> <!-- This still needs to be set, but you can use properties from parent -->
    </parent>

    <groupId>se.car_o_liner</groupId>
    <artifactId>vinno</artifactId>
    <packaging>war</packaging>
    <name>Vinno</name>
    <!-- Note that there's no version specified; it's inherited from parent -->
    ...
</project>

You are free to change myversion to whatever you want that isn't a reserved property.

Check if something is (not) in a list in Python

How do I check if something is (not) in a list in Python?

The cheapest and most readable solution is using the in operator (or in your specific case, not in). As mentioned in the documentation,

The operators in and not in test for membership. x in s evaluates to True if x is a member of s, and False otherwise. x not in s returns the negation of x in s.

Additionally,

The operator not in is defined to have the inverse true value of in.

y not in x is logically the same as not y in x.

Here are a few examples:

'a' in [1, 2, 3]
# False

'c' in ['a', 'b', 'c']
# True

'a' not in [1, 2, 3]
# True

'c' not in ['a', 'b', 'c']
# False

This also works with tuples, since tuples are hashable (as a consequence of the fact that they are also immutable):

(1, 2) in [(3, 4), (1, 2)]
#  True

If the object on the RHS defines a __contains__() method, in will internally call it, as noted in the last paragraph of the Comparisons section of the docs.

... in and not in, are supported by types that are iterable or implement the __contains__() method. For example, you could (but shouldn't) do this:

[3, 2, 1].__contains__(1)
# True

in short-circuits, so if your element is at the start of the list, in evaluates faster:

lst = list(range(10001))
%timeit 1 in lst
%timeit 10000 in lst  # Expected to take longer time.

68.9 ns ± 0.613 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
178 µs ± 5.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

If you want to do more than just check whether an item is in a list, there are options:

  • list.index can be used to retrieve the index of an item. If that element does not exist, a ValueError is raised.
  • list.count can be used if you want to count the occurrences.

The XY Problem: Have you considered sets?

Ask yourself these questions:

  • do you need to check whether an item is in a list more than once?
  • Is this check done inside a loop, or a function called repeatedly?
  • Are the items you're storing on your list hashable? IOW, can you call hash on them?

If you answered "yes" to these questions, you should be using a set instead. An in membership test on lists is O(n) time complexity. This means that python has to do a linear scan of your list, visiting each element and comparing it against the search item. If you're doing this repeatedly, or if the lists are large, this operation will incur an overhead.

set objects, on the other hand, hash their values for constant time membership check. The check is also done using in:

1 in {1, 2, 3} 
# True

'a' not in {'a', 'b', 'c'}
# False

(1, 2) in {('a', 'c'), (1, 2)}
# True

If you're unfortunate enough that the element you're searching/not searching for is at the end of your list, python will have scanned the list upto the end. This is evident from the timings below:

l = list(range(100001))
s = set(l)

%timeit 100000 in l
%timeit 100000 in s

2.58 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
101 ns ± 9.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

As a reminder, this is a suitable option as long as the elements you're storing and looking up are hashable. IOW, they would either have to be immutable types, or objects that implement __hash__.

Performance of FOR vs FOREACH in PHP

It's 2020 and stuffs had greatly evolved with php 7.4 and opcache.

Here is the OP^ benchmark, ran as unix CLI, without the echo and html parts.

Test ran locally on a regular computer.

php -v

PHP 7.4.6 (cli) (built: May 14 2020 10:02:44) ( NTS )

Modified benchmark script:

<?php 
 ## preperations; just a simple environment state

  $test_iterations = 100;
  $test_arr_size = 1000;

  // a shared function that makes use of the loop; this should
  // ensure no funny business is happening to fool the test
  function test($input)
  {
    //echo '<!-- '.trim($input).' -->';
  }

  // for each test we create a array this should avoid any of the
  // arrays internal representation or optimizations from getting
  // in the way.

  // normal array
  $test_arr1 = array();
  $test_arr2 = array();
  $test_arr3 = array();
  // hash tables
  $test_arr4 = array();
  $test_arr5 = array();

  for ($i = 0; $i < $test_arr_size; ++$i)
  {
    mt_srand();
    $hash = md5(mt_rand());
    $key = substr($hash, 0, 5).$i;

    $test_arr1[$i] = $test_arr2[$i] = $test_arr3[$i] = $test_arr4[$key] = $test_arr5[$key]
      = $hash;
  }

  ## foreach

  $start = microtime(true);
  for ($j = 0; $j < $test_iterations; ++$j)
  {
    foreach ($test_arr1 as $k => $v)
    {
      test($v);
    }
  }
  echo 'foreach '.(microtime(true) - $start)."\n";  

  ## foreach (using reference)

  $start = microtime(true);
  for ($j = 0; $j < $test_iterations; ++$j)
  {
    foreach ($test_arr2 as &$value)
    {
      test($value);
    }
  }
  echo 'foreach (using reference) '.(microtime(true) - $start)."\n";

  ## for

  $start = microtime(true);
  for ($j = 0; $j < $test_iterations; ++$j)
  {
    $size = count($test_arr3);
    for ($i = 0; $i < $size; ++$i)
    {
      test($test_arr3[$i]);
    }
  }
  echo 'for '.(microtime(true) - $start)."\n";  

  ## foreach (hash table)

  $start = microtime(true);
  for ($j = 0; $j < $test_iterations; ++$j)
  {
    foreach ($test_arr4 as $k => $v)
    {
      test($v);
    }
  }
  echo 'foreach (hash table) '.(microtime(true) - $start)."\n";

  ## for (hash table)

  $start = microtime(true);
  for ($j = 0; $j < $test_iterations; ++$j)
  {
    $keys = array_keys($test_arr5);
    $size = sizeOf($test_arr5);
    for ($i = 0; $i < $size; ++$i)
    {
      test($test_arr5[$keys[$i]]);
    }
  }
  echo 'for (hash table) '.(microtime(true) - $start)."\n";

Output:

foreach 0.0032877922058105
foreach (using reference) 0.0029420852661133
for 0.0025191307067871
foreach (hash table) 0.0035080909729004
for (hash table) 0.0061779022216797

As you can see the evolution is insane, about 560 time faster than reported in 2012.

On my machines and servers, following my numerous experiments, basics for loops are the fastest. This is even clearer using nested loops ($i $j $k..)

It is also the most flexible in usage, and has a better readability from my view.

Reset Windows Activation/Remove license key

  1. Open a command prompt as an Administrator.

  2. Enter slmgr /upk and wait for this to complete. This will uninstall the current product key from Windows and put it into an unlicensed state.

  3. Enter slmgr /cpky and wait for this to complete. This will remove the product key from the registry if it's still there.

  4. Enter slmgr /rearm and wait for this to complete. This is to reset the Windows activation timers so the new users will be prompted to activate Windows when they put in the key.

This should put the system back to a pre-key state.

Hope this helps you out!

how to make a countdown timer in java

You'll see people using the Timer class to do this. Unfortunately, it isn't always accurate. Your best bet is to get the system time when the user enters input, calculate a target system time, and check if the system time has exceeded the target system time. If it has, then break out of the loop.

java.io.InvalidClassException: local class incompatible:

Serialisation in java is not meant as long term persistence or transport format - it is too fragile for this. With the slightest difference in class bytecode and JVM, your data is not readable anymore. Use XML or JSON data-binding for your task (XStream is fast and easy to use, and there are a ton of alternatives)

How to load an ImageView by URL in Android?

Anyway people ask my comment to post it as answer. i am posting.

URL newurl = new URL(photo_url_str); 
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());
profile_photo.setImageBitmap(mIcon_val);

Best practice when adding whitespace in JSX

I have been trying to think of a good convention to use when placing text next to components on different lines, and found a couple good options:

<p>
    Hello {
        <span>World</span>
    }!
</p>

or

<p>
    Hello {}
    <span>World</span>
    {} again!
</p>

Each of these produces clean html without additional &nbsp; or other extraneous markup. It creates fewer text nodes than using {' '}, and allows using of html entities where {' hello &amp; goodbye '} does not.

when do you need .ascx files and how would you use them?

One more use of .ascx files is, they can be used for Partial Page caching in ASP.NET pages. What we have to do is to create an ascx file and then move the controls or portion of the page we need to cache into that control. Then add the @OutputCache directive in the ascx control and it will be cached separately from the parent page. It is used when you don't want to cache the whole page but only a specific portion of the page.

Convert XML String to Object

I know this question is old, but I stumbled into it and I have a different answer than, well, everyone else :-)

The usual way (as the commenters above mention) is to generate a class and de-serialize your xml.

But (warning: shameless self-promotion here) I just published a nuget package, here, with which you don't have to. You just go:

string xml = System.IO.File.ReadAllText(@"C:\test\books.xml");
var book = Dandraka.XmlUtilities.XmlSlurper.ParseText(xml);

That is literally it, nothing else needed. And, most importantly, if your xml changes, your object changes automagically as well.

If you prefer to download the dll directly, the github page is here.

error C2065: 'cout' : undeclared identifier

I have VS2010, Beta 1 and Beta 2 (one on my work machine and one at home), and I've used std plenty without issues. Try typing:

std::

And see if Intellisense gives you anything. If it gives you the usual stuff (abort, abs, acos, etc.), except for cout, well then, that is quite a puzzler. Definitely look into your C++ headers in that case.

Beyond that, I would just add to make sure you're running a regular, empty project (not CLR, where Intellisense is crippled), and that you've actually attempted to build the project at least once. As I mentioned in a comment, VS2010 parses files once you've added an include; it could be that something stuck the parser and it didn't "find" cout right away. (In which case, try restarting VS maybe?)

eloquent laravel: How to get a row count from a ->get()

Its better to access the count with the laravels count method

$count = Model::where('status','=','1')->count();

or

$count = Model::count();

SQL Not Like Statement not working

Is the value of your particular COMMENT column null?

Sometimes NOT LIKE doesn't know how to behave properly around nulls.

Vue.js unknown custom element

You forgot about the components section in your Vue initialization. So Vue actually doesn't know about your component.

Change it to:

var myTask = Vue.component('my-task', {
 template: '#task-template',
 data: function() {
  return this.tasks; //Notice: in components data should return an object. For example "return { someProp: 1 }"
 },
 props: ['task']
});

new Vue({
 el: '#app',
 data: {
  tasks: [{
    name: "task 1",
    completed: false
   },
   {
    name: "task 2",
    completed: false
   },
   {
    name: "task 3",
    completed: true
   }
  ]
 },
 components: {
  myTask: myTask
 },
 methods: {

 },
 computed: {

 },
 ready: function() {

 }

});

And here is jsBin, where all seems to works correctly: http://jsbin.com/lahawepube/edit?html,js,output

UPDATE

Sometimes you want your components to be globally visible to other components.

In this case you need to register your components in this way, before your Vue initialization or export (in case if you want to register component from the other component)

Vue.component('exampleComponent', require('./components/ExampleComponent.vue')); //component name should be in camel-case

After you can add your component inside your vue el:

<example-component></example-component>

Display string multiple times

The accepted answer is short and sweet, but here is an alternate syntax allowing to provide a separator in Python 3.x.

print(*3*('-',), sep='_')

How to run a jar file in a linux commandline

For example to execute from terminal (Ubuntu Linux) or even (Windows console) a java file called filex.jar use this command:

java -jar filex.jar

The file will execute in terminal.

Launch Pycharm from command line (terminal)

Steps for someone using zsh on Mac:

  1. emacs ~/.zshrc&
  2. Put this in zshrc---> alias pycharm="/Applications/PyCharm\CE.app/Contents/MacOS/pycharm"
  3. source ~/.zshrc
  4. Launch by typing pycharm in command window

Find what 2 numbers add to something and multiply to something

That's basically a set of 2 simultaneous equations:

x*y = a
X+y = b

(using the mathematical convention of x and y for the variables to solve and a and b for arbitrary constants).

But the solution involves a quadratic equation (because of the x*y), so depending on the actual values of a and b, there may not be a solution, or there may be multiple solutions.

How to do parallel programming in Python?

You can use the multiprocessing module. For this case I might use a processing pool:

from multiprocessing import Pool
pool = Pool()
result1 = pool.apply_async(solve1, [A])    # evaluate "solve1(A)" asynchronously
result2 = pool.apply_async(solve2, [B])    # evaluate "solve2(B)" asynchronously
answer1 = result1.get(timeout=10)
answer2 = result2.get(timeout=10)

This will spawn processes that can do generic work for you. Since we did not pass processes, it will spawn one process for each CPU core on your machine. Each CPU core can execute one process simultaneously.

If you want to map a list to a single function you would do this:

args = [A, B]
results = pool.map(solve1, args)

Don't use threads because the GIL locks any operations on python objects.

How to wait in a batch script?

You can ping an address that doesn't exist and specify the desired timeout:

ping 192.0.2.2 -n 1 -w 10000 > nul

And since the address does not exist, it'll wait 10,000 ms (10 seconds) and return.

  • The -w 10000 part specifies the desired timeout in milliseconds.
  • The -n 1 part tells ping that it should only try once (normally it'd try 4 times).
  • The > nul part is appended so the ping command doesn't output anything to screen.

You can easily make a sleep command yourself by creating a sleep.bat somewhere in your PATH and using the above technique:

rem SLEEP.BAT - sleeps by the supplied number of seconds

@ping 192.0.2.2 -n 1 -w %1000 > nul

NOTE (September 2002): The 192.0.2.x address is reserved as per RFC 3330 so it definitely will not exist in the real world. Quoting from the spec:

192.0.2.0/24 - This block is assigned as "TEST-NET" for use in documentation and example code. It is often used in conjunction with domain names example.com or example.net in vendor and protocol documentation. Addresses within this block should not appear on the public Internet.

What is the "realm" in basic authentication

A realm can be seen as an area (not a particular page, it could be a group of pages) for which the credentials are used; this is also the string that will be shown when the browser pops up the login window, e.g.

Please enter your username and password for <realm name>:

When the realm changes, the browser may show another popup window if it doesn't have credentials for that particular realm.

Why use 'git rm' to remove a file instead of 'rm'?

When using git rm, the removal will part of your next commit. So if you want to push the change you should use git rm

How can I use threading in Python?

import threading
import requests

def send():

  r = requests.get('https://www.stackoverlow.com')

thread = []
t = threading.Thread(target=send())
thread.append(t)
t.start()

How to import and use image in a Vue single file component?

These both work for me in JavaScript and TypeScript

<img src="@/assets/images/logo.png" alt=""> 

or

 <img src="./assets/images/logo.png" alt="">

Using Alert in Response.Write Function in ASP.NET

string str = "Error mEssage";
Response.Write("<script language=javascript>alert('"+str+"');</script>");

How to store JSON object in SQLite database

An alternative could be to use the new JSON extension for SQLite. I've only just come across this myself: https://www.sqlite.org/json1.html This would allow you to perform a certain level of querying the stored JSON. If you used VARCHAR or TEXT to store a JSON string you would have no ability to query it. This is a great article showing its usage (in python) http://charlesleifer.com/blog/using-the-sqlite-json1-and-fts5-extensions-with-python/

NPM Install Error:Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0'

I solve that with

First delete package-lock.json

npm cache clean --force

then update npm

npm i npm@latest -g

then use npm install command

npm install 

How to use if-else option in JSTL

This is good and efficient approach as per time complexity prospect. Once it will get a true condition , it will not check any other after this. In multiple If , it will check each and condition.

   <c:choose>
      <c:when test="${condtion1}">
        do something condtion1
      </c:when>
      <c:when test="${condtion2}">
        do something condtion2
      </c:when>
      ......
      ......
      ...... 
      .......

      <c:when test="${condtionN}">
        do something condtionn N
      </c:when>


      <c:otherwise>
        do this w
      </c:otherwise>
    </c:choose>

Converting BigDecimal to Integer

You would call myBigDecimal.intValueExact() (or just intValue()) and it will even throw an exception if you would lose information. That returns an int but autoboxing takes care of that.

Replace a character at a specific index in a string?

String is an immutable class in java. Any method which seems to modify it always returns a new string object with modification.

If you want to manipulate a string, consider StringBuilder or StringBuffer in case you require thread safety.

How to disable XDebug

Apache/2.4.33 (Win64) PHP/7.2.4 myHomeBrew stack

At end of php.ini I use the following to manage Xdebug for use with PhpStorm

; jch ~ Sweet analizer at https://xdebug.org/wizard.php for matching xdebug to php version.
; jch ~ When upgrading php versions check if newer xdebug.dll is needed in ext directory.
; jch Renamed... zend_extension = E:\x64Stack\PHP\php7.2.4\ext\php_xdebug-2.6.0-7.2-vc15-x86_64.dll

zend_extension = E:\x64Stack\PHP\php7.2.4\ext\php_xdebug.dll

; jch !!!! Added the following for Xdebug with PhpStorm

[Xdebug]
; zend_extension=<full_path_to_xdebug_extension>
; xdebug.remote_host=<the host where PhpStorm is running (e.g. localhost)>
; xdebug.remote_port=<the port to which Xdebug tries to connect on the host where PhpStorm is running (default 9000)>

xdebug.remote_enable=1
xdebug.remote_host=localhost
xdebug.remote_port=9000

xdebug.profiler_enable=1
xdebug.profiler_output_dir="E:\x64Stack\Xdebug_profiler_output"
xdebug.idekey=PHPSTORM
xdebug.remote_autostart=1

; jch ~~~~~~~~~To turn Xdebug off(disable) uncomment the following 3 lines restart Apache~~~~~~~~~ 
;xdebug.remote_autostart=0  
;xdebug.remote_enable=0
;xdebug.profiler_enable=0

; !!! Might get a little more speed by also commenting out this line above... 
;;; zend_extension = E:\x64Stack\PHP\php7.2.4\ext\php_xdebug.dll
; so that Xdebug is both disabled AND not loaded

Flutter plugin not installed error;. When running flutter doctor

Safe fix for Mac (Android studio 4.1+) It is in a different directory now, but symlink helps.

Just run in the Terminal this command

ln -s ~/Library/Application\ Support/Google/AndroidStudio4.1/plugins ~/Library/Application\ Support/AndroidStudio4.1

If you have a different Android Studio version or an installation folder adjust the command accordingly.

Android/Java - Date Difference in days

One another way:

public static int numberOfDaysBetweenDates(Calendar fromDay, Calendar toDay) {
        fromDay = calendarStartOfDay(fromDay);
        toDay = calendarStartOfDay(toDay);
        long from = fromDay.getTimeInMillis();
        long to = toDay.getTimeInMillis();
        return (int) TimeUnit.MILLISECONDS.toDays(to - from);
    }

How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?

Add android:noHistory="true" in manifest file .

<manifest >
        <activity
            android:name="UI"
            android:noHistory="true"/>

</manifest>

Where to find free public Web Services?

Here you can find some public REST services for encryption and security related things: http://security.jelastic.servint.net

Logical operator in a handlebars.js {{#if}} conditional

Correct Solution for AND/OR

Handlebars.registerHelper('and', function () {
    // Get function args and remove last one (function name)
    return Array.prototype.slice.call(arguments, 0, arguments.length - 1).every(Boolean);
});
Handlebars.registerHelper('or', function () {
    // Get function args and remove last one (function name)
    return Array.prototype.slice.call(arguments, 0, arguments.length - 1).some(Boolean);
}); 

Then call as follows

{{#if (or (eq questionType 'STARTTIME') (eq questionType 'ENDTIME') (..) ) }}

BTW: Note that the solution given here is incorrect, he's not subtracting the last argument which is the function name. https://stackoverflow.com/a/31632215/1005607

His original AND/OR was based on the full list of arguments

   and: function () {
        return Array.prototype.slice.call(arguments).every(Boolean);
    },
    or: function () {
        return Array.prototype.slice.call(arguments).some(Boolean);
    }

Can someone change that answer? I just wasted an hour trying to fix something in an answer recommended by 86 people. The fix is to filter out the last argument which is the function name. Array.prototype.slice.call(arguments, 0, arguments.length - 1)

Checking for multiple conditions using "when" on single task in ansible

Also you can use default() filter. Or just a shortcut d()

- name: Generating a new SSH key for the current user it's not exists already
  local_action:
    module: user
    name: "{{ login_user.stdout }}"
    generate_ssh_key: yes 
    ssh_key_bits: 2048
  when: 
    - sshkey_result.rc == 1
    - github_username | d('none') | lower == 'none'

How to compare type of an object in Python?

i think this should do it

if isinstance(obj, str)

Convert ascii char[] to hexadecimal char[] in C

void atoh(char *ascii_ptr, char *hex_ptr,int len)
{
    int i;

    for(i = 0; i < (len / 2); i++)
    {

        *(hex_ptr+i)   = (*(ascii_ptr+(2*i)) <= '9') ? ((*(ascii_ptr+(2*i)) - '0') * 16 ) :  (((*(ascii_ptr+(2*i)) - 'A') + 10) << 4);
        *(hex_ptr+i)  |= (*(ascii_ptr+(2*i)+1) <= '9') ? (*(ascii_ptr+(2*i)+1) - '0') :  (*(ascii_ptr+(2*i)+1) - 'A' + 10);

    }


}

Java file path in Linux

Looks like you are missing a leading slash. Perhaps try:

Scanner s = new Scanner(new File("/home/me/java/ex.txt"));

(as to where it looks for files by default, it is where the JVM is run from for relative paths like the one you have in your question)

Passing functions with arguments to another function in Python?

You can use the partial function from functools like so.

from functools import partial

def perform(f):
    f()

perform(Action1)
perform(partial(Action2, p))
perform(partial(Action3, p, r))

Also works with keywords

perform(partial(Action4, param1=p))

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

  • The ownership of the relation is determined by where you place the 'mappedBy' attribute to the annotation. The entity you put 'mappedBy' is the one which is NOT the owner. There's no chance for both sides to be owners. If you don't have a 'delete user' use-case you could simply move the ownership to the Group entity, as currently the User is the owner.
  • On the other hand, you haven't been asking about it, but one thing worth to know. The groups and users are not combined with each other. I mean, after deleting User1 instance from Group1.users, the User1.groups collections is not changed automatically (which is quite surprising for me),
  • All in all, I would suggest you decide who is the owner. Let say the User is the owner. Then when deleting a user the relation user-group will be updated automatically. But when deleting a group you have to take care of deleting the relation yourself like this:

entityManager.remove(group)
for (User user : group.users) {
     user.groups.remove(group);
}
...
// then merge() and flush()

"&" meaning after variable type

The & means that the function accepts the address (or reference) to a variable, instead of the value of the variable.

For example, note the difference between this:

void af(int& g)
{
    g++;
    cout<<g;
}

int main()
{
    int g = 123;
    cout << g;
    af(g);
    cout << g;
    return 0;
}

And this (without the &):

void af(int g)
{
    g++;
    cout<<g;
}

int main()
{
    int g = 123;
    cout << g;
    af(g);
    cout << g;
    return 0;
}

JavaScript associative array to JSON

There are no associative arrays in JavaScript. However, there are objects with named properties, so just don't initialise your "array" with new Array, then it becomes a generic object.

Use of 'prototype' vs. 'this' in JavaScript?

The first example changes the interface for that object only. The second example changes the interface for all object of that class.

"Continue" (to next iteration) on VBScript

One option would be to put all the code in the loop inside a Sub and then just return from that Sub when you want to "continue".

Not perfect, but I think it would be less confusing that the extra loop.

Swift error : signal SIGABRT how to solve it

You get a SIGABRT error whenever you have a disconnected outlet. Click on your view controller in the storyboard and go to connections in the side panel (the arrow symbol). See if you have an extra outlet there, a duplicate, or an extra one that's not connected. If it's not that then maybe you haven't connected your outlets to your code correctly.

Just remember that SIGABRT happens when you are trying to call an outlet (button, view, textfield, etc) that isn't there.

How to detect if JavaScript is disabled?

code inside <noscript> tags will be executed when there is no js enabled in browser. we can use noscript tags to display msg to turn on JS as below.<noscript> <h1 style="text-align: center;">enable java script and reload the page</h1> </noscript> while keeping our website content inside body as hidden. as below

<body>
<div id="main_body" style="display: none;">
website content.
</div>
</body>

now if JS is turned on you can just make the content inside your main_body visible as below

<script type="text/javascript">
document.getElementById("main_body").style.display="block";
</script>

PHP Warning: PHP Startup: ????????: Unable to initialize module

In my case, with Windows Server 2008, I had to change the PATH variable. The former version of PHP (VC9) was inside it.

I have changed it with the newer version of PHP (VC11).

After a restart of Apache, it was okay.

Where to find extensions installed folder for Google Chrome on Mac?

The default locations of Chrome's profile directory are defined at http://www.chromium.org/user-experience/user-data-directory. For Chrome on Mac, it's

~/Library/Application\ Support/Google/Chrome/Default

The actual location can be different, by setting the --user-data-dir=path/to/directory flag.
If only one user is registered in Chrome, look in the Default/Extensions subdirectory. Otherwise, look in the <profile user name>/Extensions directory.

If that didn't help, you can always do a custom search.

  1. Go to chrome://extensions/, and find out the ID of an extension (32 lowercase letters) (if not done already, activate "Developer mode" first).

  2. Open the terminal, cd to the directory which is most likely a parent of your Chrome profile (if unsure, try ~ then /).

  3. Run find . -type d -iname "<EXTENSION ID HERE>", for example:

    find . -type d -iname jifpbeccnghkjeaalbbjmodiffmgedin
    

    Result:

    ./Library/Application Support/Google/Chrome/Default/Extensions/jifpbeccnghkjeaalbbjmodiffmgedin

Make HTML5 video poster be same size as video itself

Or you can use simply preload="none" attribute to make VIDEO background visible. And you can use background-size: cover; here.

 video {
   background: transparent url('video-image.jpg') 50% 50% / cover no-repeat ;
 }

 <video preload="none" controls>
   <source src="movie.mp4" type="video/mp4">
   <source src="movie.ogg" type="video/ogg">
 </video>

Node.js check if file exists

After a bit of experimentation, I found the following example using fs.stat to be a good way to asynchronously check whether a file exists. It also checks that your "file" is "really-is-a-file" (and not a directory).

This method uses Promises, assuming that you are working with an asynchronous codebase:

const fileExists = path => {
  return new Promise((resolve, reject) => {
    try {
      fs.stat(path, (error, file) => {
        if (!error && file.isFile()) {
          return resolve(true);
        }

        if (error && error.code === 'ENOENT') {
          return resolve(false);
        }
      });
    } catch (err) {
      reject(err);
    }
  });
};

If the file does not exist, the promise still resolves, albeit false. If the file does exist, and it is a directory, then is resolves true. Any errors attempting to read the file will reject the promise the error itself.

How to display an image stored as byte array in HTML/JavaScript?

Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions:

How to make my font bold using css?

You can use the CSS declaration font-weight: bold;.

I would advise you to read the CSS beginner guide at http://htmldog.com/guides/cssbeginner/ .

Sending and receiving UDP packets?

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

"Proxy server connection failed" in google chrome

  1. Open Google Chrome.
  2. Click Menu on the upper right side. Beside the STAR symbol (Bookmark).
  3. Click Show Advanced Settings.
  4. Scroll down and find Network.
  5. Click Change proxy settings.
  6. On the Connections tab, click LAN settings.
  7. Uncheck "Use a proxy server for your LAN."
  8. Then click OK.

Hope it helps .

MySQL: Insert record if not exists in table

MySQL provides a very cute solution :

REPLACE INTO `table` VALUES (5, 'John', 'Doe', SHA1('password'));

Very easy to use since you have declared a unique primary key (here with value 5).

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

You can't do it with just CSS, but you can do it with Javascript, and (optionally) jQuery.

If you want to do it without jQuery:

<script>
    window.onload = function() {
        var anchors = document.getElementsByTagName('a');
        for(var i = 0; i < anchors.length; i++) {
            var anchor = anchors[i];
            anchor.onclick = function() {
                alert('ho ho ho');
            }
        }
    }
</script>

And to do it without jQuery, and only on a specific class (ex: hohoho):

<script>
    window.onload = function() {
        var anchors = document.getElementsByTagName('a');
        for(var i = 0; i < anchors.length; i++) {
            var anchor = anchors[i];
            if(/\bhohoho\b/).match(anchor.className)) {
                anchor.onclick = function() {
                    alert('ho ho ho');
                }
            }
        }
    }
</script>

If you are okay with using jQuery, then you can do this for all anchors:

<script>
    $(document).ready(function() {
        $('a').click(function() {
            alert('ho ho ho');
        });
    });
</script>

And this jQuery snippet to only apply it to anchors with a specific class:

<script>
    $(document).ready(function() {
        $('a.hohoho').click(function() {
            alert('ho ho ho');
        });
    });
</script>

Is there "\n" equivalent in VBscript?

As David and Remou pointed out, vbCrLf if you want a carriage-return-linefeed combination. Otherwise, Chr(13) and Chr(10) (although some VB-derivatives have vbCr and vbLf; VBScript may well have those, worth checking before using Chr).

What is the fastest way to create a checksum for large files in C#

You can have a look to XxHash.Net ( https://github.com/wilhelmliao/xxHash.NET )
The xxHash algorythm seems to be faster than all other.
Some benchmark on the xxHash site : https://github.com/Cyan4973/xxHash

PS: I've not yet used it.

Convert datetime value into string

Try this:

concat(left(datefield,10),left(timefield,8))
  • 10 char on date field based on full date yyyy-MM-dd.

  • 8 char on time field based on full time hh:mm:ss.

It depends on the format you want it. normally you can use script above and you can concat another field or string as you want it.

Because actually date and time field tread as string if you read it. But of course you will got error while update or insert it.

What is the difference between user and kernel modes in operating systems?

I'm going to take a stab in the dark and guess you're talking about Windows. In a nutshell, kernel mode has full access to hardware, but user mode doesn't. For instance, many if not most device drivers are written in kernel mode because they need to control finer details of their hardware.

See also this wikibook.

How to override equals method in Java

@Override
public boolean equals(Object that){
  if(this == that) return true;//if both of them points the same address in memory

  if(!(that instanceof People)) return false; // if "that" is not a People or a childclass

  People thatPeople = (People)that; // than we can cast it to People safely

  return this.name.equals(thatPeople.name) && this.age == thatPeople.age;// if they have the same name and same age, then the 2 objects are equal unless they're pointing to different memory adresses
}

Is there a simple way to remove multiple spaces in a string?

To remove white space, considering leading, trailing and extra white space in between words, use:

(?<=\s) +|^ +(?=\s)| (?= +[\n\0])

The first or deals with leading white space, the second or deals with start of string leading white space, and the last one deals with trailing white space.

For proof of use, this link will provide you with a test.

https://regex101.com/r/meBYli/4

This is to be used with the re.split function.

Tomcat request timeout

This article talks about setting the timeouts on the server level. http://www.coderanch.com/t/364207/Servlets/java/Servlet-Timeout-two-ways

What is causing the application to go into infinite loop? If you are opening connections to other resources, you might want to put timeouts on those connections and sending appropriate response when those time out occurs.

Error in finding last used cell in Excel with VBA

sub last_filled_cell()
msgbox range("A65536").end(xlup).row
end sub

Here, A65536 is the last cell in the Column A this code was tested on excel 2003.

getting error while updating Composer

This works for me with php 7.2

sudo apt-get install php7.2-xml

Check the current number of connections to MongoDb

Alternatively you can check connection status by logging into Mongo Atlas and then navigating to your cluster.

enter image description here

Inline JavaScript onclick function

you can use Self-Executing Anonymous Functions. this code will work:

<a href="#" onClick="(function(){
    alert('Hey i am calling');
    return false;
})();return false;">click here</a>

see JSfiddle

Convert .pem to .crt and .key

If you asked this question because you're using mkcert then the trick is that the .pem file is the cert and the -key.pem file is the key.

(You don't need to convert, just run mkcert yourdomain.dev otherdomain.dev )

Get webpage contents with Python?

If you ask me. try this one

import urllib2
resp = urllib2.urlopen('http://hiscore.runescape.com/index_lite.ws?player=zezima')

and read the normal way ie

page = resp.read()

Good luck though

How do I set an ASP.NET Label text from code behind on page load?

If you are just placing the code on the page, usually the code behind will get an auto generated field you to use like @Oded has shown.

In other cases, you can always use this code:

Label myLabel = this.FindControl("myLabel") as Label; // this is your Page class

if(myLabel != null)
   myLabel.Text = "SomeText";

Using GSON to parse a JSON array

Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);

HTML5 Local storage vs. Session storage

performance wise, my (crude) measurements found no difference on 1000 writes and reads

security wise, intuitively it would seem the localStore might be shut down before the sessionStore, but have no concrete evidence - maybe someone else does?

functional wise, concur with digitalFresh above

Rails: FATAL - Peer authentication failed for user (PG::Error)

Adding host: localhost was the magic for me

development:
  adapter: postgresql
  database: database_name_here
  host: localhost
  username: user_name_here

ASP.NET Core configuration for .NET Core console application

For a .NET Core 2.0 console app, I did the following:

  1. Create a new file named appsettings.json at the root of the project (the file name can be anything)
  2. Add my specific settings to that file as json. For example:
{
  "myKey1" :  "my test value 1", 
  "myKey2" :  "my test value 2", 
  "foo" :  "bar" 
}
  1. Configure to copy the file to the output directory whenever the project is built (in VS -> Solution Explorer -> right-click file -> select 'Properties' -> Advanced -> Copy to Output Directory -> select 'Copy Always')

  2. Install the following nuget package in my project:

    • Microsoft.Extensions.Configuration.Json
  3. Add the following to Program.cs (or wherever Main() is located):

    static void Main(string[] args)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json");
    
        var configuration = builder.Build();
    
        // rest of code...
    }
    
  4. Then read the values using either of the following ways:

    string myKey1 = configuration["myKey1"];
    Console.WriteLine(myKey1);
    
    string foo = configuration.GetSection("foo").Value;
    Console.WriteLine(foo);
    

More info: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration?tabs=basicconfiguration#simple-configuration

The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication

For me it was a load balancer/url issue. A web service behind a load balancer called another service behind the same load balancer using the full url like: loadbalancer.mycompany.com. I changed it to bypass the load balancer when calling the second service by using localhost.mycompany.com instead.

I think there was some kind of circular reference issue going on with the load balancer.

What are the differences in die() and exit() in PHP?

Here is something that's pretty interesting. Although exit() and die() are equivalent, die() closes the connection. exit() doesn't close the connection.

die():

<?php
    header('HTTP/1.1 304 Not Modified');
    die();
?>

exit():

<?php
    header('HTTP/1.1 304 Not Modified');
    exit();
?>

Results:

exit():

HTTP/1.1 304 Not Modified 
Connection: Keep-Alive 
Keep-Alive: timeout=5, max=100

die():

HTTP/1.1 304 Not Modified 
Connection: close

Just incase in need to take this into account for your project.

Credits: https://stackoverflow.com/a/20932511/4357238

data type not understood

Try:

mmatrix = np.zeros((nrows, ncols))

Since the shape parameter has to be an int or sequence of ints

http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html

Otherwise you are passing ncols to np.zeros as the dtype.

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

why not try opening your file as text?

with open(fname, 'rt') as f:
    lines = [x.strip() for x in f.readlines()]

Additionally here is a link for python 3.x on the official page: https://docs.python.org/3/library/io.html And this is the open function: https://docs.python.org/3/library/functions.html#open

If you are really trying to handle it as a binary then consider encoding your string.

Get the full URL in PHP

$page_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

For more: How to get the full URL of a page using PHP

Set the layout weight of a TextView programmatically

There is another way to do this. In case you need to set only one parameter, for example 'height':

TextView textView = (TextView)findViewById(R.id.text_view);
ViewGroup.LayoutParams params = textView.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.setLayoutParams(params);

Laravel back button

In Laravel, you can do something like this: <a href="{{ Request::referrer() }}">Back</a> (assuming you're using Blade).

Laravel 4

{{ URL::previous() }}

Laravel 5+

{{ url()->previous() }}

Laravel documentation

Assign output of a program to a variable using a MS batch file

In addition to the answer, you can't directly use output redirection operators in the set part of for loop (e.g. if you wanna hide stderror output from a user and provide a nicer error message). Instead, you have to escape them with a caret character (^):

for /f %%O in ('some-erroring-command 2^> nul') do (echo %%O)

Reference: Redirect output of command in for loop of batch script

How to validate domain name in PHP?

If you don't want to use regular expressions, you can try this:

$str = 'domain-name';

if (ctype_alnum(str_replace('-', '', $str)) && $str[0] != '-' && $str[strlen($str) - 1] != '-') {
    echo "Valid domain\n";
} else {
    echo "Invalid domain\n";
}

but as said regexp are the best tool for this.

gitignore all files of extension in directory

UPDATE: Take a look at @Joey's answer: Git now supports the ** syntax in patterns. Both approaches should work fine.


The gitignore(5) man page states:

Patterns read from a .gitignore file in the same directory as the path, or in any parent directory, with patterns in the higher level files (up to the toplevel of the work tree) being overridden by those in lower level files down to the directory containing the file.

What this means is that the patterns in a .gitignore file in any given directory of your repo will affect that directory and all subdirectories.

The pattern you provided

/public/static/**/*.js

isn't quite right, firstly because (as you correctly noted) the ** syntax is not used by Git. Also, the leading / anchors that pattern to the start of the pathname. (So, /public/static/*.js will match /public/static/foo.js but not /public/static/foo/bar.js.) Removing the leading / won't work either, matching paths like public/static/foo.js and foo/public/static/bar.js. EDIT: Just removing the leading slash won't work either — because the pattern still contains a slash, it is treated by Git as a plain, non-recursive shell glob (thanks @Joey Hoer for pointing this out).

As @ptyx suggested, what you need to do is create the file <repo>/public/static/.gitignore and include just this pattern:

*.js

There is no leading /, so it will match at any part of the path, and that pattern will only ever be applied to files in the /public/static directory and its subdirectories.

No Activity found to handle Intent : android.intent.action.VIEW

If you don't pass the correct web URL and don't have a browser, ActivityNotFoundException occurs, so check those requirements or handle the exception explicitly. That can resolve your problem.

public static void openWebPage(Context context, String url) {
    try {
        if (!URLUtil.isValidUrl(url)) {
            Toast.makeText(context, " This is not a valid link", Toast.LENGTH_LONG).show();   
        } else {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            context.startActivity(intent);
        }
    } catch (ActivityNotFoundException e) {
        Toast.makeText(context, " You don't have any browser to open web page", Toast.LENGTH_LONG).show();
    }
}

How do I test if a recordSet is empty? isNull?

I would check the "End of File" flag:

If temp_rst1.EOF Or temp_rst2.EOF Then MsgBox "null"

Apache is "Unable to initialize module" because of module's and PHP's API don't match after changing the PHP configuration

What worked for me was simply to do the following:

open the php.ini file.

Under the DYNAMIC EXTENSIONS heading, comment out the following line as

;extension=php_java.dll

Restarted Apache and all was fine

What is the Ruby <=> (spaceship) operator?

Since this operator reduces comparisons to an integer expression, it provides the most general purpose way to sort ascending or descending based on multiple columns/attributes.

For example, if I have an array of objects I can do things like this:

# `sort!` modifies array in place, avoids duplicating if it's large...

# Sort by zip code, ascending
my_objects.sort! { |a, b| a.zip <=> b.zip }

# Sort by zip code, descending
my_objects.sort! { |a, b| b.zip <=> a.zip }
# ...same as...
my_objects.sort! { |a, b| -1 * (a.zip <=> b.zip) }

# Sort by last name, then first
my_objects.sort! { |a, b| 2 * (a.last <=> b.last) + (a.first <=> b.first) }

# Sort by zip, then age descending, then last name, then first
# [Notice powers of 2 make it work for > 2 columns.]
my_objects.sort! do |a, b|
      8 * (a.zip   <=> b.zip) +
     -4 * (a.age   <=> b.age) +
      2 * (a.last  <=> b.last) +
          (a.first <=> b.first)
end

This basic pattern can be generalized to sort by any number of columns, in any permutation of ascending/descending on each.

Detecting the character encoding of an HTTP POST request

the default encoding of a HTTP POST is ISO-8859-1.

else you have to look at the Content-Type header that will then look like

Content-Type: application/x-www-form-urlencoded ; charset=UTF-8

You can maybe declare your form with

<form enctype="application/x-www-form-urlencoded;charset=UTF-8">

or

<form accept-charset="UTF-8">

to force the encoding.

Some references :

http://www.htmlhelp.com/reference/html40/forms/form.html

http://www.w3schools.com/tags/tag_form.asp

How do I undo 'git add' before commit?

Run

git gui

and remove all the files manually or by selecting all of them and clicking on the unstage from commit button.

Apache POI error loading XSSFWorkbook class

Add commons-collections4-x.x.jar file in your build path and try it again. It will work.

You can download it from https://mvnrepository.com/artifact/org.apache.commons/commons-collections4/4.0

Sorting a Python list by two fields

Python has a stable sort, so provided that performance isn't an issue the simplest way is to sort it by field 2 and then sort it again by field 1.

That will give you the result you want, the only catch is that if it is a big list (or you want to sort it often) calling sort twice might be an unacceptable overhead.

list1 = sorted(csv1, key=operator.itemgetter(2))
list1 = sorted(list1, key=operator.itemgetter(1))

Doing it this way also makes it easy to handle the situation where you want some of the columns reverse sorted, just include the 'reverse=True' parameter when necessary.

Otherwise you can pass multiple parameters to itemgetter or manually build a tuple. That is probably going to be faster, but has the problem that it doesn't generalise well if some of the columns want to be reverse sorted (numeric columns can still be reversed by negating them but that stops the sort being stable).

So if you don't need any columns reverse sorted, go for multiple arguments to itemgetter, if you might, and the columns aren't numeric or you want to keep the sort stable go for multiple consecutive sorts.

Edit: For the commenters who have problems understanding how this answers the original question, here is an example that shows exactly how the stable nature of the sorting ensures we can do separate sorts on each key and end up with data sorted on multiple criteria:

DATA = [
    ('Jones', 'Jane', 58),
    ('Smith', 'Anne', 30),
    ('Jones', 'Fred', 30),
    ('Smith', 'John', 60),
    ('Smith', 'Fred', 30),
    ('Jones', 'Anne', 30),
    ('Smith', 'Jane', 58),
    ('Smith', 'Twin2', 3),
    ('Jones', 'John', 60),
    ('Smith', 'Twin1', 3),
    ('Jones', 'Twin1', 3),
    ('Jones', 'Twin2', 3)
]

# Sort by Surname, Age DESCENDING, Firstname
print("Initial data in random order")
for d in DATA:
    print("{:10s} {:10s} {}".format(*d))

print('''
First we sort by first name, after this pass all
Twin1 come before Twin2 and Anne comes before Fred''')
DATA.sort(key=lambda row: row[1])

for d in DATA:
    print("{:10s} {:10s} {}".format(*d))

print('''
Second pass: sort by age in descending order.
Note that after this pass rows are sorted by age but
Twin1/Twin2 and Anne/Fred pairs are still in correct
firstname order.''')
DATA.sort(key=lambda row: row[2], reverse=True)
for d in DATA:
    print("{:10s} {:10s} {}".format(*d))

print('''
Final pass sorts the Jones from the Smiths.
Within each family members are sorted by age but equal
age members are sorted by first name.
''')
DATA.sort(key=lambda row: row[0])
for d in DATA:
    print("{:10s} {:10s} {}".format(*d))

This is a runnable example, but to save people running it the output is:

Initial data in random order
Jones      Jane       58
Smith      Anne       30
Jones      Fred       30
Smith      John       60
Smith      Fred       30
Jones      Anne       30
Smith      Jane       58
Smith      Twin2      3
Jones      John       60
Smith      Twin1      3
Jones      Twin1      3
Jones      Twin2      3

First we sort by first name, after this pass all
Twin1 come before Twin2 and Anne comes before Fred
Smith      Anne       30
Jones      Anne       30
Jones      Fred       30
Smith      Fred       30
Jones      Jane       58
Smith      Jane       58
Smith      John       60
Jones      John       60
Smith      Twin1      3
Jones      Twin1      3
Smith      Twin2      3
Jones      Twin2      3

Second pass: sort by age in descending order.
Note that after this pass rows are sorted by age but
Twin1/Twin2 and Anne/Fred pairs are still in correct
firstname order.
Smith      John       60
Jones      John       60
Jones      Jane       58
Smith      Jane       58
Smith      Anne       30
Jones      Anne       30
Jones      Fred       30
Smith      Fred       30
Smith      Twin1      3
Jones      Twin1      3
Smith      Twin2      3
Jones      Twin2      3

Final pass sorts the Jones from the Smiths.
Within each family members are sorted by age but equal
age members are sorted by first name.

Jones      John       60
Jones      Jane       58
Jones      Anne       30
Jones      Fred       30
Jones      Twin1      3
Jones      Twin2      3
Smith      John       60
Smith      Jane       58
Smith      Anne       30
Smith      Fred       30
Smith      Twin1      3
Smith      Twin2      3

Note in particular how in the second step the reverse=True parameter keeps the firstnames in order whereas simply sorting then reversing the list would lose the desired order for the third sort key.

How do I set an absolute include path in PHP?

What I do is put a config.php file in my root directory. This file is included by all PHP files in my project. In that config.php file, I then do the following;

define( 'ROOT_DIR', dirname(__FILE__) );

Then in all files, I know what the root of my project is and can do stuff like this

require_once( ROOT_DIR.'/include/functions.php' );

Sorry, no bonus points for getting outside of the public directory ;) This also has the unfortunate side affect that you still need a relative path for finding config.php, but it makes the rest of your includes much easier.

How do I change the database name using MySQL?

I don't think it's possible.

You can use mysqldump to dump the data and then create a schema with your new name and then dump the data into that new database.

SQL Server 2008 - Case / If statements in SELECT Clause

Simple CASE expression:

CASE input_expression 
     WHEN when_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END

Searched CASE expression:

CASE
     WHEN Boolean_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END

Reference: http://msdn.microsoft.com/en-us/library/ms181765.aspx

How do I add records to a DataGridView in VB.Net?

I think you should build a dataset/datatable in code and bind the grid to that.

How to specify the current directory as path in VBA?

I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path

But the main issue was not here. The problem was with these 2 lines of code

strFile = Dir(strPath & "*.csv")

Which should have written as

strFile = Dir(strPath & "\*.csv")

and

With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _

Which should have written as

With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _

How to select into a variable in PL/SQL when the result might be null?

I would recommend using a cursor. A cursor fetch is always a single row (unless you use a bulk collection), and cursors do not automatically throw no_data_found or too_many_rows exceptions; although you may inspect the cursor attribute once opened to determine if you have a row and how many.

declare
v_column my_table.column%type;
l_count pls_integer;
cursor my_cursor is
  select count(*) from my_table where ...;

begin
  open my_cursor;
    fetch my_cursor into l_count;
  close my_cursor;

  if l_count = 1 then
    select whse_code into v_column from my_table where ...;
  else
    v_column := null;
  end if;
end;

Or, even more simple:

    declare
    v_column my_table.column%type;
    cursor my_cursor is
      select column from my_table where ...;

    begin
      open my_cursor;
        fetch my_cursor into v_column;
        -- Optional IF .. THEN based on FOUND or NOTFOUND
        -- Not really needed if v_column is not set
        if my_cursor%notfound then
          v_column := null;
        end if;
      close my_cursor;
    end;

copy db file with adb pull results in 'permission denied' error

I had just the same problem, here's how to deal with it:

  1. adb shell to the device
  2. su
  3. ls -l and check current access rights on the file you need. You'll need that later.
  4. go to the file needed and: chmod 777 file.ext. Note: now you have a temporary security issue. You've just allowed all the rights to everyone! Consider adding just R for users.
  5. open another console and: adb pull /path/to/file.ext c:\pc\path\to\file.exe
  6. Important: after you're done, revert the access rights back to the previous value (point 3)

Someone mentioned something similar earlier.

Thanks for the comments below.

How do I convert NSInteger to NSString datatype?

Easy way to do:

NSInteger value = x;
NSString *string = [@(value) stringValue];

Here the @(value) converts the given NSInteger to an NSNumber object for which you can call the required function, stringValue.

Simplest way to wait some asynchronous tasks complete, in Javascript?

I do this without external libaries:

var yourArray = ['aaa','bbb','ccc'];
var counter = [];

yourArray.forEach(function(name){
    conn.collection(name).drop(function(err) {
        counter.push(true);
        console.log('dropped');
        if(counter.length === yourArray.length){
            console.log('all dropped');
        }
    });                
});

What is the Java ?: operator called and what does it do?

Others have answered this to reasonable extent, but often with the name "ternary operator".

Being the pedant that I am, I'd like to make it clear that the name of the operator is the conditional operator or "conditional operator ?:". It's a ternary operator (in that it has three operands) and it happens to be the only ternary operator in Java at the moment.

However, the spec is pretty clear that its name is the conditional operator or "conditional operator ?:" to be absolutely unambiguous. I think it's clearer to call it by that name, as it indicates the behaviour of the operator to some extent (evaluating a condition) rather than just how many operands it has.

Get MIME type from filename extension

It is always not necessary that the mime type calculated by the extention of the file will be always right.

lets say i can save a file with .png extention but the fileformat i can set as "ImageFormat.jpeg".

So in this case the file which you will be calculating, will give a different result... it may result in big size file than the original.

If you are working with images then you can use the imagecodecInfo and ImageFormat.

Order Bars in ggplot2 bar graph

Using scale_x_discrete (limits = ...) to specify the order of bars.

positions <- c("Goalkeeper", "Defense", "Striker")
p <- ggplot(theTable, aes(x = Position)) + scale_x_discrete(limits = positions)

C#: HttpClient with POST parameters

As Ben said, you are POSTing your request ( HttpMethod.Post specified in your code )

The querystring (get) parameters included in your url probably will not do anything.

Try this:

string url = "http://myserver/method";    
string content = "param1=1&param2=2";
HttpClientHandler handler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(handler);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
HttpResponseMessage response = await httpClient.SendAsync(request,content);

HTH,

bovako

Why would I use dirname(__FILE__) in an include or include_once statement?

I used this below if this is what you are thinking. It it worked well for me.

<?php
    include $_SERVER['DOCUMENT_ROOT']."/head_lib.php";
?>

What I was trying to do was pulla file called /head_lib.php from the root folder. It would not pull anything to build the webpage. The header, footer and other key features in sub directories would never show up. Until I did above it worked like a champ.

How to check whether java is installed on the computer

Check the installation directories (typically C:\Program Files (x86) or C:\Program Files) for the java folder. If it contains the JRE you have java installed.

Oracle PL/SQL - Are NO_DATA_FOUND Exceptions bad for stored procedure performance?

@DCookie

I just want to point out that you can leave off the lines that say

EXCEPTION  
  WHEN OTHERS THEN    
    RAISE;

You'll get the same effect if you leave off the exception block all together, and the line number reported for the exception will be the line where the exception is actually thrown, not the line in the exception block where it was re-raised.

How to check if a string "StartsWith" another string?

I am not sure for javascript but in typescript i did something like

var str = "something";
(<String>str).startsWith("some");

I guess it should work on js too. I hope it helps!

How to select <td> of the <table> with javascript?

There are also the rows and cells members;

var t = document.getElementById("tbl");
for (var r = 0; r < t.rows.length; r++) {
    for (var c = 0; c < t.rows[r].cells.length; c++) {
        alert(t.rows[r].cells[c].innerHTML)
    }
}

PowerShell: Comparing dates

Late but more complete answer in point of getting the most advanced date from $Output

## Q:\test\2011\02\SO_5097125.ps1
## simulate object input with a here string 
$Output = @"
"Date"
"Monday, April 08, 2013 12:00:00 AM"
"Friday, April 08, 2011 12:00:00 AM"
"@ -split '\r?\n' | ConvertFrom-Csv

## use Get-Date and calculated property in a pipeline
$Output | Select-Object @{n='Date';e={Get-Date $_.Date}} |
    Sort-Object Date | Select-Object -Last 1 -Expand Date

## use Get-Date in a ForEach-Object
$Output.Date | ForEach-Object{Get-Date $_} |
    Sort-Object | Select-Object -Last 1

## use [datetime]::ParseExact
## the following will only work if your locale is English for day, month day abbrev.
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',$Null)
} | Sort-Object | Select-Object -Last 1

## for non English locales
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',[cultureinfo]::InvariantCulture)
} | Sort-Object | Select-Object -Last 1

## in case the day month abbreviations are in other languages, here German
## simulate object input with a here string 
$Output = @"
"Date"
"Montag, April 08, 2013 00:00:00"
"Freidag, April 08, 2011 00:00:00"
"@ -split '\r?\n' | ConvertFrom-Csv
$CIDE = New-Object System.Globalization.CultureInfo("de-DE")
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy HH:mm:ss',$CIDE)
} | Sort-Object | Select-Object -Last 1

How to Add Incremental Numbers to a New Column Using Pandas

df.insert(0, 'New_ID', range(880, 880 + len(df)))
df

enter image description here

Styling input buttons for iPad and iPhone

Use the below css

_x000D_
_x000D_
input[type="submit"] {_x000D_
  font-size: 20px;_x000D_
  background: pink;_x000D_
  border: none;_x000D_
  padding: 10px 20px;_x000D_
}_x000D_
.flat-btn {_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
   appearance: none;_x000D_
   border-radius: 0;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
  margin: 25px 0 10px;_x000D_
  font-size: 20px;_x000D_
}
_x000D_
<h2>iOS Styled Button!</h2>_x000D_
<input type="submit" value="iOS Styled Button!" />_x000D_
_x000D_
<h2>No More Style! Button!</h2>_x000D_
<input class="flat-btn" type="submit" value="No More Style! Button!" />
_x000D_
_x000D_
_x000D_

Javascript format date / time

I don't think that can be done RELIABLY with built in methods on the native Date object. The toLocaleString method gets close, but if I am remembering correctly, it won't work correctly in IE < 10. If you are able to use a library for this task, MomentJS is a really amazing library; and it makes working with dates and times easy. Otherwise, I think you will have to write a basic function to give you the format that you are after.

function formatDate(date) {
    var year = date.getFullYear(),
        month = date.getMonth() + 1, // months are zero indexed
        day = date.getDate(),
        hour = date.getHours(),
        minute = date.getMinutes(),
        second = date.getSeconds(),
        hourFormatted = hour % 12 || 12, // hour returned in 24 hour format
        minuteFormatted = minute < 10 ? "0" + minute : minute,
        morning = hour < 12 ? "am" : "pm";

    return month + "/" + day + "/" + year + " " + hourFormatted + ":" +
            minuteFormatted + morning;
}

Creating CSS Global Variables : Stylesheet theme management

You will either need LESS or SASS for the same..

But here is another alternative which I believe will work out in CSS3..

http://css3.bradshawenterprises.com/blog/css-variables/

Example :

 :root {
    -webkit-var-beautifulColor: rgba(255,40,100, 0.8);
    -moz-var-beautifulColor: rgba(255,40,100, 0.8);
    -ms-var-beautifulColor: rgba(255,40,100, 0.8);
    -o-var-beautifulColor: rgba(255,40,100, 0.8);
    var-beautifulColor: rgba(255,40,100, 0.8);
 }
  .example1 h1 {
    color: -webkit-var(beautifulColor);
    color: -moz-var(beautifulColor);
    color: -ms-var(beautifulColor);
    color: -o-var(beautifulColor);
    color: var(beautifulColor);
 }

Play audio as microphone input

Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.

I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.

If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.

ParseError: not well-formed (invalid token) using cElementTree

A solution for gottcha for me, using Python's ElementTree... this has the invalid token error:

# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET

xml = u"""<?xml version='1.0' encoding='utf8'?>
<osm generator="pycrocosm server" version="0.6"><changeset created_at="2017-09-06T19:26:50.302136+00:00" id="273" max_lat="0.0" max_lon="0.0" min_lat="0.0" min_lon="0.0" open="true" uid="345" user="john"><tag k="test" v="????? ?? ??? ???? ?????? ??????????? ????? ?? ????? ???" /><tag k="foo" v="bar" /><discussion><comment data="2015-01-01T18:56:48Z" uid="1841" user="metaodi"><text>Did you verify those street names?</text></comment></discussion></changeset></osm>"""

xmltest = ET.fromstring(xml.encode("utf-8"))

However, it works with the addition of a hyphen in the encoding type:

<?xml version='1.0' encoding='utf-8'?>

Most odd. Someone found this footnote in the python docs:

The encoding string included in XML output should conform to the appropriate standards. For example, “UTF-8” is valid, but “UTF8” is not.

How do you get the current text contents of a QComboBox?

Getting the Text of ComboBox when the item is changed

     self.ui.comboBox.activated.connect(self.pass_Net_Adap)

  def pass_Net_Adap(self):
      print str(self.ui.comboBox.currentText())

How to import or copy images to the "res" folder in Android Studio?

You can simply use the terminal that comes with Android Studio. It is listed at the bottom of Android Studio. Just open it and use the cp command.

Allow Google Chrome to use XMLHttpRequest to load a URL from a local file

startup chrome with --disable-web-security

On Windows:

chrome.exe --disable-web-security

On Mac:

open /Applications/Google\ Chrome.app/ --args --disable-web-security

This will allow for cross-domain requests.
I'm not aware of if this also works for local files, but let us know !

And mention, this does exactly what you expect, it disables the web security, so be careful with it.

Can pandas automatically recognize dates?

While loading csv file contain date column.We have two approach to to make pandas to recognize date column i.e

  1. Pandas explicit recognize the format by arg date_parser=mydateparser

  2. Pandas implicit recognize the format by agr infer_datetime_format=True

Some of the date column data

01/01/18

01/02/18

Here we don't know the first two things It may be month or day. So in this case we have to use Method 1:- Explicit pass the format

    mydateparser = lambda x: pd.datetime.strptime(x, "%m/%d/%y")
    df = pd.read_csv(file_name, parse_dates=['date_col_name'],
date_parser=mydateparser)

Method 2:- Implicit or Automatically recognize the format

df = pd.read_csv(file_name, parse_dates=[date_col_name],infer_datetime_format=True)

CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

if you wanna remove attributes for all files in all folders on whole flash drive do this:

attrib -r -s -h /S /D

this command will remove attrubutes for all files folders and subfolders:

-read only -system file -is hidden -Processes matching files and all subfolders. -Processes folders as well

How to add colored border on cardview?

I solved this by putting two CardViews in a RelativeLayout. One with background of the border color and the other one with the image. (or whatever you wish to use)

Note the margin added to top and start for the second CardView. In my case I decided to use a 2dp thick border.

            <android.support.v7.widget.CardView
            android:id="@+id/user_thumb_rounded_background"
            android:layout_width="36dp"
            android:layout_height="36dp"
            app:cardCornerRadius="18dp"
            android:layout_marginEnd="6dp">

            <ImageView
                android:id="@+id/user_thumb_background"
                android:background="@color/colorPrimaryDark"
                android:layout_width="36dp"
                android:layout_height="36dp" />

        </android.support.v7.widget.CardView>

        <android.support.v7.widget.CardView
            android:id="@+id/user_thumb_rounded"
            android:layout_width="32dp"
            android:layout_height="32dp"
            app:cardCornerRadius="16dp"
            android:layout_marginTop="2dp"
            android:layout_marginStart="2dp"
            android:layout_marginEnd="6dp">

        <ImageView
            android:id="@+id/user_thumb"
            android:src="@drawable/default_profile"
            android:layout_width="32dp"
            android:layout_height="32dp" />

        </android.support.v7.widget.CardView>

Find the max of two or more columns with pandas

You can get the maximum like this:

>>> import pandas as pd
>>> df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
>>> df
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]]
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]].max(axis=1)
0    1
1    8
2    3

and so:

>>> df["C"] = df[["A", "B"]].max(axis=1)
>>> df
   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3

If you know that "A" and "B" are the only columns, you could even get away with

>>> df["C"] = df.max(axis=1)

And you could use .apply(max, axis=1) too, I guess.

How to upgrade OpenSSL in CentOS 6.5 / Linux / Unix from source?

rpm -qa openssl yum clean all && yum update "openssl*" lsof -n | grep ssl | grep DEL cd /usr/src wget http://www.openssl.org/source/openssl-1.0.1g.tar.gz tar -zxf openssl-1.0.1g.tar.gz cd openssl-1.0.1g ./config --prefix=/usr --openssldir=/usr/local/openssl shared ./config make make test make install cd /usr/src rm -rf openssl-1.0.1g.tar.gz rm -rf openssl-1.0.1g

and

openssl version

How to convert int[] into List<Integer> in Java?

If you're open to using a third party library, this will work in Eclipse Collections:

int[] a = {1, 2, 3};
List<Integer> integers = IntLists.mutable.with(a).collect(i -> i);
Assert.assertEquals(Lists.mutable.with(1, 2, 3), integers);

Note: I am a committer for Eclipse Collections.

Spring Boot - How to get the running port

You can get the port that is being used by an embedded Tomcat instance during tests by injecting the local.server.port value as such:

// Inject which port we were assigned
@Value("${local.server.port}")
int port;

how to create a list of lists

Just came across the same issue today...

In order to create a list of lists you will have firstly to store your data, array, or other type of variable into a list. Then, create a new empty list and append to it the lists that you just created. At the end you should end up with a list of lists:

list_1=data_1.tolist()
list_2=data_2.tolist()
listoflists = []
listoflists.append(list_1)
listoflists.append(list_2)

Auto-fit TextView for Android

My requirement is to

  • Click on the ScalableTextView
  • Open a listActivity and display various length string items.
  • Select a text from list.
  • Set the text back to the ScalableTextView in another activity.

I referred the link: Auto Scale TextView Text to Fit within Bounds (including comments) and also the DialogTitle.java

I found that the solution provided is nice and simple but it does not dynamically change the size of the text box. It works great when the selected text length from the list view is greater in size than the existing text lenght in the ScalableTextView. When selected the text having length smaller than the existing text in the ScalableTextView, it do not increase the size of the text, showing the text in the smaller size.

I modified the ScalableTextView.java to readjust the text size based on the text length. Here is my ScalableTextView.java

public class ScalableTextView extends TextView
{
float defaultTextSize = 0.0f;

public ScalableTextView(Context context, AttributeSet attrs, int defStyle)
{
    super(context, attrs, defStyle);
    setSingleLine();
    setEllipsize(TruncateAt.END);
    defaultTextSize = getTextSize();
}

public ScalableTextView(Context context, AttributeSet attrs)
{
    super(context, attrs);
    setSingleLine();
    setEllipsize(TruncateAt.END);
    defaultTextSize = getTextSize();
}

public ScalableTextView(Context context)
{
    super(context);
    setSingleLine();
    setEllipsize(TruncateAt.END);
    defaultTextSize = getTextSize();
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
    setTextSize(TypedValue.COMPLEX_UNIT_PX, defaultTextSize);
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    final Layout layout = getLayout();
    if (layout != null)
    {
        final int lineCount = layout.getLineCount();
        if (lineCount > 0)
        {
            int ellipsisCount = layout.getEllipsisCount(lineCount - 1);
            while (ellipsisCount > 0)
            {
                final float textSize = getTextSize();

                // textSize is already expressed in pixels
                setTextSize(TypedValue.COMPLEX_UNIT_PX, (textSize - 1));

                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
                ellipsisCount = layout.getEllipsisCount(lineCount - 1);
            }
        }
    }
}
}

Happy Coding....