Programs & Examples On #Infinispan

Infinispan is an ASL2 licensed data grid platform for Java and other JVM languages, providing a distributed in-memory cache as well as a clustering toolkit.

PSQLException: current transaction is aborted, commands ignored until end of transaction block

I had the same issue but then realised there is a table with the same name in the database. After deleting that I was able to import the file.

Auto refresh page every 30 seconds

Use setInterval instead of setTimeout. Though in this case either will be fine but setTimeout inherently triggers only once setInterval continues indefinitely.

<script language="javascript">
setInterval(function(){
   window.location.reload(1);
}, 30000);
</script>

UIView Hide/Show with animation

swift 4.2

with extension :

extension UIView {
func hideWithAnimation(hidden: Bool) {
        UIView.transition(with: self, duration: 0.5, options: .transitionCrossDissolve, animations: {
            self.isHidden = hidden
        })
    }
}

simple method:

func setView(view: UIView, hidden: Bool) {
    UIView.transition(with: view, duration: 0.5, options: .transitionCrossDissolve, animations: {
        view.isHidden = hidden
    })
}

How do you disable viewport zooming on Mobile Safari?

for iphones safari up to iOS 10 "viewport" is not a solution, i don't like this way, but i have used this javascript code and it helped me

 document.addEventListener('touchmove', function(event) {
    event = event.originalEvent || event;
    if(event.scale > 1) {
      event.preventDefault();
    }
  }, false);

Can I pass parameters in computed properties in Vue.Js

Yes methods are there for using params. Like answers stated above, in your example it's best to use methods since execution is very light.

Only for reference, in a situation where the method is complex and cost is high, you can cache the results like so:

data() {
    return {
        fullNameCache:{}
    };
}

methods: {
    fullName(salut) {
        if (!this.fullNameCache[salut]) {
            this.fullNameCache[salut] = salut + ' ' + this.firstName + ' ' + this.lastName;
        }
        return this.fullNameCache[salut];
    }
}

note: When using this, watchout for memory if dealing with thousands

Append text to textarea with javascript

Give this a try:

<!DOCTYPE html>
<html>
<head>
    <title>List Test</title>
    <style>
        li:hover {
            cursor: hand; cursor: pointer;
        }
    </style>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("li").click(function(){
                $('#alltext').append($(this).text());
            });
        });
    </script>
</head>
<body>

    <h2>List items</h2>
    <ol>
        <li>Hello</li>
        <li>World</li>
        <li>Earthlings</li>
    </ol>
    <form>
        <textarea id="alltext"></textarea>
    </form>

</body>
</html>

How to use the toString method in Java?

The toString() method returns a textual representation of an object. A basic implementation is already included in java.lang.Object and so because all objects inherit from java.lang.Object it is guaranteed that every object in Java has this method.

Overriding the method is always a good idea, especially when it comes to debugging, because debuggers often show objects by the result of the toString() method. So use a meaningful implementation but use it for technical purposes. The application logic should use getters:

public class Contact {
  private String firstName;
  private String lastName;
  public Contact (String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  public String getFirstName() {return firstName;}
  public String getLastName() {return lastName;}

  public String getContact() {
    return firstName + " " + lastName;
  }

  @Override
  public String toString() {
    return "["+getContact()+"]";
  }
}

How to use function srand() with time.h?

If you chose to srand, it is a good idea to then call rand() at least once before you use it, because it is a kind of horrible primitive psuedo-random generator. See Stack Overflow question Why does rand() % 7 always return 0?.

srand(time(NULL));
rand();
//Now use rand()

If available, either random or arc4rand would be better.

Creating a DateTime in a specific Time Zone in c#

I altered Jon Skeet answer a bit for the web with extension method. It also works on azure like a charm.

public static class DateTimeWithZone
{

private static readonly TimeZoneInfo timeZone;

static DateTimeWithZone()
{
//I added web.config <add key="CurrentTimeZoneId" value="Central Europe Standard Time" />
//You can add value directly into function.
    timeZone = TimeZoneInfo.FindSystemTimeZoneById(ConfigurationManager.AppSettings["CurrentTimeZoneId"]);
}


public static DateTime LocalTime(this DateTime t)
{
     return TimeZoneInfo.ConvertTime(t, timeZone);   
}
}

How to check if keras tensorflow backend is GPU or CPU version?

According to the documentation.

If you are running on the TensorFlow or CNTK backends, your code will automatically run on GPU if any available GPU is detected.

You can check what all devices are used by tensorflow by -

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

Also as suggested in this answer

import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

This will print whether your tensorflow is using a CPU or a GPU backend. If you are running this command in jupyter notebook, check out the console from where you have launched the notebook.

If you are sceptic whether you have installed the tensorflow gpu version or not. You can install the gpu version via pip.

pip install tensorflow-gpu

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

The error you have is because -credential without -computername can't exist.

You can try this way:

Invoke-Command -Credential $migratorCreds  -ScriptBlock ${function:Get-LocalUsers} -ArgumentList $xmlPRE,$migratorCreds -computername YOURCOMPUTERNAME

When should null values of Boolean be used?

I suppose in some case, you should have a mechanism to distinguish a Boolean field which already set value or not.

curl_exec() always returns false

In my case I need to set VERIFYHOST and VERIFYPEER to false, like this:

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

before the call to curl_exec($ch).

Because i am working between two development environments with self-assigned certificates. With valid certificates there is no need to set VERIFYHOST and VERIFYPEER to false because the curl_exec($ch) method will work and return the response you expect.

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

Since the problem is due to the difference in compilation and target machine specifications (x86 & x64) Follow the steps below:

  1. Open the C++ project that you want to configure.
  2. Choose the Configuration Manager button to open the Configuration Manager dialog box.
  3. In the Active Solution Platform drop-down list, select the option to open the New Solution Platform dialog box.
  4. In the Type or select the new platform drop-down list, select a 64-bit platform.

It solved my problem.

It says that TypeError: document.getElementById(...) is null

You can use JQuery to ensure that all elements of the documents are ready before it starts the client side scripting

$(document).ready(
    function()
    {
        document.getElementById(elmId).innerHTML = value;
    }
);

ImportError: No module named site on Windows

I have an application which relies heavily on Python and have kept up-to-date with python 2.7.x as new versions are released. Everthing has been fine until 2.7.11 when I got the same "No module named site" error. I've set PYTHONHOME to c:\Python27 and it's working. But the mystery remains why this is now needed when it wasn't with previous releases. And, if it is needed, why doesn't the installer set this var?

Regex to match 2 digits, optional decimal, two digits

  \d{1,}(\.\d{1,2})|\d{0,9}

tested in https://regexr.com/

matches with numbers with 2 decimals or just one, or numbers without decimals.

You can change the number or decimals you want by changing the number 2

How can I assign an ID to a view programmatically?

Yes, you can call setId(value) in any view with any (positive) integer value that you like and then find it in the parent container using findViewById(value). Note that it is valid to call setId() with the same value for different sibling views, but findViewById() will return only the first one.

How to import functions from different js file in a Vue+webpack+vue-loader project

I like the answer of Anacrust, though, by the fact "console.log" is executed twice, I would like to do a small update for src/mylib.js:

let test = {
  foo () { return 'foo' },
  bar () { return 'bar' },
  baz () { return 'baz' }
}

export default test

All other code remains the same...

Link to add to Google calendar

There is a comprehensive doc for google calendar and other calendar services: https://github.com/InteractionDesignFoundation/add-event-to-calendar-docs/blob/master/services/google.md

An example of working link: https://calendar.google.com/calendar/render?action=TEMPLATE&text=Bithday&dates=20201231T193000Z/20201231T223000Z&details=With%20clowns%20and%20stuff&location=North%20Pole

Simple way to create matrix of random numbers

use np.random.randint() as np.random.random_integers() is deprecated

random_matrix = np.random.randint(min_val,max_val,(<num_rows>,<num_cols>))

How do I load an org.w3c.dom.Document from XML in a string?

To manipulate XML in Java, I always tend to use the Transformer API:

import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;

public static Document loadXMLFrom(String xml) throws TransformerException {
    Source source = new StreamSource(new StringReader(xml));
    DOMResult result = new DOMResult();
    TransformerFactory.newInstance().newTransformer().transform(source , result);
    return (Document) result.getNode();
}   

How to use ng-repeat without an html element

If you use ng > 1.2, here is an example of using ng-repeat-start/end without generating unnecessary tags:

_x000D_
_x000D_
<html>_x000D_
  <head>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
    <script>_x000D_
      angular.module('mApp', []);_x000D_
    </script>_x000D_
  </head>_x000D_
  <body ng-app="mApp">_x000D_
    <table border="1" width="100%">_x000D_
      <tr ng-if="0" ng-repeat-start="elem in [{k: 'A', v: ['a1','a2']}, {k: 'B', v: ['b1']}, {k: 'C', v: ['c1','c2','c3']}]"></tr>_x000D_
_x000D_
      <tr>_x000D_
        <td rowspan="{{elem.v.length}}">{{elem.k}}</td>_x000D_
        <td>{{elem.v[0]}}</td>_x000D_
      </tr>_x000D_
      <tr ng-repeat="v in elem.v" ng-if="!$first">_x000D_
        <td>{{v}}</td>_x000D_
      </tr>_x000D_
_x000D_
      <tr ng-if="0" ng-repeat-end></tr>_x000D_
    </table>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

The important point: for tags used for ng-repeat-start and ng-repeat-end set ng-if="0", to let not be inserted in the page. In this way the inner content will be handled exactly as it is in knockoutjs (using commands in <!--...-->), and there will be no garbage.

Storing integer values as constants in Enum manner in java

You can use ordinal. So PAGE.SIGN_CREATE.ordinal() returns 1.

EDIT:

The only problem with doing this is that if you add, remove or reorder the enum values you will break the system. For many this is not an issue as they will not remove enums and will only add additional values to the end. It is also no worse than integer constants which also require you not to renumber them. However it is best to use a system like:

public enum PAGE{
  SIGN_CREATE0(0), SIGN_CREATE(1) ,HOME_SCREEN(2), REGISTER_SCREEN(3)

  private int id;

  PAGE(int id){
    this.id = id;
  }

  public int getID(){
    return id;
  }

}

You can then use getID. So PAGE.SIGN_CREATE.getID() returns 1.

Quick way to retrieve user information Active Directory

Well, if you know where your user lives in the AD hierarchy (e.g. quite possibly in the "Users" container, if it's a small network), you could also bind to the user account directly, instead of searching for it.

DirectoryEntry deUser = new DirectoryEntry("LDAP://cn=John Doe,cn=Users,dc=yourdomain,dc=com");

if (deUser != null)
{
  ... do something with your user
}

And if you're on .NET 3.5 already, you could even use the vastly expanded System.DirectorySrevices.AccountManagement namespace with strongly typed classes for each of the most common AD objects:

// bind to your domain
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "LDAP://dc=yourdomain,dc=com");

// find the user by identity (or many other ways)
UserPrincipal user = UserPrincipal.FindByIdentity(pc, "cn=John Doe");

There's loads of information out there on System.DirectoryServices.AccountManagement - check out this excellent article on MSDN by Joe Kaplan and Ethan Wilansky on the topic.

How to get am pm from the date time string using moment js

You are using the wrong format tokens when parsing your input. You should use ddd for an abbreviation of the name of day of the week, DD for day of the month, MMM for an abbreviation of the month's name, YYYY for the year, hh for the 1-12 hour, mm for minutes and A for AM/PM. See moment(String, String) docs.

Here is a working live sample:

_x000D_
_x000D_
console.log( moment('Mon 03-Jul-2017, 11:00 AM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );_x000D_
console.log( moment('Mon 03-Jul-2017, 11:00 PM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

How add spaces between Slick carousel item

An improvement based on the post by Dishan TD (which removes the vertical margin as well):

  .slick-slide{
    margin-left:  15px;
    margin-right:  15px;
  }

  .slick-list {
    margin-left: -15px;
    margin-right: -15px;
    pointer-events: none;
  }

Note: the pointer-events was necessary in my case, to be able to click on the left arrow.

php hide ALL errors

to Hide All Errors:

error_reporting(0);
ini_set('display_errors', 0);

to Show All Errors:

error_reporting(E_ALL);
ini_set('display_errors', 1);

Radio buttons not checked in jQuery

(!$('#radio').is(':checked'))

This worked for me

Convert double to Int, rounded down

Another option either using Double or double is use Double.valueOf(double d).intValue();. Simple and clean

Getting "net::ERR_BLOCKED_BY_CLIENT" error on some AJAX calls

AdBlockers usually have some rules, i.e. they match the URIs against some type of expression (sometimes they also match the DOM against expressions, not that this matters in this case).

Having rules and expressions that just operate on a tiny bit of text (the URI) is prone to create some false-positives...

Besides instructing your users to disable their extensions (at least on your site) you can also get the extension and test which of the rules/expressions blocked your stuff, provided the extension provides enough details about that. Once you identified the culprit, you can either try to avoid triggering the rule by using different URIs, report the rule as incorrect or overly-broad to the team that created it, or both. Check the docs for a particular add-on on how to do that.

For example, AdBlock Plus has a Blockable items view that shows all blocked items on a page and the rules that triggered the block. And those items also including XHR requests.

Blockable items

How do files get into the External Dependencies in Visual Studio C++?

The External Dependencies folder is populated by IntelliSense: the contents of the folder do not affect the build at all (you can in fact disable the folder in the UI).

You need to actually include the header (using a #include directive) to use it. Depending on what that header is, you may also need to add its containing folder to the "Additional Include Directories" property and you may need to add additional libraries and library folders to the linker options; you can set all of these in the project properties (right click the project, select Properties). You should compare the properties with those of the project that does build to determine what you need to add.

How Can I Truncate A String In jQuery?

From: jQuery text truncation (read more style)

Try this:

var title = "This is your title";

var shortText = jQuery.trim(title).substring(0, 10)
    .split(" ").slice(0, -1).join(" ") + "...";

And you can also use a plugin:

As a extension of String

String.prototype.trimToLength = function(m) {
  return (this.length > m) 
    ? jQuery.trim(this).substring(0, m).split(" ").slice(0, -1).join(" ") + "..."
    : this;
};

Use as

"This is your title".trimToLength(10);

Removing unwanted table cell borders with CSS

You need to add this to your CSS:

table { border-collapse:collapse }

Make Frequency Histogram for Factor Variables

The reason you are getting the unexpected result is that hist(...) calculates the distribution from a numeric vector. In your code, table(animalFactor) behaves like a numeric vector with three elements: 1, 3, 7. So hist(...) plots the number of 1's (1), the number of 3's (1), and the number of 7's (1). @Roland's solution is the simplest.

Here's a way to do this using ggplot:

library(ggplot2)
ggp <- ggplot(data.frame(animals),aes(x=animals))
# counts
ggp + geom_histogram(fill="lightgreen")
# proportion
ggp + geom_histogram(fill="lightblue",aes(y=..count../sum(..count..)))

You would get precisely the same result using animalFactor instead of animals in the code above.

How to use Global Variables in C#?

There's no such thing as a global variable in C#. Period.

You can have static members if you want:

public static class MyStaticValues
{
   public static bool MyStaticBool {get;set;}
}

Combine two OR-queries with AND in Mongoose

It's probably easiest to create your query object directly as:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });

How to set min-height for bootstrap container

Usually, if you are using bootstrap you can do this to set a min-height of 100%.

 <div class="container-fluid min-vh-100"></div>

this will also solve the footer not sticking at the bottom.

you can also do this from CSS with the following class

.stickDamnFooter{min-height: 100vh;}

if this class does not stick your footer just add position: fixed; to that same css class and you will not have this issue in a lifetime. Cheers.

Android Eclipse - Could not find *.apk

I just fixed this by reselecting a default JRE for the execution environment (JRE6 for JavaSE-1.6 in my case). It got unchecked for some reason.

Python exit commands - why so many and when should each be used?

sys.exit is the canonical way to exit.

Internally sys.exit just raises SystemExit. However, calling sys.exitis more idiomatic than raising SystemExit directly.

os.exit is a low-level system call that exits directly without calling any cleanup handlers.

quit and exit exist only to provide an easy way out of the Python prompt. This is for new users or users who accidentally entered the Python prompt, and don't want to know the right syntax. They are likely to try typing exit or quit. While this will not exit the interpreter, it at least issues a message that tells them a way out:

>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit
>>> exit()
$

This is essentially just a hack that utilizes the fact that the interpreter prints the __repr__ of any expression that you enter at the prompt.

send mail from linux terminal in one line

mail can represent quite a couple of programs on a linux system. What you want behind it is either sendmail or postfix. I recommend the latter.

You can install it via your favorite package manager. Then you have to configure it, and once you have done that, you can send email like this:

 echo "My message" | mail -s subject [email protected]

See the manual for more information.

As far as configuring postfix goes, there's plenty of articles on the internet on how to do it. Unless you're on a public server with a registered domain, you generally want to forward the email to a SMTP server that you can send email from.

For gmail, for example, follow http://rtcamp.com/tutorials/linux/ubuntu-postfix-gmail-smtp/ or any other similar tutorial.

Remove Item in Dictionary based on Value

Dictionary<string, string> source
//
//functional programming - do not modify state - only create new state
Dictionary<string, string> result = source
  .Where(kvp => string.Compare(kvp.Value, "two", true) != 0)
  .ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
//
// or you could modify state
List<string> keys = source
  .Where(kvp => string.Compare(kvp.Value, "two", true) == 0)
  .Select(kvp => kvp.Key)
  .ToList();

foreach(string theKey in keys)
{
  source.Remove(theKey);
}

How do I run a batch script from within a batch script?

You can use

call script.bat

or just

script.bat

How to return a list of keys from a Hash Map?

map.keySet()

will return you all the keys. If you want the keys to be sorted, you might consider a TreeMap

How to strip HTML tags from string in JavaScript?

cleanText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");

Distilled from this website (web.achive).

This regex looks for <, an optional slash /, one or more characters that are not >, then either > or $ (the end of the line)

Examples:

'<div>Hello</div>' ==> 'Hello'
 ^^^^^     ^^^^^^
'Unterminated Tag <b' ==> 'Unterminated Tag '
                  ^^

But it is not bulletproof:

'If you are < 13 you cannot register' ==> 'If you are '
            ^^^^^^^^^^^^^^^^^^^^^^^^
'<div data="score > 42">Hello</div>' ==> ' 42">Hello'
 ^^^^^^^^^^^^^^^^^^          ^^^^^^

If someone is trying to break your application, this regex will not protect you. It should only be used if you already know the format of your input. As other knowledgable and mostly sane people have pointed out, to safely strip tags, you must use a parser.

If you do not have acccess to a convenient parser like the DOM, and you cannot trust your input to be in the right format, you may be better off using a package like sanitize-html, and also other sanitizers are available.

Node.js fs.readdir recursive directory search

A library called Filehound is another option. It will recursively search a given directory (working directory by default). It supports various filters, callbacks, promises and sync searches.

For example, search the current working directory for all files (using callbacks):

const Filehound = require('filehound');

Filehound.create()
.find((err, files) => {
    if (err) {
        return console.error(`error: ${err}`);
    }
    console.log(files); // array of files
});

Or promises and specifying a specific directory:

const Filehound = require('filehound');

Filehound.create()
.paths("/tmp")
.find()
.each(console.log);

Consult the docs for further use cases and examples of usage: https://github.com/nspragg/filehound

Disclaimer: I'm the author.

Linux shell script for database backup

You might consider this Open Source tool, matiri, https://github.com/AAFC-MBB/matiri which is a concurrent mysql backup script with metadata in Sqlite3. Features:

  • Multi-Server: Multiple MySQL servers are supported whether they are co-located on the same or separate physical servers.
  • Parallel: Each database on the server to be backed up is done separately, in parallel (concurrency settable: default: 3)
  • Compressed: Each database backup compressed
  • Checksummed: SHA256 of each compressed backup file stored and the archive of all files
  • Archived: All database backups tar'ed together into single file
  • Recorded: Backup information stored in Sqlite3 database

Full disclosure: original matiri author.

JQuery: How to get selected radio button value?

It will start as soon as the page loads. You can keep it under some events like button click

$("#btn").click(function() { 
var val= $('input[type="radio"]:checked').val();
});

Changing file permission in Python

Just add 0 before the permission number:
For example - we want to give all permissions - 777
Syntax: os.chmod("file_name" , permission)

import os
os.chmod("file_name" , 0777)

Python version 3.7 does not support this syntax. It requires '0o' prefix for octal literals - this is the comment I have got in PyCharm

So for python 3.7, it will be

import os
os.chmod("file_name" , 0o777)

Child element click event trigger the parent click event

Without jQuery : DEMO

 <div id="parentDiv" onclick="alert('parentDiv');">
   <div id="childDiv" onclick="alert('childDiv');event.cancelBubble=true;">
     AAA
   </div>   
</div>

Thread Safe C# Singleton Pattern

The Lazy<T> version:

public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy
        = new Lazy<Singleton>(() => new Singleton());

    public static Singleton Instance
        => lazy.Value;

    private Singleton() { }
}

Requires .NET 4 and C# 6.0 (VS2015) or newer.

Formatting MM/DD/YYYY dates in textbox in VBA

For a quick solution, I usually do like this.

This approach will allow the user to enter date in any format they like in the textbox, and finally format in mm/dd/yyyy format when he is done editing. So it is quite flexible:

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    If TextBox1.Text <> "" Then
        If IsDate(TextBox1.Text) Then
            TextBox1.Text = Format(TextBox1.Text, "mm/dd/yyyy")
        Else
            MsgBox "Please enter a valid date!"
            Cancel = True
        End If
    End If
End Sub

However, I think what Sid developed is a much better approach - a full fledged date picker control.

Access Control Request Headers, is added to header in AJAX request with jQuery

Try to use the rack-cors gem. And add the header field in your Ajax call.

Draw in Canvas by finger, Android

I think it's important to add a thing, if you use the layout inflation that constructor in the drawview is not correct, add these constructors in the class:

public DrawingView(Context c, AttributeSet attrs) {
    super(c, attrs);
    ...
}

public DrawingView(Context c, AttributeSet attrs, int defStyle) {
    super(c, attrs, defStyle);
    ...
}

or the android system fails to inflate the layout file. I hope this could to help.

What is the difference between PUT, POST and PATCH?

The below definition is from the real world example.

Example Overview
For every client data, we are storing an identifier to find that client data and we will send back that identifier to that client for reference.

  1. POST

    • If the Client sends data without any identifier using the POST method then we will store it and assign a new identifier.
    • If the Client again sends the same data without any identifier using the POST method, then we will store it and assign a new identifier.
    • Note: Duplication is allowed here
  2. PUT

    • If the Client Sends data with an identifier then we will check whether that identifier exists. If the identifier exists we will update data else we will create it and assign a new identifier.
  3. PATCH

    • If the Client Sends data with an identifier then we will check whether that identifier exists. If the identifier exists we will update data else we will throw an exception.

Note: On Put Method, We are not throwing an exception if an identifier is not found. But in Patch method, we are throwing an exception if the identifier is not found.

Do let me know if you have any queries on the above.

Printing 2D array in matrix format

Your can do it like this in short hands.

        int[,] values=new int[2,3]{{2,4,5},{4,5,2}};

        for (int i = 0; i < values.GetLength(0); i++)
        {
            for (int k = 0; k < values.GetLength(1); k++) {
                Console.Write(values[i,k]);
            }

            Console.WriteLine();
        }

flutter remove back button on appbar

A simple way to remove the back button in the AppBar is to set automaticallyImplyLeading to false.

appBar: AppBar(
  title: Text("App Bar without Back Button"),
  automaticallyImplyLeading: false,
),

Linux/Unix command to determine if process is running?

Here is my version. Features:

  • checks for exact program name (first argument of the function). search for "mysql" will not match running "mysqld"
  • searches program arguments (second argument of the function)

script:

#!/bin/bash

# $1 - cmd
# $2 - args
# return: 0 - no error, running; 1 - error, not running
function isRunning() {
    for i in $(pidof $1); do
        cat /proc/$i/cmdline | tr '\000' ' ' | grep -F -e "$2" 1>&2> /dev/null
        if [ $? -eq 0 ]; then
            return 0
        fi
    done
    return 1
}

isRunning java "-Djava.util.logging.config.file=logging.properties"
if [ $? -ne 0 ]; then
    echo "not running, starting..."
fi

What's the best way to add a full screen background image in React Native

Easiest way to implemet background:

<ImageBackground style={styles.container} source={require('../../images/screen_login.jpg')}>
  <View style={styles.logoContainer}>
    <Image style={styles.logo}
      source={require('../../images/logo.png')}
    />
  </View> 
  <View style={styles.containerTextInput}>
    < LoginForm />
  </View>   
</ImageBackground>

const styles = StyleSheet.create({
  container: {
    flex: 1,
    //   backgroundColor:"#0984e3"
  },
  containerTextInput: {
    marginTop: 10,
    justifyContent: 'center'
  },

  logoContainer: {
    marginTop: 100,
    justifyContent: 'center',
    alignItems: 'center'
  },
  logo: {
    height: 150,
    width: 150
  }
});

How to grep and replace

You could even do it like this:

Example

grep -rl 'windows' ./ | xargs sed -i 's/windows/linux/g'

This will search for the string 'windows' in all files relative to the current directory and replace 'windows' with 'linux' for each occurrence of the string in each file.

How to copy file from host to container using Dockerfile

I faced this issue, I was not able to copy zeppelin [1GB] directory into docker container and was getting issue

COPY failed: stat /var/lib/docker/tmp/docker-builder977188321/zeppelin-0.7.2-bin-all: no such file or directory

I am using docker Version: 17.09.0-ce and resolved the issue with the following steps.

Step 1: copy zeppelin directory [which i want to copy into docker package]into directory contain "Dockfile"

Step 2: edit Dockfile and add command [location where we want to copy] ADD ./zeppelin-0.7.2-bin-all /usr/local/

Step 3: go to directory which contain DockFile and run command [alternatives also available] docker build

Step 4: docker image created Successfully with logs

Step 5/9 : ADD ./zeppelin-0.7.2-bin-all /usr/local/ ---> 3691c902d9fe

Step 6/9 : WORKDIR $ZEPPELIN_HOME ---> 3adacfb024d8 .... Successfully built b67b9ea09f02

Change language for bootstrap DateTimePicker

This is for your reference only:

https://github.com/rajit/bootstrap3-datepicker/tree/master/locales/zh-CN

https://github.com/smalot/bootstrap-datetimepicker

https://bootstrap-datepicker.readthedocs.io/en/v1.4.1/i18n.html

The case is as follows:

 <div class="input" id="event_period">
   <input class="date" required="required" type="text">
 </div>

 $.fn.datepicker.dates['zh-CN'] = {
    days:["???","???","???","???","???","???","???"],
    daysShort:["??","??","??","??","??","??","??"],
    daysMin:["?","?","?","?","?","?","?"],
    months:["??","??","??","??","??","??","??","??","??","??","???","???"],
    monthsShort:["1?","2?","3?","4?","5?","6?","7?","8?","9?","10?","11?","12?"],
    today:"??",
    clear:"??"
  };

  $('#event_period').datepicker({
    inputs: $('input.date'),
    todayBtn: "linked",
    clearBtn: true,
    format: "yyyy?mm?",
    titleFormat: "yyyy?mm?",
    language: 'zh-CN',
    weekStart:1 // Available or not
  });

How to use a TRIM function in SQL Server

Example:

DECLARE @Str NVARCHAR(MAX) = N'
            foo   bar
        Foo           Bar        

'

PRINT '[' + @Str + ']'

DECLARE @StrPrv NVARCHAR(MAX) = N''

WHILE ((@StrPrv <> @Str) AND (@Str IS NOT NULL)) BEGIN
    SET @StrPrv = @Str

    -- Beginning
    IF EXISTS (SELECT 1 WHERE @Str LIKE '[' + CHAR(13) + CHAR(10) + CHAR(9) + ']%')
        SET @Str = LTRIM(RIGHT(@Str, LEN(@Str) - 1))

    -- Ending
    IF EXISTS (SELECT 1 WHERE @Str LIKE '%[' + CHAR(13) + CHAR(10) + CHAR(9) + ']')
        SET @Str = RTRIM(LEFT(@Str, LEN(@Str) - 1))
END

PRINT '[' + @Str + ']'

Result

[
            foo   bar
        Foo           Bar        

]
[foo   bar
        Foo           Bar]

Using fnTrim

Source: https://github.com/reduardo7/fnTrim

SELECT dbo.fnTrim(colName)

Javascript : calling function from another file

Why don't you take a look to this answer

Including javascript files inside javascript files

In short you can load the script file with AJAX or put a script tag on the HTML to include it( before the script that uses the functions of the other script). The link I posted is a great answer and has multiple examples and explanations of both methods.

What does the ??!??! operator do in C?

As already stated ??!??! is essentially two trigraphs (??! and ??! again) mushed together that get replaced-translated to ||, i.e the logical OR, by the preprocessor.

The following table containing every trigraph should help disambiguate alternate trigraph combinations:

Trigraph   Replaces

??(        [
??)        ]
??<        {
??>        }
??/        \
??'        ^
??=        #
??!        |
??-        ~

Source: C: A Reference Manual 5th Edition

So a trigraph that looks like ??(??) will eventually map to [], ??(??)??(??) will get replaced by [][] and so on, you get the idea.

Since trigraphs are substituted during preprocessing you could use cpp to get a view of the output yourself, using a silly trigr.c program:

void main(){ const char *s = "??!??!"; } 

and processing it with:

cpp -trigraphs trigr.c 

You'll get a console output of

void main(){ const char *s = "||"; }

As you can notice, the option -trigraphs must be specified or else cpp will issue a warning; this indicates how trigraphs are a thing of the past and of no modern value other than confusing people who might bump into them.


As for the rationale behind the introduction of trigraphs, it is better understood when looking at the history section of ISO/IEC 646:

ISO/IEC 646 and its predecessor ASCII (ANSI X3.4) largely endorsed existing practice regarding character encodings in the telecommunications industry.

As ASCII did not provide a number of characters needed for languages other than English, a number of national variants were made that substituted some less-used characters with needed ones.

(emphasis mine)

So, in essence, some needed characters (those for which a trigraph exists) were replaced in certain national variants. This leads to the alternate representation using trigraphs comprised of characters that other variants still had around.

What is the difference between & and && in Java?

Besides not being a lazy evaluator by evaluating both operands, I think the main characteristics of bitwise operators compare each bytes of operands like in the following example:

int a = 4;
int b = 7;
System.out.println(a & b); // prints 4
//meaning in an 32 bit system
// 00000000 00000000 00000000 00000100
// 00000000 00000000 00000000 00000111
// ===================================
// 00000000 00000000 00000000 00000100

pip install - locale.Error: unsupported locale setting

For Dockerfile, this works for me:

RUN locale-gen en_US.UTF-8  
ENV LANG en_US.UTF-8  
ENV LANGUAGE en_US:en  
ENV LC_ALL en_US.UTF-8  

How to install locale-gen?

docker ubuntu /bin/sh: 1: locale-gen: not found

jQuery "on create" event for dynamically-created elements

I Think it's worth mentioning that in some cases, this would work:

$( document ).ajaxComplete(function() {
// Do Stuff
});

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

Nobody seems to be explaining the difference between an array and an object.

[] is declaring an array.

{} is declaring an object.

An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class. In fact, typeof [] === "object" to further show you that an array is an object.

The additional features consist of a magic .length property that keeps track of the number of items in the array and a whole slew of methods for operating on the array such as .push(), .pop(), .slice(), .splice(), etc... You can see a list of array methods here.

An object gives you the ability to associate a property name with a value as in:

var x = {};
x.foo = 3;
x["whatever"] = 10;
console.log(x.foo);      // shows 3
console.log(x.whatever); // shows 10

Object properties can be accessed either via the x.foo syntax or via the array-like syntax x["foo"]. The advantage of the latter syntax is that you can use a variable as the property name like x[myvar] and using the latter syntax, you can use property names that contain characters that Javascript won't allow in the x.foo syntax.

A property name can be any string value.


An array is an object so it has all the same capabilities of an object plus a bunch of additional features for managing an ordered, sequential list of numbered indexes starting from 0 and going up to some length. Arrays are typically used for an ordered list of items that are accessed by numerical index. And, because the array is ordered, there are lots of useful features to manage the order of the list .sort() or to add or remove things from the list.

jQuery validation: change default error message

You can specify your own messages in the validate call. Lifting and abbreviating this code from the Remember the Milk signup form used in the Validation plugin documentation (http://jquery.bassistance.de/validate/demo/milk/), you can easily specify your own messages:

var validator = $("#signupform").validate({
    rules: {
        firstname: "required",
        lastname: "required",
        username: {
            required: true,
            minlength: 2,
            remote: "users.php"
        }
    },
    messages: {
        firstname: "Enter your firstname",
        lastname: "Enter your lastname",
        username: {
            required: "Enter a username",
            minlength: jQuery.format("Enter at least {0} characters"),
            remote: jQuery.format("{0} is already in use")
        }
    }
});

The complete API for validate(...) : http://jqueryvalidation.org/validate

How do you find the first key in a dictionary?

If you just want the first key from a dictionary you should use what many have suggested before

first = next(iter(prices))

However if you want the first and keep the rest as a list you could use the values unpacking operator

first, *rest = prices

The same is applicable on values by replacing prices with prices.values() and for both key and value you can even use unpacking assignment

>>> (product, price), *rest = prices.items()
>>> product
'banana'
>>> price
4

Note: You might be tempted to use first, *_ = prices to just get the first key, but I would generally advice against this usage unless the dictionary is very short since it loops over all keys and creating a list for the rest has some overhead.

Note: As mentioned by others insertion order is preserved from python 3.7 (or technically 3.6) and above whereas earlier implementations should be regarded as undefined order.

Error:Execution failed for task ':app:processDebugResources'. > java.io.IOException: Could not delete folder "" in android studio

Fix This issue by this command

In Windows Platform

cd android && gradlew clean && cd..

In Mac Platform

cd android && ./gradlew clean && cd ..

Select * from subquery

You can select every column from that sub-query by aliasing it and adding the alias before the *:

SELECT t.*, a+b AS total_sum
FROM
(
   SELECT SUM(column1) AS a, SUM(column2) AS b
   FROM table
) t

How to compute precision, recall, accuracy and f1-score for the multiclass case with scikit learn?

Posed question

Responding to the question 'what metric should be used for multi-class classification with imbalanced data': Macro-F1-measure. Macro Precision and Macro Recall can be also used, but they are not so easily interpretable as for binary classificaion, they are already incorporated into F-measure, and excess metrics complicate methods comparison, parameters tuning, and so on.

Micro averaging are sensitive to class imbalance: if your method, for example, works good for the most common labels and totally messes others, micro-averaged metrics show good results.

Weighting averaging isn't well suited for imbalanced data, because it weights by counts of labels. Moreover, it is too hardly interpretable and unpopular: for instance, there is no mention of such an averaging in the following very detailed survey I strongly recommend to look through:

Sokolova, Marina, and Guy Lapalme. "A systematic analysis of performance measures for classification tasks." Information Processing & Management 45.4 (2009): 427-437.

Application-specific question

However, returning to your task, I'd research 2 topics:

  1. metrics commonly used for your specific task - it lets (a) to compare your method with others and understand if you do something wrong, and (b) to not explore this by yourself and reuse someone else's findings;
  2. cost of different errors of your methods - for example, use-case of your application may rely on 4- and 5-star reviewes only - in this case, good metric should count only these 2 labels.

Commonly used metrics. As I can infer after looking through literature, there are 2 main evaluation metrics:

  1. Accuracy, which is used, e.g. in

Yu, April, and Daryl Chang. "Multiclass Sentiment Prediction using Yelp Business."

(link) - note that the authors work with almost the same distribution of ratings, see Figure 5.

Pang, Bo, and Lillian Lee. "Seeing stars: Exploiting class relationships for sentiment categorization with respect to rating scales." Proceedings of the 43rd Annual Meeting on Association for Computational Linguistics. Association for Computational Linguistics, 2005.

(link)

  1. MSE (or, less often, Mean Absolute Error - MAE) - see, for example,

Lee, Moontae, and R. Grafe. "Multiclass sentiment analysis with restaurant reviews." Final Projects from CS N 224 (2010).

(link) - they explore both accuracy and MSE, considering the latter to be better

Pappas, Nikolaos, Rue Marconi, and Andrei Popescu-Belis. "Explaining the Stars: Weighted Multiple-Instance Learning for Aspect-Based Sentiment Analysis." Proceedings of the 2014 Conference on Empirical Methods In Natural Language Processing. No. EPFL-CONF-200899. 2014.

(link) - they utilize scikit-learn for evaluation and baseline approaches and state that their code is available; however, I can't find it, so if you need it, write a letter to the authors, the work is pretty new and seems to be written in Python.

Cost of different errors. If you care more about avoiding gross blunders, e.g. assinging 1-star to 5-star review or something like that, look at MSE; if difference matters, but not so much, try MAE, since it doesn't square diff; otherwise stay with Accuracy.

About approaches, not metrics

Try regression approaches, e.g. SVR, since they generally outperforms Multiclass classifiers like SVC or OVA SVM.

Rmi connection refused with localhost

You need to have a rmiregistry running before attempting to connect (register) a RMI service with it.

The LocateRegistry.createRegistry(2020) method call creates and exports a registry on the specified port number.

See the documentation for LocateRegistry

Bootstrap 4, how to make a col have a height of 100%?

Although it is not a good solution but may solve your problem. You need to use position absolute in #yellow element!

_x000D_
_x000D_
#yellow {height: 100%; background: yellow; position: absolute; top: 0px; left: 0px;}_x000D_
.container-fluid {position: static !important;}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<div class="container-fluid">_x000D_
  <div class="row justify-content-center">_x000D_
_x000D_
    <div class="col-4" id="yellow">_x000D_
      XXXX_x000D_
    </div>_x000D_
_x000D_
    <div class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8">_x000D_
      Form Goes Here_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
_x000D_
_x000D_
_x000D_

How to find specified name and its value in JSON-string from Java?

Use a JSON library to parse the string and retrieve the value.

The following very basic example uses the built-in JSON parser from Android.

String jsonString = "{ \"name\" : \"John\", \"age\" : \"20\", \"address\" : \"some address\" }";
JSONObject jsonObject = new JSONObject(jsonString);
int age = jsonObject.getInt("age");

More advanced JSON libraries, such as jackson, google-gson, json-io or genson, allow you to convert JSON objects to Java objects directly.

What's the difference between passing by reference vs. passing by value?

In short, Passed by value is WHAT it is and passed by reference is WHERE it is.

If your value is VAR1 = "Happy Guy!", you will only see "Happy Guy!". If VAR1 changes to "Happy Gal!", you won't know that. If it's passed by reference, and VAR1 changes, you will.

I got error "The DELETE statement conflicted with the REFERENCE constraint"

To DELETE, without changing the references, you should first delete or otherwise alter (in a manner suitable for your purposes) all relevant rows in other tables.

To TRUNCATE you must remove the references. TRUNCATE is a DDL statement (comparable to CREATE and DROP) not a DML statement (like INSERT and DELETE) and doesn't cause triggers, whether explicit or those associated with references and other constraints, to be fired. Because of this, the database could be put into an inconsistent state if TRUNCATE was allowed on tables with references. This was a rule when TRUNCATE was an extension to the standard used by some systems, and is mandated by the the standard, now that it has been added.

$ is not a function - jQuery error

When jQuery is not present you get $ is undefined and not your message.

Did you check if you don't have a variable called $ somewhere before your code?
Inspect the value of $ in firebug to see what it is.

Slightly out of the question, but I can't resist to write a shorter code to your class assignment:

    var i = 1;
    $("ol li").each(function(){
        $(this).addClass('olli' + i++);
    });

How do you rename a Git tag?

Regardless of the issues dealing with pushing tags and renaming tags that have already been pushed, in case the tag to rename is an annotated one, you could first copy it thanks to the following single-line command line:

git tag -a -m "`git cat-file -p old_tag | tail -n +6`" new_tag old_tag^{}

Then, you just need to delete the old tag:

git tag -d old_tag

I found this command line thanks to the following two answers:

Edit:
Having encountered problems using automatic synchronisation of tags setting fetch.pruneTags=true (as described in https://stackoverflow.com/a/49215190/7009806), I personally suggest to first copy the new tag on the server and then delete the old one. That way, the new tag does not get randomly deleted when deleting the old tag and a synchronisation of the tags would like to delete the new tag that is not yet on the server. So, for instance, all together we get:

git tag -a -m "`git cat-file -p old_tag | tail -n +6`" new_tag old_tag^{}
git push --tags
git tag -d old_tag
git push origin :refs/tags/old_tag

The imported project "C:\Microsoft.CSharp.targets" was not found

In my case I could not load one out of 5 projects in my solution.

It helped to close Visual Studio and I had to delete Microsoft.Net.Compilers.1.3.2 nuget folder under packages folder.

Afterwards, open your solution again and the project loaded as expected

Just to be sure, close all instances of VS before you delete the folder.

The type or namespace name could not be found

If your project (PrjTest) does not expose any public types within the PrjTest namespace, it will cause that error.

Does the project (PrjTest) include any classes or types in the "PrjTest" namespace which are public?

How to get domain root url in Laravel 4?

In Laravel 5.1 and later you can use

request()->getHost();

or

request()->getHttpHost();

(the second one will add port if it's not standard one)

How to list all the roles existing in Oracle database?

all_roles.sql

SELECT SUBSTR(TRIM(rtp.role),1,12)          AS ROLE
     , SUBSTR(rp.grantee,1,16)              AS GRANTEE
     , SUBSTR(TRIM(rtp.privilege),1,12)     AS PRIVILEGE
     , SUBSTR(TRIM(rtp.owner),1,12)         AS OWNER
     , SUBSTR(TRIM(rtp.table_name),1,28)    AS TABLE_NAME
     , SUBSTR(TRIM(rtp.column_name),1,20)   AS COLUMN_NAME
     , SUBSTR(rtp.common,1,4)               AS COMMON
     , SUBSTR(rtp.grantable,1,4)            AS GRANTABLE
     , SUBSTR(rp.default_role,1,16)         AS DEFAULT_ROLE
     , SUBSTR(rp.admin_option,1,4)          AS ADMIN_OPTION
  FROM role_tab_privs rtp
  LEFT JOIN dba_role_privs rp
    ON (rtp.role = rp.granted_role)
 WHERE ('&1' IS NULL OR UPPER(rtp.role) LIKE UPPER('%&1%'))
   AND ('&2' IS NULL OR UPPER(rp.grantee) LIKE UPPER('%&2%'))
   AND ('&3' IS NULL OR UPPER(rtp.table_name) LIKE UPPER('%&3%'))
   AND ('&4' IS NULL OR UPPER(rtp.owner) LIKE UPPER('%&4%'))
 ORDER BY 1
        , 2
        , 3
        , 4
;

Usage

SQLPLUS> @all_roles '' '' '' '' '' ''
SQLPLUS> @all_roles 'somerol' '' '' '' '' ''
SQLPLUS> @all_roles 'roler' 'username' '' '' '' ''
SQLPLUS> @all_roles '' '' 'part-of-database-package-name' '' '' ''
etc.

ToggleButton in C# WinForms

When my button's FlatStyle is set to system, it looks flat. And when it's set to popup, it only pops up when mouses over. Either is what I want. I want it to look sunken when checked and raised when unchecked and no change while mousing over (the button is really a checkbox but the checkbox's appearance property is set to button).

I end up setting the FlatStyle to flat and wrote a new Paint event handler.

 private void checkbox_paint(object sender, PaintEventArgs e)
        {
            CheckBox myCheckbox = (CheckBox)sender;
            Rectangle borderRectangle = myCheckbox.ClientRectangle;
            if (myCheckbox.Checked)
            {
                ControlPaint.DrawBorder3D(e.Graphics, borderRectangle,
                    Border3DStyle.Sunken);
            }
            else
            {
                ControlPaint.DrawBorder3D(e.Graphics, borderRectangle,
                    Border3DStyle.Raised);
            }
        }

I give a similar answer to this question: C# winforms button with solid border, like 3d Sorry for double posting.

NTFS performance and large volumes of files and directories

I am building a File-Structure to host up to 2 billion (2^32) files and performed the following tests that show a sharp drop in Navigate + Read Performance at about 250 Files or 120 Directories per NTFS Directory on a Solid State Drive (SSD):

  • The File Performance drops by 50% between 250 and 1000 Files.
  • The Directory Performance drops by 60% between 120 and 1000 Directories.
  • Values for Numbers > 1000 remain relatively stable

Interestingly the Number of Directories and Files do NOT significantly interfere.

So the Lessons are:

  • File Numbers above 250 cost a Factor of 2
  • Directories above 120 cost a Factor of 2.5
  • The File-Explorer in Windows 7 can handle large #Files or #Dirs, but Usability is still bad.
  • Introducing Sub-Directories is not expensive

This is the Data (2 Measurements for each File and Directory):

(FOPS = File Operations per Second)
(DOPS = Directory Operations per Second)

#Files  lg(#)   FOPS    FOPS2   DOPS    DOPS2
   10   1.00    16692   16692   16421   16312
  100   2.00    16425   15943   15738   16031
  120   2.08    15716   16024   15878   16122
  130   2.11    15883   16124   14328   14347
  160   2.20    15978   16184   11325   11128
  200   2.30    16364   16052   9866    9678
  210   2.32    16143   15977   9348    9547
  220   2.34    16290   15909   9094    9038
  230   2.36    16048   15930   9010    9094
  240   2.38    15096   15725   8654    9143
  250   2.40    15453   15548   8872    8472
  260   2.41    14454   15053   8577    8720
  300   2.48    12565   13245   8368    8361
  400   2.60    11159   11462   7671    7574
  500   2.70    10536   10560   7149    7331
 1000   3.00    9092    9509    6569    6693
 2000   3.30    8797    8810    6375    6292
10000   4.00    8084    8228    6210    6194
20000   4.30    8049    8343    5536    6100
50000   4.70    7468    7607    5364    5365

And this is the Test Code:

[TestCase(50000, false, Result = 50000)]
[TestCase(50000, true, Result = 50000)]
public static int TestDirPerformance(int numFilesInDir, bool testDirs) {
    var files = new List<string>();
    var dir = Path.GetTempPath() + "\\Sub\\" + Guid.NewGuid() + "\\";
    Directory.CreateDirectory(dir);
    Console.WriteLine("prepare...");
    const string FILE_NAME = "\\file.txt";
    for (int i = 0; i < numFilesInDir; i++) {
        string filename = dir + Guid.NewGuid();
        if (testDirs) {
            var dirName = filename + "D";
            Directory.CreateDirectory(dirName);
            using (File.Create(dirName + FILE_NAME)) { }
        } else {
            using (File.Create(filename)) { }
        }
        files.Add(filename);
    }
    //Adding 1000 Directories didn't change File Performance
    /*for (int i = 0; i < 1000; i++) {
        string filename = dir + Guid.NewGuid();
        Directory.CreateDirectory(filename + "D");
    }*/
    Console.WriteLine("measure...");
    var r = new Random();
    var sw = new Stopwatch();
    sw.Start();
    int len = 0;
    int count = 0;
    while (sw.ElapsedMilliseconds < 5000) {
        string filename = files[r.Next(files.Count)];
        string text = File.ReadAllText(testDirs ? filename + "D" + FILE_NAME : filename);
        len += text.Length;
        count++;
    }
    Console.WriteLine("{0} File Ops/sec ", count / 5);
    return numFilesInDir; 
}

Update Top 1 record in table sql server

It also works well ...

Update t
Set t.TIMESTAMP2 = '2013-12-12 15:40:31.593'
From
(
    Select Top 1 TIMESTAMP2
    From TX_Master_PCBA
    Where SERIAL_NO IN ('0500030309')
    Order By TIMESTAMP2 DESC
) t

How to read integer value from the standard input in Java

This causes headaches so I updated a solution that will run using the most common hardware and software tools available to users in December 2014. Please note that the JDK/SDK/JRE/Netbeans and their subsequent classes, template libraries compilers, editors and debuggerz are free.

This program was tested with Java v8 u25. It was written and built using
Netbeans IDE 8.0.2, JDK 1.8, OS is win8.1 (apologies) and browser is Chrome (double-apologies) - meant to assist UNIX-cmd-line OG's deal with modern GUI-Web-based IDEs at ZERO COST - because information (and IDEs) should always be free. By Tapper7. For Everyone.

code block:

    package modchk; //Netbeans requirement.
    import java.util.Scanner;
    //import java.io.*; is not needed Netbeans automatically includes it.           
    public class Modchk {
        public static void main(String[] args){
            int input1;
            int input2;

            //Explicity define the purpose of the .exe to user:
            System.out.println("Modchk by Tapper7. Tests IOStream and basic bool modulo fxn.\n"
            + "Commented and coded for C/C++ programmers new to Java\n");

            //create an object that reads integers:
            Scanner Cin = new Scanner(System.in); 

            //the following will throw() if you don't do you what it tells you or if 
            //int entered == ArrayIndex-out-of-bounds for your system. +-~2.1e9
            System.out.println("Enter an integer wiseguy: ");
            input1 = Cin.nextInt(); //this command emulates "cin >> input1;"

            //I test like Ernie Banks played hardball: "Let's play two!"
            System.out.println("Enter another integer...anyday now: ");
            input2 = Cin.nextInt(); 

            //debug the scanner and istream:
            System.out.println("the 1st N entered by the user was " + input1);
            System.out.println("the 2nd N entered by the user was " + input2);

            //"do maths" on vars to make sure they are of use to me:
            System.out.println("modchk for " + input1);
            if(2 % input1 == 0){
                System.out.print(input1 + " is even\n"); //<---same output effect as *.println
                }else{
                System.out.println(input1 + " is odd");
            }//endif input1

            //one mo' 'gain (as in istream dbg chk above)
            System.out.println("modchk for " + input2);
            if(2 % input2 == 0){
                System.out.print(input2 + " is even\n");
                }else{
                System.out.println(input2 + " is odd");
            }//endif input2
        }//end main
    }//end Modchk

int object is not iterable?

You can try to change for i in inp: into for i in range(1,inp): Iteration doesn't work with a single int. Instead, you need provide a range for it to run.

How to use Boost in Visual Studio 2010

In addition, there is something I find very useful. Use environment variables for your boost paths. (How to set environment variables in windows, link at bottom for 7,8,10) The BOOST_ROOT variable seems to be common place anymore and is set to the root path where you unzip boost.

Then in Properties, c++, general, Additional Include Directories use $(BOOST_ROOT). Then if/when you move to a newer version of the boost library you can update your environment variable to point to this newer version. As more of your projects, use boost you will not have to update the 'Additional Include Directories' for all of them.

You may also create a BOOST_LIB variable and point it to where the libs are staged. So likewise for the Linker->Additional Library Directories, you won't have to update projects. I have some old stuff built with vs10 and new stuff with vs14 so built both flavors of the boost lib to the same folder. So if I move a project from vs10 to vs14 I don't have to change the boost paths.

NOTE: If you change an environment variable it will not suddenly work in an open VS project. VS loads variables on startup. So you will have to close VS and reopen it.

Convert string with comma to integer

If someone is looking to sub out more than a comma I'm a fan of:

"1,200".chars.grep(/\d/).join.to_i

dunno about performance but, it is more flexible than a gsub, ie:

"1-200".chars.grep(/\d/).join.to_i

Checkout remote branch using git svn

Standard Subversion layout

Create a git clone of that includes your Subversion trunk, tags, and branches with

git svn clone http://svn.example.com/project -T trunk -b branches -t tags

The --stdlayout option is a nice shortcut if your Subversion repository uses the typical structure:

git svn clone http://svn.example.com/project --stdlayout

Make your git repository ignore everything the subversion repo does:

git svn show-ignore >> .git/info/exclude

You should now be able to see all the Subversion branches on the git side:

git branch -r

Say the name of the branch in Subversion is waldo. On the git side, you'd run

git checkout -b waldo-svn remotes/waldo

The -svn suffix is to avoid warnings of the form

warning: refname 'waldo' is ambiguous.

To update the git branch waldo-svn, run

git checkout waldo-svn
git svn rebase

Starting from a trunk-only checkout

To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config to contain

[svn-remote "svn-mybranch"]
        url = http://svn.example.com/project/branches/mybranch
        fetch = :refs/remotes/mybranch

You'll need to develop the habit of running

git svn fetch --fetch-all

to update all of what git svn thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run

git checkout -b mybranch-svn remotes/mybranch

For the branches from which you intend to git svn dcommit, keep their histories linear!


Further information

You may also be interested in reading an answer to a related question.

regex pattern to match the end of a string

Use the $ metacharacter to match the end of a string.

In Perl, this looks like:

my $str = 'red/white/blue';
my($last_match) = $str =~ m/.*\/(.*)$/;

Written in JavaScript, this looks like:

var str = 'red/white/blue'.match(/.*\/(.*)$/);

What's the point of 'meta viewport user-scalable=no' in the Google Maps API

From the v3 documentation (Developer's Guide > Concepts > Developing for Mobile Devices):

Android and iOS devices respect the following <meta> tag:

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

This setting specifies that the map should be displayed full-screen and should not be resizable by the user. Note that the iPhone's Safari browser requires this <meta> tag be included within the page's <head> element.

Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.0) and test app (23.0.1) differ

Project Rebuild solved my problem.

In Android studio in the toolbar.. Build>Rebuild Project.

Generating a PDF file from React Components

I used jsPDF and html-to-image.

You can check out the code on the below git repo.

Link

If you like, you can drop a star there??

select2 changing items dynamically

I fix the lack of example's library here:

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js">

http://jsfiddle.net/bbAU9/328/

Timeout a command in bash without unnecessary delay

I prefer "timelimit", which has a package at least in debian.

http://devel.ringlet.net/sysutils/timelimit/

It is a bit nicer than the coreutils "timeout" because it prints something when killing the process, and it also sends SIGKILL after some time by default.

Java String to Date object of the format "yyyy-mm-dd HH:mm:ss"

For future reference:

 yyyy => 4 digit year
 MM   => 2 digit month (you must type MM in ALL CAPS)
 dd   => 2 digit "day of the month"

 HH   => 2-digit "hour in day" (0 to 23)
 mm   => 2-digit minute (you must type mm in lowercase)
 ss   => 2-digit seconds
 SSS  => milliseconds

So "yyyy-MM-dd HH:mm:ss" returns "2018-01-05 09:49:32"

But "MMM dd, yyyy hh:mm a" returns "Jan 05, 2018 09:49 am"

The so-called examples at https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html show only output. They do not tell you what formats to use!

How do I get a range's address including the worksheet name, but not the workbook name, in Excel VBA?

The Address() worksheet function does exactly that. As it's not available through Application.WorksheetFunction, I came up with a solution using the Evaluate() method.

This solution let Excel deals with spaces and other funny characters in the sheet name, which is a nice advantage over the previous answers.

Example:

Evaluate("ADDRESS(" & rng.Row & "," & rng.Column & ",1,1,""" & _
    rng.Worksheet.Name & """)")

returns exactly "Sheet1!$A$1", with a Range object named rng referring the A1 cell in the Sheet1 worksheet.

This solution returns only the address of the first cell of a range, not the address of the whole range ("Sheet1!$A$1" vs "Sheet1!$A$1:$B$2"). So I use it in a custom function:

Public Function AddressEx(rng As Range) As String

    Dim strTmp As String

    strTmp = Evaluate("ADDRESS(" & rng.Row & "," & _
        rng.Column & ",1,1,""" & rng.Worksheet.Name & """)")

    If (rng.Count > 1) Then

        strTmp = strTmp & ":" & rng.Cells(rng.Count) _
            .Address(RowAbsolute:=True, ColumnAbsolute:=True)

    End If

    AddressEx = strTmp

End Function

The full documentation of the Address() worksheet function is available on the Office website: https://support.office.com/en-us/article/ADDRESS-function-D0C26C0D-3991-446B-8DE4-AB46431D4F89

Detecting arrow key presses in JavaScript

On key up and down call function. There are different codes for each key.

document.onkeydown = checkKey;

function checkKey(e) {

    e = e || window.event;

    if (e.keyCode == '38') {
        // up arrow
    }
    else if (e.keyCode == '40') {
        // down arrow
    }
    else if (e.keyCode == '37') {
       // left arrow
    }
    else if (e.keyCode == '39') {
       // right arrow
    }

}

SDK Manager.exe doesn't work

Had the same problem and tried everything I browse in several forums till I found a clue, then finally solved the problem.

Basically I installed the SDK and worked ok, then my Windows Vista crashed, on restart I run SDK again but it only opened a CMD window which closed immediately.

So here's a list of useless things I did:

  • Went to CMD "d:/java/android/tool" and execute "android.bat", didn't work and show an pointer exception error.
  • Reinstalled the whole thing JDK + SDK
  • Changed the system path to a new folder
  • I traced and deleted all android occurrences on Regedit

At this point I was seriously considering start learning objetive-c was not a bad idea, finally I did this:

  • delete ".android" folder from "c:/users/youruser/"
  • delete all files within "c:/users/youruser/AppData/Local/Temp"
  • reinstall SDK

it WORKED !! I'm not sure though if is necessary to uninstall SDK (since I had again to download all packages & platforms) and just clear the temp folder.

Hope this helps.

Chmod 777 to a folder and all contents

If by all permissions you mean 777

Navigate to folder and

chmod -R 777 .

Shortcut to Apply a Formula to an Entire Column in Excel

Select a range of cells (the entire column in this case), type in your formula, and hold down Ctrl while you press Enter. This places the formula in all selected cells.

Starting Docker as Daemon on Ubuntu

There are multiple popular repositories offering docker packages for Ubuntu. The package docker.io is (most likely) from the Ubuntu repository. Another popular one is http://get.docker.io/ubuntu which offers a package lxc-docker (I am running the latter because it ships updates faster). Make sure only one package is installed. Not quite sure if removal of the packages cleans up properly. If sudo service docker restart still does not work, you may have to clean up manually in /etc/.

Subtracting 2 lists in Python

import numpy as np
a = [2,2,2]
b = [1,1,1]
np.subtract(a,b)

What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

We should also use 'use strict' in the scope function to make sure that the code should be executed in "strict mode". Sample code shown below

(function() {
    'use strict';

    //Your code from here
})();

Disable a textbox using CSS

Just try this.

<asp:TextBox ID="tb" onkeypress="javascript:return false;" width="50px" runat="server"></asp:TextBox>

This won't allow any characters to be entered inside the TextBox.

How do I force detach Screen from another SSH session?

Short answer

  1. Reattach without ejecting others: screen -x
  2. Get list of displays: ^A *, select the one to disconnect, press d


Explained answer

Background: When I was looking for the solution with same problem description, I have always landed on this answer. I would like to provide more sensible solution. (For example: the other attached screen has a different size and a I cannot force resize it in my terminal.)

Note: PREFIX is usually ^A = ctrl+a

Note: the display may also be called:

  • "user front-end" (in at command manual in screen)
  • "client" (tmux vocabulary where this functionality is detach-client)
  • "terminal" (as we call the window in our user interface) /depending on

1. Reattach a session: screen -x

-x attach to a not detached screen session without detaching it

2. List displays of this session: PREFIX *

It is the default key binding for: PREFIX :displays. Performing it within the screen, identify the other display we want to disconnect (e.g. smaller size). (Your current display is displayed in brighter color/bold when not selected).

term-type   size         user interface           window       Perms
---------- ------- ---------- ----------------- ----------     -----
 screen     240x60         you@/dev/pts/2      nb  0(zsh)        rwx
 screen      78x40         you@/dev/pts/0      nb  0(zsh)        rwx

Using arrows ? ?, select the targeted display, press d If nothing happens, you tried to detach your own display and screen will not detach it. If it was another one, within a second or two, the entry will disappear.

Press ENTER to quit the listing.

Optionally: in order to make the content fit your screen, reflow: PREFIX F (uppercase F)

Excerpt from man page of screen:

displays

Shows a tabular listing of all currently connected user front-ends (displays). This is most useful for multiuser sessions. The following keys can be used in displays list:

  • mouseclick Move to the selected line. Available when "mousetrack" is set to on.
  • space Refresh the list
  • d Detach that display
  • D Power detach that display
  • C-g, enter, or escape Exit the list

Text Editor which shows \r\n?

vi can show all characters.

How to catch exception correctly from http.request()?

The RxJS functions need to be specifically imported. An easy way to do this is to import all of its features with import * as Rx from "rxjs/Rx"

Then make sure to access the Observable class as Rx.Observable.

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

I had a similar use case where I wanted to test a Spring Boot configured repository in isolation (in my case without Spring Security autoconfiguration which was failing my test). @SpringApplicationConfiguration uses SpringApplicationContextLoader and that has a JavaDoc stating

Can be used to test non-web features (like a repository layer) or start an fully-configured embedded servlet container.

However, like yourself, I could not work out how you are meant to configure the test to only test the repository layer using the main configuration entry point i.e. using your approach of @SpringApplicationConfiguration(classes = Application.class).

My solution was to create a completely new application context exclusive for testing. So in src/test/java I have two files in a sub-package called repo

  1. RepoIntegrationTest.java
  2. TestRepoConfig.java

where RepoIntegrationTest.java has

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestRepoConfig.class)
public class RepoIntegrationTest {

and TestRepoConfig.java has

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class TestRepoConfig {

It got me out of trouble but it would be really useful if anyone from the Spring Boot team could provide an alternative recommended solution

How to add a button programmatically in VBA next to some sheet cell data?

Suppose your function enters data in columns A and B and you want to a custom Userform to appear if the user selects a cell in column C. One way to do this is to use the SelectionChange event:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim clickRng As Range
    Dim lastRow As Long

    lastRow = Range("A1").End(xlDown).Row
    Set clickRng = Range("C1:C" & lastRow) //Dynamically set cells that can be clicked based on data in column A

    If Not Intersect(Target, clickRng) Is Nothing Then
        MyUserForm.Show //Launch custom userform
    End If

End Sub

Note that the userform will appear when a user selects any cell in Column C and you might want to populate each cell in Column C with something like "select cell to launch form" to make it obvious that the user needs to perform an action (having a button naturally suggests that it should be clicked)

SELECT *, COUNT(*) in SQLite

If what you want is the total number of records in the table appended to each row you can do something like

SELECT *
  FROM my_table
  CROSS JOIN (SELECT COUNT(*) AS COUNT_OF_RECS_IN_MY_TABLE
                FROM MY_TABLE)

document.getElementById("remember").visibility = "hidden"; not working on a checkbox

you can use

style="display:none"

Ex:

<asp:TextBox ID="txbProv" runat="server" style="display:none"></asp:TextBox>

How do I find if a string starts with another string in Ruby?

The method mentioned by steenslag is terse, and given the scope of the question it should be considered the correct answer. However it is also worth knowing that this can be achieved with a regular expression, which if you aren't already familiar with in Ruby, is an important skill to learn.

Have a play with Rubular: http://rubular.com/

But in this case, the following ruby statement will return true if the string on the left starts with 'abc'. The \A in the regex literal on the right means 'the beginning of the string'. Have a play with rubular - it will become clear how things work.

'abcdefg' =~  /\Aabc/ 

Create a new txt file using VB.NET

Here is a single line that will create (or overwrite) the file:

File.Create("C:\my files\2010\SomeFileName.txt").Dispose()

Note: calling Dispose() ensures that the reference to the file is closed.

No 'Access-Control-Allow-Origin' header is present on the requested resource error

Chrome doesn't allow you to integrate two different localhost,that's why we are getting this error. You just have to include Microsoft Visual Studio Web Api Core package from nuget manager.And add the two lines of code in WebApi project's in your WebApiConfig.cs file.

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

Then all done.

Paste in insert mode?

While in insert mode, you can use Ctrl-R {register}, where register can be:

  • + for the clipboard,
  • * for the X clipboard (last selected text in X),
  • " for the unnamed register (last delete or yank in Vim),
  • or a number of others (see :h registers).

Ctrl-R {register} inserts the text as if it were typed.

Ctrl-R Ctrl-O {register} inserts the text with the original indentation.

Ctrl-R Ctrl-P {register} inserts the text and auto-indents it.

Ctrl-O can be used to run any normal mode command before returning to insert mode, so
Ctrl-O "+p can also be used, for example.

For more information, view the documentation with :h i_ctrl-r

How to get HTTP response code for a URL in Java?

Efficient way to get data(With uneven payload) by scanner.

public static String getResponseFromHttpUrl(URL url) throws IOException {
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
        InputStream in = urlConnection.getInputStream();

        Scanner scanner = new Scanner(in);
        scanner.useDelimiter("\\A");  // Put entire content to next token string, Converts utf8 to 16, Handles buffering for different width packets

        boolean hasInput = scanner.hasNext();
        if (hasInput) {
            return scanner.next();
        } else {
            return null;
        }
    } finally {
        urlConnection.disconnect();
    }
}

Abstract methods in Java

If you use the java keyword abstract you cannot provide an implementation.

Sometimes this idea comes from having a background in C++ and mistaking the virtual keyword in C++ as being "almost the same" as the abstract keyword in Java.

In C++ virtual indicates that a method can be overridden and polymorphism will follow, but abstract in Java is not the same thing. In Java abstract is more like a pure virtual method, or one where the implementation must be provided by a subclass. Since Java supports polymorphism without the need to declare it, all methods are virtual from a C++ point of view. So if you want to provide a method that might be overridden, just write it as a "normal" method.

Now to protect a method from being overridden, Java uses the keyword final in coordination with the method declaration to indicate that subclasses cannot override the method.

Any way to make a WPF textblock selectable?


new TextBox
{
   Text = text,
   TextAlignment = TextAlignment.Center,
   TextWrapping = TextWrapping.Wrap,
   IsReadOnly = true,
   Background = Brushes.Transparent,
   BorderThickness = new Thickness()
         {
             Top = 0,
             Bottom = 0,
             Left = 0,
             Right = 0
         }
};

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

\ is an escape character in Python. \t gets interpreted as a tab. If you need \ character in a string, you have to use \\.

Your code should be:
test_file=open('c:\\Python27\\test.txt','r')

How can I show three columns per row?

Even though the above answer appears to be correct, I wanted to add a (hopefully) more readable example that also stays in 3 columns form at different widths:

_x000D_
_x000D_
.flex-row-container {_x000D_
    background: #aaa;_x000D_
    display: flex;_x000D_
    flex-wrap: wrap;_x000D_
    align-items: center;_x000D_
    justify-content: center;_x000D_
}_x000D_
.flex-row-container > .flex-row-item {_x000D_
    flex: 1 1 30%; /*grow | shrink | basis */_x000D_
    height: 100px;_x000D_
}_x000D_
_x000D_
.flex-row-item {_x000D_
  background-color: #fff4e6;_x000D_
  border: 1px solid #f76707;_x000D_
}
_x000D_
<div class="flex-row-container">_x000D_
  <div class="flex-row-item">1</div>_x000D_
  <div class="flex-row-item">2</div>_x000D_
  <div class="flex-row-item">3</div>_x000D_
  <div class="flex-row-item">4</div>_x000D_
  <div class="flex-row-item">5</div>_x000D_
  <div class="flex-row-item">6</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hope this helps someone else.

Resolve Git merge conflicts in favor of their changes during a pull

If you're already in conflicted state, and do not want to checkout path one by one. You may try

git merge --abort
git pull -X theirs

Convert string to hex-string in C#

According to this snippet here, this approach should be good for long strings:

private string StringToHex(string hexstring)
{
    StringBuilder sb = new StringBuilder();
    foreach (char t in hexstring)
    { 
        //Note: X for upper, x for lower case letters
        sb.Append(Convert.ToInt32(t).ToString("x")); 
    }
    return sb.ToString();
}

usage:

string result = StringToHex("Hello world"); //returns "48656c6c6f20776f726c64"

Another approach in one line

string input = "Hello world";
string result = String.Concat(input.Select(x => ((int)x).ToString("x")));

Convert HTML Character Back to Text Using Java Standard Library

As @jem suggested, it is possible to use jsoup.

With jSoup 1.8.3 it il possible to use the method Parser.unescapeEntities that retain the original html.

import org.jsoup.parser.Parser;
...
String html = Parser.unescapeEntities(original_html, false);

It seems that in some previous release this method is not present.

How to measure the a time-span in seconds using System.currentTimeMillis()?

TimeUnit.SECONDS.convert(start6, TimeUnit.MILLISECONDS);

Can an int be null in Java?

I'm no expert, but I do believe that the null equivalent for an int is 0.

For example, if you make an int[], each slot contains 0 as opposed to null, unless you set it to something else.

In some situations, this may be of use.

Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?

Python Extension. From the Python Docs:

The solution chosen by the Perl developers was to use (?...) as the extension syntax. ? immediately after a parenthesis was a syntax error because the ? would have nothing to repeat, so this didn’t introduce any compatibility problems. The characters immediately after the ? indicate what extension is being used, so (?=foo) is one thing (a positive lookahead assertion) and (?:foo) is something else (a non-capturing group containing the subexpression foo).

Python supports several of Perl’s extensions and adds an extension syntax to Perl’s extension syntax.If the first character after the question mark is a P, you know that it’s an extension that’s specific to Python

https://docs.python.org/3/howto/regex.html

Attach Authorization header for all axios requests

There are multiple ways to achieve this. Here, I have explained the two most common approaches.

1. You can use axios interceptors to intercept any requests and add authorization headers.

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    const token = store.getState().session.token;
    config.headers.Authorization =  token;

    return config;
});

2. From the documentation of axios you can see there is a mechanism available which allows you to set default header which will be sent with every request you make.

axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

So in your case:

axios.defaults.headers.common['Authorization'] = store.getState().session.token;

If you want, you can create a self-executable function which will set authorization header itself when the token is present in the store.

(function() {
     String token = store.getState().session.token;
     if (token) {
         axios.defaults.headers.common['Authorization'] = token;
     } else {
         axios.defaults.headers.common['Authorization'] = null;
         /*if setting null does not remove `Authorization` header then try     
           delete axios.defaults.headers.common['Authorization'];
         */
     }
})();

Now you no longer need to attach token manually to every request. You can place the above function in the file which is guaranteed to be executed every time (e.g: File which contains the routes).

Hope it helps :)

How to execute a Ruby script in Terminal?

Although its too late to answer this question, but still for those guys who came here to see the solution of same problem just like me and didn't get a satisfactory answer on this page, The reason is that you don't have your file in the form of .rb extension. You most probably have it in simple text mode. Let me elaborate. Binding up the whole solution on the page, here you go (assuming you filename is abc.rb or at least you created abc):

Type in terminal window:

cd ~/to/the/program/location
ruby abc.rb

and you are done

If the following error occurs

ruby: No such file or directory -- abc.rb (LoadError)

Then go to the directory in which you have the abc file, rename it as abc.rb Close gedit and reopen the file abc.rb. Apply the same set of commands and success!

Difference between jQuery parent(), parents() and closest() functions

The differences between the two, though subtle, are significant:

.closest()

  • Begins with the current element
  • Travels up the DOM tree until it finds a match for the supplied selector
  • The returned jQuery object contains zero or one element

.parents()

  • Begins with the parent element
  • Travels up the DOM tree to the document's root element, adding each ancestor element to a temporary collection; it then filters that collection based on a selector if one is supplied
  • The returned jQuery object contains zero, one, or multiple elements

From jQuery docs

Have border wrap around text

The easiest way to do it is to make the display an inline block

<div id='page' style='width: 600px'>
  <h1 style='border:2px black solid; font-size:42px; display: inline-block;'>Title</h1>
</div>

if you do this it should work

How do I mock a class without an interface?

With MoQ, you can mock concrete classes:

var mocked = new Mock<MyConcreteClass>();

but this allows you to override virtual code (methods and properties).

Call child component method from parent class - Angular

You can do this by using @ViewChild for more info check this link

With type selector

child component

@Component({
  selector: 'child-cmp',
  template: '<p>child</p>'
})
class ChildCmp {
  doSomething() {}
}

parent component

@Component({
  selector: 'some-cmp',
  template: '<child-cmp></child-cmp>',
  directives: [ChildCmp]
})
class SomeCmp {

  @ViewChild(ChildCmp) child:ChildCmp;

  ngAfterViewInit() {
    // child is set
    this.child.doSomething();
  }
}

With string selector

child component

@Component({
  selector: 'child-cmp',
  template: '<p>child</p>'
})
class ChildCmp {
  doSomething() {}
}

parent component

@Component({
  selector: 'some-cmp',
  template: '<child-cmp #child></child-cmp>',
  directives: [ChildCmp]
})
class SomeCmp {

  @ViewChild('child') child:ChildCmp;

  ngAfterViewInit() {
    // child is set
    this.child.doSomething();
  }
}

How do I get current URL in Selenium Webdriver 2 Python?

Selenium2Library has get_location():

import Selenium2Library
s = Selenium2Library.Selenium2Library()
url = s.get_location()

Why do we need boxing and unboxing in C#?

Why

To have a unified type system and allow value types to have a completely different representation of their underlying data from the way that reference types represent their underlying data (e.g., an int is just a bucket of thirty-two bits which is completely different than a reference type).

Think of it like this. You have a variable o of type object. And now you have an int and you want to put it into o. o is a reference to something somewhere, and the int is emphatically not a reference to something somewhere (after all, it's just a number). So, what you do is this: you make a new object that can store the int and then you assign a reference to that object to o. We call this process "boxing."

So, if you don't care about having a unified type system (i.e., reference types and value types have very different representations and you don't want a common way to "represent" the two) then you don't need boxing. If you don't care about having int represent their underlying value (i.e., instead have int be reference types too and just store a reference to their underlying value) then you don't need boxing.

where should I use it.

For example, the old collection type ArrayList only eats objects. That is, it only stores references to somethings that live somewhere. Without boxing you cannot put an int into such a collection. But with boxing, you can.

Now, in the days of generics you don't really need this and can generally go merrily along without thinking about the issue. But there are a few caveats to be aware of:

This is correct:

double e = 2.718281828459045;
int ee = (int)e;

This is not:

double e = 2.718281828459045;
object o = e; // box
int ee = (int)o; // runtime exception

Instead you must do this:

double e = 2.718281828459045;
object o = e; // box
int ee = (int)(double)o;

First we have to explicitly unbox the double ((double)o) and then cast that to an int.

What is the result of the following:

double e = 2.718281828459045;
double d = e;
object o1 = d;
object o2 = e;
Console.WriteLine(d == e);
Console.WriteLine(o1 == o2);

Think about it for a second before going on to the next sentence.

If you said True and False great! Wait, what? That's because == on reference types uses reference-equality which checks if the references are equal, not if the underlying values are equal. This is a dangerously easy mistake to make. Perhaps even more subtle

double e = 2.718281828459045;
object o1 = e;
object o2 = e;
Console.WriteLine(o1 == o2);

will also print False!

Better to say:

Console.WriteLine(o1.Equals(o2));

which will then, thankfully, print True.

One last subtlety:

[struct|class] Point {
    public int x, y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

Point p = new Point(1, 1);
object o = p;
p.x = 2;
Console.WriteLine(((Point)o).x);

What is the output? It depends! If Point is a struct then the output is 1 but if Point is a class then the output is 2! A boxing conversion makes a copy of the value being boxed explaining the difference in behavior.

Git merge without auto commit

I prefer this way so I don't need to remember any rare parameters.

git merge branch_name

It will then say your branch is ahead by "#" commits, you can now pop these commits off and put them into the working changes with the following:

git reset @~#

For example if after the merge it is 1 commit ahead, use:

git reset @~1

Note: On Windows, quotes are needed. (As Josh noted in comments) eg:

git reset "@~1"

How can you make a custom keyboard in Android?

Use KeyboardView:

KeyboardView kbd = new KeyboardView(context);
kbd.setKeyboard(new Keyboard(this, R.xml.custom));

kbd.setOnKeyboardActionListener(new OnKeyboardActionListener() {
    ....
}

now you have kbd which is a normal view.

The nice thing about this is that R.xml.custom refers to /res/xml/custom.xml, which defines in xml the layout of the keyboard. For more information on this file, look here: Keyboard, Keyboard.Row, Keyboard.Key.

Sticky and NON-Sticky sessions

When your website is served by only one web server, for each client-server pair, a session object is created and remains in the memory of the web server. All the requests from the client go to this web server and update this session object. If some data needs to be stored in the session object over the period of interaction, it is stored in this session object and stays there as long as the session exists.

However, if your website is served by multiple web servers which sit behind a load balancer, the load balancer decides which actual (physical) web-server should each request go to. For example, if there are 3 web servers A, B and C behind the load balancer, it is possible that www.mywebsite.com/index.jsp is served from server A, www.mywebsite.com/login.jsp is served from server B and www.mywebsite.com/accoutdetails.php are served from server C.

Now, if the requests are being served from (physically) 3 different servers, each server has created a session object for you and because these session objects sit on three independent boxes, there's no direct way of one knowing what is there in the session object of the other. In order to synchronize between these server sessions, you may have to write/read the session data into a layer which is common to all - like a DB. Now writing and reading data to/from a db for this use-case may not be a good idea. Now, here comes the role of sticky-session.

If the load balancer is instructed to use sticky sessions, all of your interactions will happen with the same physical server, even though other servers are present. Thus, your session object will be the same throughout your entire interaction with this website.

To summarize, In case of Sticky Sessions, all your requests will be directed to the same physical web server while in case of a non-sticky loadbalancer may choose any webserver to serve your requests.

As an example, you may read about Amazon's Elastic Load Balancer and sticky sessions here : http://aws.typepad.com/aws/2010/04/new-elastic-load-balancing-feature-sticky-sessions.html

Cycles in an Undirected Graph

You can solve it using DFS. Time complexity: O(n)

The essence of the algorithm is that if a connected component/graph does NOT contain a CYCLE, it will always be a TREE.See here for proof

Let us assume the graph has no cycle, i.e. it is a tree. And if we look at a tree, each edge from a node:

1.either reaches to its one and only parent, which is one level above it.

2.or reaches to its children, which are one level below it.

So if a node has any other edge which is not among the two described above, it will obviously connect the node to one of its ancestors other than its parent. This will form a CYCLE.

Now that the facts are clear, all you have to do is run a DFS for the graph (considering your graph is connected, otherwise do it for all unvisited vertices), and IF you find a neighbor of the node which is VISITED and NOT its parent, then my friend there is a CYCLE in the graph, and you're DONE.

You can keep track of parent by simply passing the parent as parameter when you do DFS for its neighbors. And Since you only need to examine n edges at the most, the time complexity will be O(n).

Hope the answer helped.

How can I check if a command exists in a shell script?

A function which works in both bash and zsh:

# Return the first pathname in $PATH for name in $1
function cmd_path () {
  if [[ $ZSH_VERSION ]]; then
    whence -cp "$1" 2> /dev/null
  else  # bash
     type -P "$1"  # No output if not in $PATH
  fi
}

Non-zero is returned if the command is not found in $PATH.

Prevent linebreak after </div>

I have many times succeeded to get div's without line breaks after them, by playing around with the float css attribute and the width css attribute.
Of course after working out the solution you have to test it in all browsers, and in each browser you have to re-size the windows to make sure that it works in all circumstances.

How to check if input date is equal to today's date?

The following solution compares the timestamp integer divided by the values of hours, minutes, seconds, millis.

var reducedToDay = function(date){return ~~(date.getTime()/(1000*60*60*24));};
return reducedToDay(date1) == reducedToDay(date2)

The tilde truncs the division result (see this article about integer division)

No restricted globals

Perhaps you could try passing location into the component as a prop. Below I use ...otherProps. This is the spread operator, and is valid but unneccessary if you passed in your props explicitly it's just there as a place holder for demonstration purposes. Also, research destructuring to understand where ({ location }) came from.

import React from 'react';
import withRouter from 'react-router-dom';

const MyComponent = ({ location, ...otherProps }) => (whatever you want to render)


export withRouter(MyComponent);

How to resolve Nodejs: Error: ENOENT: no such file or directory

92% additional asset processing scripts-webpack-plugin× ?wdm?: Error: ENOENT: no such file or directory, open....==> if anyone faced to such error, you should do followings: 1) you should check the if the file path is correct in angular.json file.

 "scripts": [
          "node_modules/jquery/dist/jquery.min.js",
          "node_modules/bootstrap/dist/js/bootstrap.js"
        ],

2) you should press crtl+c and re run the project.

How to convert JSON to string?

JSON.stringify()

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

javax.naming.NameNotFoundException: Name is not bound in this Context. Unable to find

ugh, just to iterate over my own case, which gave out approximately the same error - in the Resource declaration (server.xml) make sure to NOT omit driverClassName, and that e.g. for Oracle it is "oracle.jdbc.OracleDriver", and that the right JAR file (e.g. ojdbc14.jar) exists in %CATALINA_HOME%/lib

Java 8 stream map to list of keys sorted by values

You say you want to sort by value, but you don't have that in your code. Pass a lambda (or method reference) to sorted to tell it how you want to sort.

And you want to get the keys; use map to transform entries to keys.

List<Type> types = countByType.entrySet().stream()
        .sorted(Comparator.comparing(Map.Entry::getValue))
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());

Creating/writing into a new file in Qt

QFile file("test.txt");
/*
 *If file does not exist, it will be created
 */
if (!file.open(QIODevice::ReadOnly | QIODevice::Text | QIODevice::ReadWrite))
{
    qDebug() << "FAILED TO CREATE FILE / FILE DOES NOT EXIST";
}

/*for Reading line by line from text file*/
while (!file.atEnd()) {
    QByteArray line = file.readLine();
    qDebug() << "read output - " << line;
}

/*for writing line by line to text file */
if (file.open(QIODevice::ReadWrite))
{
    QTextStream stream(&file);
    stream << "1_XYZ"<<endl;
    stream << "2_XYZ"<<endl;
}

Append values to query string

Note you can add the Microsoft.AspNetCore.WebUtilities nuget package from Microsoft and then use this to append values to query string:

QueryHelpers.AddQueryString(longurl, "action", "login1")
QueryHelpers.AddQueryString(longurl, new Dictionary<string, string> { { "action", "login1" }, { "attempts", "11" } });

Python memory leaks

Have a look at this article: Tracing python memory leaks

Also, note that the garbage collection module actually can have debug flags set. Look at the set_debug function. Additionally, look at this code by Gnibbler for determining the types of objects that have been created after a call.

Div Size Automatically size of content

As far as I know, display: inline-block is what you probably need. That will make it seem like it's sort of inline but still allow you to use things like margins and such.

Child with max-height: 100% overflows parent

The closest I can get to this is this example:

http://jsfiddle.net/YRFJQ/1/

or

.container {  
  background: blue; 
  border: 10px solid blue; 
  max-height: 200px; 
  max-width: 200px; 
  overflow:hidden;
  box-sizing:border-box;
}

img { 
  display: block;
  max-height: 100%; 
  max-width: 100%; 
}

The main problem is that the height takes the percentage of the containers height, so it is looking for an explicitly set height in the parent container, not it's max-height.

The only way round this to some extent I can see is the fiddle above where you can hide the overflow, but then the padding still acts as visible space for the image to flow into, and so replacing with a solid border works instead (and then adding border-box to make it 200px if that's the width you need)

Not sure if this would fit with what you need it for, but the best I can seem to get to.

How to run a .awk file?

If you put #!/bin/awk -f on the first line of your AWK script it is easier. Plus editors like Vim and ... will recognize the file as an AWK script and you can colorize. :)

#!/bin/awk -f
BEGIN {}  # Begin section
{}        # Loop section
END{}     # End section

Change the file to be executable by running:

chmod ugo+x ./awk-script

and you can then call your AWK script like this:

`$ echo "something" | ./awk-script`

How to Check byte array empty or not?

You must swap the order of your test:

From:

if (Attachment.Length > 0 && Attachment != null)

To:

if (Attachment != null && Attachment.Length > 0 )

The first version attempts to dereference Attachment first and therefore throws if it's null. The second version will check for nullness first and only go on to check the length if it's not null (due to "boolean short-circuiting").


[EDIT] I come from the future to tell you that with later versions of C# you can use a "null conditional operator" to simplify the code above to:

if (Attachment?.Length > 0)
        

Select multiple records based on list of Id's with linq

That should be simple. Try this:

var idList = new int[1, 2, 3, 4, 5];
var userProfiles = _dataContext.UserProfile.Where(e => idList.Contains(e));

How to fire a button click event from JavaScript in ASP.NET

I can make things work this way:

inside javascript junction that is executed by the html button:

document.getElementById("<%= Button2.ClientID %>").click();

ASP button inside div:

<div id="submitBtn" style="display: none;">
   <asp:Button ID="Button2" runat="server" Text="Submit" ValidationGroup="AllValidators" OnClick="Button2_Click" />
</div>

Everything runs from the .cs file except that the code below doesn't execute. There is no message box and redirect to the same page (refresh all boxes):

 int count = cmd.ExecuteNonQuery();
 if (count > 0)
 {
   cmd2.CommandText = insertSuperRoster;
   cmd2.Connection = con;
   cmd2.ExecuteNonQuery();
   string url = "VaccineRefusal.aspx";
   ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "alert('Data Inserted Successfully!');window.location.href = '" + url + "';", true);
  }

Any ideas why these lines won't execute?

How to find out the location of currently used MySQL configuration file in linux

If you are using terminal just type the following:

locate my.cnf

How to view query error in PDO PHP

I'm guessing that your complaint is that the exception is not firing. PDO is most likely configured to not throw exceptions. Enable them with this:

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

Sending message through WhatsApp

This is what worked for me :

        Uri uri = Uri.parse("https://api.whatsapp.com/send?phone=" + "<number>" + "&text=" + "Hello WhatsApp!!");
        Intent sendIntent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(sendIntent);

How do I create a comma-separated list from an array in PHP?

A functional solution would go like this:

$fruit = array('apple', 'banana', 'pear', 'grape');
$sep = ','; 

array_reduce(
    $fruits,
    function($fruitsStr, $fruit) use ($sep) {
        return (('' == $fruitsStr) ? $fruit : $fruitsStr . $sep . $fruit);
    },
    ''
);

How do I copy an entire directory of files into an existing directory using Python?

Here is my version of the same task::

import os, glob, shutil

def make_dir(path):
    if not os.path.isdir(path):
        os.mkdir(path)


def copy_dir(source_item, destination_item):
    if os.path.isdir(source_item):
        make_dir(destination_item)
        sub_items = glob.glob(source_item + '/*')
        for sub_item in sub_items:
            copy_dir(sub_item, destination_item + '/' + sub_item.split('/')[-1])
    else:
        shutil.copy(source_item, destination_item)

How do I select text nodes with jQuery?

For me, plain old .contents() appeared to work to return the text nodes, just have to be careful with your selectors so that you know they will be text nodes.

For example, this wrapped all the text content of the TDs in my table with pre tags and had no problems.

jQuery("#resultTable td").content().wrap("<pre/>")

Why do you use typedef when declaring an enum in C++?

In C, it is good style because you can change the type to something besides an enum.

typedef enum e_TokenType
{
    blah1   = 0x00000000,
    blah2   = 0X01000000,
    blah3   = 0X02000000
} TokenType;

foo(enum e_TokenType token);  /* this can only be passed as an enum */

foo(TokenType token); /* TokenType can be defined to something else later
                         without changing this declaration */

In C++ you can define the enum so that it will compile as C++ or C.

UDP vs TCP, how much faster is it?

UDP is faster than TCP, and the simple reason is because its non-existent acknowledge packet (ACK) that permits a continuous packet stream, instead of TCP that acknowledges a set of packets, calculated by using the TCP window size and round-trip time (RTT).

For more information, I recommend the simple, but very comprehensible Skullbox explanation (TCP vs. UDP)

CSS center content inside div

The problem is that you assigned a fixed width to your .wrap DIV. The DIV itself is centered (you can see that when you add a border to it) but the DIV is just too wide. In other words the content does not fill the whole width of the DIV.

To solve the problem you have to make sure, that the .wrap DIV is only as wide as it's content.

To achieve that you have to remove the floating in the content elements and set the display property of the block levels elements to inline:

#partners .wrap {
 display: inline;
} 

.wrap { margin: 0 auto; position: relative;}

#partners h2 {
color: #A6A5A5;
font-weight: normal;
margin: 2px 15px 0 0;
display: inline;
}

#partners ul {
display: inline;
}

#partners li {display: inline}

ul { list-style-position: outside; list-style-type: none; }

Most efficient way to get table row count

If you do not have privilege for "Show Status" then, The best option is to, create two triggers and a new table which keeps the row count of your billion records table.

Example:

TableA >> Billion Records
TableB >> 1 Column and 1 Row

Whenever there is insert query on TableA(InsertTrigger), Increment the row value by 1 TableB
Whenever there is delete query on TableA(DeleteTrigger), Decrement the row value by 1 in TableB

Make UINavigationBar transparent

C# / Xamarin Solution

NavigationController.NavigationBar.SetBackgroundImage(new UIImage(), UIBarMetrics.Default);
NavigationController.NavigationBar.ShadowImage = new UIImage();
NavigationController.NavigationBar.Translucent = true;

Remove a marker from a GoogleMap

Try this, it is updating the current location, and it works fine.

        public void onLocationChanged(@NonNull Location location) {               
        //here we update the location on the map
        
        LatLng myActualLocation = new LatLng(location.getLatitude(), location.getLongitude());
        
        if (markerName!=null){  // marker name is declared as a gloval variable.
            markerName.remove();
        }
        
        markerName = mMap.addMarker(new MarkerOptions().position(myActualLocation).title("Marker Miami").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
        
        // mMap.addMarker(new MarkerOptions().position(myActualLocation).title("Marker Miami").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myActualLocation,18));
        
        }

Whats the CSS to make something go to the next line in the page?

It depends why the something is on the same line in the first place.

clear in the case of floats, display: block in the case of inline content naturally flowing, nothing will defeat position: absolute as the previous element will be taken out of the normal flow by it.

Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type

I had this issue when I added react-router-dom to the new CRA app using typescript. After I added @types/react-router, the issue was fixed.

Transition of background-color

To me, it is better to put the transition codes with the original/minimum selectors than with the :hover or any other additional selectors:

_x000D_
_x000D_
#content #nav a {_x000D_
    background-color: #FF0;_x000D_
    _x000D_
    -webkit-transition: background-color 1000ms linear;_x000D_
    -moz-transition: background-color 1000ms linear;_x000D_
    -o-transition: background-color 1000ms linear;_x000D_
    -ms-transition: background-color 1000ms linear;_x000D_
    transition: background-color 1000ms linear;_x000D_
}_x000D_
_x000D_
#content #nav a:hover {_x000D_
    background-color: #AD310B;_x000D_
}
_x000D_
<div id="content">_x000D_
    <div id="nav">_x000D_
        <a href="#link1">Link 1</a>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

CSS border less than 1px

try giving border in % for exapmle 0.1% according to your need.

Maven does not find JUnit tests to run

I faced the same issue , it resolved by below change in pom.xml :

<build>
    <testSourceDirectory>test</testSourceDirectory>

...

changed to:

<build>
    <testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>

How to show an alert box in PHP?

use this code

echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';

The problem was:

  1. you missed "
  2. It should be alert not alery

What does += mean in Python?

+= is the in-place addition operator.

It's the same as doing cnt = cnt + 1. For example:

>>> cnt = 0
>>> cnt += 2
>>> print cnt
2
>>> cnt += 42
>>> print cnt
44

The operator is often used in a similar fashion to the ++ operator in C-ish languages, to increment a variable by one in a loop (i += 1)

There are similar operator for subtraction/multiplication/division/power and others:

i -= 1 # same as i = i - 1
i *= 2 # i = i * 2
i /= 3 # i = i / 3
i **= 4 # i = i ** 4

The += operator also works on strings, for example:

>>> s = "Hi"
>>> s += " there"
>>> print s
Hi there

People tend to recommend against doing this for performance reason, but for the most scripts this really isn't an issue. To quote from the "Sequence Types" docs:

  1. If s and t are both strings, some Python implementations such as CPython can usually perform an in-place optimization for assignments of the form s=s+t or s+=t. When applicable, this optimization makes quadratic run-time much less likely. This optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations.

The str.join() method refers to doing the following:

mysentence = []
for x in range(100):
    mysentence.append("test")
" ".join(mysentence)

..instead of the more obvious:

mysentence = ""
for x in range(100):
    mysentence += " test"

The problem with the later is (aside from the leading-space), depending on the Python implementation, the Python interpreter will have to make a new copy of the string in memory every time you append (because strings are immutable), which will get progressively slower the longer the string to append is.. Whereas appending to a list then joining it together into a string is a consistent speed (regardless of implementation)

If you're doing basic string manipulation, don't worry about it. If you see a loop which is basically just appending to a string, consider constructing an array, then "".join()'ing it.

Checking if a string can be converted to float in Python

Try to convert to float. If there is an error, print the ValueError exception.

try:
    x = float('1.23')
    print('val=',x)
    y = float('abc')
    print('val=',y)
except ValueError as err:
    print('floatErr;',err)

Output:

val= 1.23
floatErr: could not convert string to float: 'abc'

How to resize html canvas element?

This worked for me just now:

<canvas id="c" height="100" width="100" style="border:1px solid red"></canvas>
<script>
var c = document.getElementById('c');
alert(c.height + ' ' + c.width);
c.height = 200;
c.width = 200;
alert(c.height + ' ' + c.width);
</script>

Opening Chrome From Command Line

C:\>start chrome "http://site1.com" works on Windows Vista.

Using app.config in .Net Core

  1. You can use Microsoft.Extensions.Configuration API with any .NET Core app, not only with ASP.NET Core app. Look into sample provided in the link, that shows how to read configs in the console app.

  2. In most cases, the JSON source (read as .json file) is the most suitable config source.

    Note: don't be confused when someone says that config file should be appsettings.json. You can use any file name, that is suitable for you and file location may be different - there are no specific rules.

    But, as the real world is complicated, there are a lot of different configuration providers:

    • File formats (INI, JSON, and XML)
    • Command-line arguments
    • Environment variables

    and so on. You even could use/write a custom provider.

  3. Actually, app.config configuration file was an XML file. So you can read settings from it using XML configuration provider (source on github, nuget link). But keep in mind, it will be used only as a configuration source - any logic how your app behaves should be implemented by you. Configuration Provider will not change 'settings' and set policies for your apps, but only read data from the file.

Assign format of DateTime with data annotations?

Did you try this?

[DataType(DataType.Date)]

In Python, how do you convert seconds since epoch to a `datetime` object?

For those that want it ISO 8601 compliant, since the other solutions do not have the T separator nor the time offset (except Meistro's answer):

from datetime import datetime, timezone
result = datetime.fromtimestamp(1463288494, timezone.utc).isoformat('T', 'microseconds')
print(result) # 2016-05-15T05:01:34.000000+00:00

Note, I use fromtimestamp because if I used utcfromtimestamp I would need to chain on .astimezone(...) anyway to get the offset.

If you don't want to go all the way to microseconds you can choose a different unit with the isoformat() method.

Drop all tables command

Once you've dropped all the tables (and the indexes will disappear when the table goes) then there's nothing left in a SQLite database as far as I know, although the file doesn't seem to shrink (from a quick test I just did).

So deleting the file would seem to be fastest - it should just be recreated when your app tries to access the db file.

AngularJs: How to check for changes in file input fields?

You can simply add the below code in onchange and it will detect change. you can write a function on X click or something to remove file data..

document.getElementById(id).value = "";

Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?

This is an old post but maybe this could help people to complete the CORS problem. To complete the basic authorization problem you should avoid authorization for OPTIONS requests in your server. This is an Apache configuration example. Just add something like this in your VirtualHost or Location.

<LimitExcept OPTIONS>
    AuthType Basic
    AuthName <AUTH_NAME>
    Require valid-user
    AuthUserFile <FILE_PATH>
</LimitExcept>

Interfaces with static fields in java for sharing 'constants'

Given the advantage of hindsight, we can see that Java is broken in many ways. One major failing of Java is the restriction of interfaces to abstract methods and static final fields. Newer, more sophisticated OO languages like Scala subsume interfaces by traits which can (and typically do) include concrete methods, which may have arity zero (constants!). For an exposition on traits as units of composable behavior, see http://scg.unibe.ch/archive/papers/Scha03aTraits.pdf. For a short description of how traits in Scala compare with interfaces in Java, see http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-5. In the context of teaching OO design, simplistic rules like asserting that interfaces should never include static fields are silly. Many traits naturally include constants and these constants are appropriately part of the public "interface" supported by the trait. In writing Java code, there is no clean, elegant way to represent traits, but using static final fields within interfaces is often part of a good workaround.

How do I convert a C# List<string[]> to a Javascript array?

JSON is valid JavaScript Object anyway, while you are printing JavaScript itself, you don't need to encode/decode JSON further once it is converted to JSON.

<script type="text/javascript">
    var addresses = @Html.Raw(Model.Addresses);
</script>

Following will be printed, and it is valid JavaScript Expression.

<script type="text/javascript">
    var addresses = [["123 Street St.","City","CA","12345"],["456 Street St.","City","UT","12345"],["789 Street St.","City","OR","12345"]];
</script>

RegEx to extract all matches from string using RegExp.exec

Continue calling re.exec(s) in a loop to obtain all the matches:

var re = /\s*([^[:]+):\"([^"]+)"/g;
var s = '[description:"aoeu" uuid:"123sth"]';
var m;

do {
    m = re.exec(s);
    if (m) {
        console.log(m[1], m[2]);
    }
} while (m);

Try it with this JSFiddle: https://jsfiddle.net/7yS2V/

Launch Bootstrap Modal on page load

Update 2020 - Bootstrap 4

The modal markup has changed slightly for Bootstrap 4. Here's how you can open the modal on page load, and optionally delay display of the modal...

$(window).on('load',function(){
    var delayMs = 1500; // delay in milliseconds

    setTimeout(function(){
        $('#myModal').modal('show');
    }, delayMs);
});    

<div class="modal fade" id="myModal">
      <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">My Modal</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">
                    ...
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary mx-auto" data-dismiss="modal">Close</button>
                </div>
            </div>
      </div>
</div>

Demo on Codeply

Difference between onStart() and onResume()

Hopefully a simple explanation : -

onStart() -> called when the activity becomes visible, but might not be in the foreground (e.g. an AlertFragment is on top or any other possible use case).

onResume() -> called when the activity is in the foreground, or the user can interact with the Activity.

How do I split a string so I can access item x?



    Alter Function dbo.fn_Split
    (
    @Expression nvarchar(max),
    @Delimiter  nvarchar(20) = ',',
    @Qualifier  char(1) = Null
    )
    RETURNS @Results TABLE (id int IDENTITY(1,1), value nvarchar(max))
    AS
    BEGIN
       /* USAGE
            Select * From dbo.fn_Split('apple pear grape banana orange honeydew cantalope 3 2 1 4', ' ', Null)
            Select * From dbo.fn_Split('1,abc,"Doe, John",4', ',', '"')
            Select * From dbo.fn_Split('Hello 0,"&""&&&&', ',', '"')
       */

       -- Declare Variables
       DECLARE
          @X     xml,
          @Temp  nvarchar(max),
          @Temp2 nvarchar(max),
          @Start int,
          @End   int

       -- HTML Encode @Expression
       Select @Expression = (Select @Expression For XML Path(''))

       -- Find all occurences of @Delimiter within @Qualifier and replace with |||***|||
       While PATINDEX('%' + @Qualifier + '%', @Expression) > 0 AND Len(IsNull(@Qualifier, '')) > 0
       BEGIN
          Select
             -- Starting character position of @Qualifier
             @Start = PATINDEX('%' + @Qualifier + '%', @Expression),
             -- @Expression starting at the @Start position
             @Temp = SubString(@Expression, @Start + 1, LEN(@Expression)-@Start+1),
             -- Next position of @Qualifier within @Expression
             @End = PATINDEX('%' + @Qualifier + '%', @Temp) - 1,
             -- The part of Expression found between the @Qualifiers
             @Temp2 = Case When @End < 0 Then @Temp Else Left(@Temp, @End) End,
             -- New @Expression
             @Expression = REPLACE(@Expression,
                                   @Qualifier + @Temp2 + Case When @End < 0 Then '' Else @Qualifier End,
                                   Replace(@Temp2, @Delimiter, '|||***|||')
                           )
       END

       -- Replace all occurences of @Delimiter within @Expression with '</fn_Split><fn_Split>'
       -- And convert it to XML so we can select from it
       SET
          @X = Cast('<fn_Split>' +
                    Replace(@Expression, @Delimiter, '</fn_Split><fn_Split>') +
                    '</fn_Split>' as xml)

       -- Insert into our returnable table replacing '|||***|||' back to @Delimiter
       INSERT @Results
       SELECT
          "Value" = LTRIM(RTrim(Replace(C.value('.', 'nvarchar(max)'), '|||***|||', @Delimiter)))
       FROM
          @X.nodes('fn_Split') as X(C)

       -- Return our temp table
       RETURN
    END

How to check Oracle database for long running queries

select sq.PARSING_SCHEMA_NAME, sq.LAST_LOAD_TIME, sq.ELAPSED_TIME, sq.ROWS_PROCESSED, ltrim(sq.sql_text), sq.SQL_FULLTEXT
  from v$sql sq, v$session se
 order by sq.ELAPSED_TIME desc, sq.LAST_LOAD_TIME desc;

How can I color a UIImage in Swift?

There's a built in method to obtain a UIImage that is automatically rendered in template mode. This uses a view's tintColor to color the image:

let templateImage = originalImage.imageWithRenderingMode(UIImageRenderingModeAlwaysTemplate)
myImageView.image = templateImage
myImageView.tintColor = UIColor.orangeColor()

When is std::weak_ptr useful?

I see std::weak_ptr<T> as a handle to a std::shared_ptr<T>: It allows me to get the std::shared_ptr<T> if it still exists, but it will not extend its lifetime. There are several scenarios when such point of view is useful:

// Some sort of image; very expensive to create.
std::shared_ptr< Texture > texture;

// A Widget should be able to quickly get a handle to a Texture. On the
// other hand, I don't want to keep Textures around just because a widget
// may need it.

struct Widget {
    std::weak_ptr< Texture > texture_handle;
    void render() {
        if (auto texture = texture_handle.get(); texture) {
            // do stuff with texture. Warning: `texture`
            // is now extending the lifetime because it
            // is a std::shared_ptr< Texture >.
        } else {
            // gracefully degrade; there's no texture.
        }
    }
};

Another important scenario is to break cycles in data structures.

// Asking for trouble because a node owns the next node, and the next node owns
// the previous node: memory leak; no destructors automatically called.
struct Node {
    std::shared_ptr< Node > next;
    std::shared_ptr< Node > prev;
};

// Asking for trouble because a parent owns its children and children own their
// parents: memory leak; no destructors automatically called.
struct Node {
    std::shared_ptr< Node > parent;
    std::shared_ptr< Node > left_child;
    std::shared_ptr< Node > right_child;
};

// Better: break dependencies using a std::weak_ptr (but not best way to do it;
// see Herb Sutter's talk).
struct Node {
    std::shared_ptr< Node > next;
    std::weak_ptr< Node > prev;
};

// Better: break dependencies using a std::weak_ptr (but not best way to do it;
// see Herb Sutter's talk).
struct Node {
    std::weak_ptr< Node > parent;
    std::shared_ptr< Node > left_child;
    std::shared_ptr< Node > right_child;
};

Herb Sutter has an excellent talk that explains the best use of language features (in this case smart pointers) to ensure Leak Freedom by Default (meaning: everything clicks in place by construction; you can hardly screw it up). It is a must watch.

How to find out what is locking my tables?

Take a look at the following system stored procedures, which you can run in SQLServer Management Studio (SSMS):

  • sp_who
  • sp_lock

Also, in SSMS, you can view locks and processes in different ways:

enter image description here

Different versions of SSMS put the activity monitor in different places. For example, SSMS 2008 and 2012 have it in the context menu when you right-click on a server node.