Programs & Examples On #Duffs device

How to access the request body when POSTing using Node.js and Express?

Starting from express v4.16 there is no need to require any additional modules, just use the built-in JSON middleware:

app.use(express.json())

Like this:

const express = require('express')

app.use(express.json())    // <==== parse request body as JSON

app.listen(8080)

app.post('/test', (req, res) => {
  res.json({requestBody: req.body})  // <==== req.body will be a parsed JSON object
})

Note - body-parser, on which this depends, is already included with express.

Also don't forget to send the header Content-Type: application/json

Count the items from a IEnumerable<T> without iterating?

IEnumerable cannot count without iterating.

Under "normal" circumstances, it would be possible for classes implementing IEnumerable or IEnumerable<T>, such as List<T>, to implement the Count method by returning the List<T>.Count property. However, the Count method is not actually a method defined on the IEnumerable<T> or IEnumerable interface. (The only one that is, in fact, is GetEnumerator.) And this means that a class-specific implementation cannot be provided for it.

Rather, Count it is an extension method, defined on the static class Enumerable. This means it can be called on any instance of an IEnumerable<T> derived class, regardless of that class's implementation. But it also means it is implemented in a single place, external to any of those classes. Which of course means that it must be implemented in a way that is completely independent of these class' internals. The only such way to do counting is via iteration.

How to commit and rollback transaction in sql server?

Don't use @@ERROR, use BEGIN TRY/BEGIN CATCH instead. See this article: Exception handling and nested transactions for a sample procedure:

create procedure [usp_my_procedure_name]
as
begin
    set nocount on;
    declare @trancount int;
    set @trancount = @@trancount;
    begin try
        if @trancount = 0
            begin transaction
        else
            save transaction usp_my_procedure_name;

        -- Do the actual work here

lbexit:
        if @trancount = 0   
            commit;
    end try
    begin catch
        declare @error int, @message varchar(4000), @xstate int;
        select @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
        if @xstate = -1
            rollback;
        if @xstate = 1 and @trancount = 0
            rollback
        if @xstate = 1 and @trancount > 0
            rollback transaction usp_my_procedure_name;

        raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
        return;
    end catch   
end

Build Step Progress Bar (css and jquery)

This is what I did:

  1. Create jQuery .progressbar() to load a div into a progress bar.
  2. Create the step title on the bottom of the progress bar. Position them with CSS.
  3. Then I create function in jQuery that change the value of the progressbar everytime user move on to next step.

HTML

<div id="divProgress"></div>
<div id="divStepTitle">
    <span class="spanStep">Step 1</span> <span class="spanStep">Step 2</span> <span class="spanStep">Step 3</span>
</div>

<input type="button" id="btnPrev" name="btnPrev" value="Prev" />
<input type="button" id="btnNext" name="btnNext" value="Next" />

CSS

#divProgress
{
    width: 600px;
}

#divStepTitle
{
    width: 600px;
}

.spanStep
{
    text-align: center;
    width: 200px;
}

Javascript/jQuery

var progress = 0;

$(function({
    //set step progress bar
    $("#divProgress").progressbar();

    //event handler for prev and next button
    $("#btnPrev, #btnNext").click(function(){
        step($(this));
    });
});

function step(obj)
{
    //switch to prev/next page
    if (obj.val() == "Prev")
    {
        //set new value for progress bar
        progress -= 20;
        $("#divProgress").progressbar({ value: progress });

        //do extra step for showing previous page
    }
    else if (obj.val() == "Next")
    {
        //set new value for progress bar
        progress += 20;
        $("#divProgress").progressbar({ value: progress });

        //do extra step for showing next page
    }
}

DIV table colspan: how?

I would imagine that this would be covered by CSS Tables, a specification which, while mentioned on the CSS homepage, appears to currently be at a state of "not yet published in any form"

In practical terms, you can't achieve this at present.

What is more efficient? Using pow to square or just multiply it with itself?

The most efficient way is to consider the exponential growth of the multiplications. Check this code for p^q:

template <typename T>
T expt(T p, unsigned q){
    T r =1;
    while (q != 0) {
        if (q % 2 == 1) {    // if q is odd
            r *= p;
            q--;
        }
        p *= p;
        q /= 2;
    }
    return r;
}

clearInterval() not working

There are errors in your functions, but the first thing you should do, is to set the body tag correctly:

<body>
<p><span id="go" class="georgia">go</span> Italian</p>
<p>
    <button id="on" type="button" value="turn on">turn on</button>
    <button id="off" type="button" value="turn off">turn off</button>
</p>
</body>

<script>....</script>

The problem sometimes may be, that you call 'var text' and the other vars only once, when the script starts. If you make changements to the DOM, this static solution may be harmful.

So you could try this (this is more flexible approach and using function parameters, so you can call the functions on any element):

<body>
<p><span id="go" class="georgia">go</span> Italian</p>
<p>
    <button type="button" value="turn on"
         onclick=turnOn("go")>turn on</button>
    <button type="button" value="turn off"
         onclick=turnOff()>turn off</button>
</p>
</body>

<script type="text/JavaScript">
var interval;

var turnOn = function(elementId){
    interval = setInterval(function(){fontChange(elementId);}, 500);
};

var turnOff = function(){
    clearInterval(interval);
};

var fontChange = function(elementId) {
    var text = document.getElementById(elementId);
    switch(text.className) {
        case "georgia":
            text.className = "arial";
            break;
        case "arial":
            text.className = "courierNew";
            break;
        case "courierNew":
            text.className = "georgia";
            break;      
    }
};
</script>

You don't need this anymore, so delete it:

var text = document.getElementById("go");
var on = document.getElementById("on");
var off = document.getElementById("off");

This is dynamic code, meaning JS code which runs generic and doesn't adress elements directly. I like this approach more than defining an own function for every div element. ;)

How to process each output line in a loop?

For those looking for a one-liner:

grep xyz abc.txt | while read -r line; do echo "Processing $line"; done

Create code first, many to many, with additional fields in association table

The code provided by this answer is right, but incomplete, I've tested it. There are missing properties in "UserEmail" class:

    public UserTest UserTest { get; set; }
    public EmailTest EmailTest { get; set; }

I post the code I've tested if someone is interested. Regards

using System.Data.Entity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

#region example2
public class UserTest
{
    public int UserTestID { get; set; }
    public string UserTestname { get; set; }
    public string Password { get; set; }

    public ICollection<UserTestEmailTest> UserTestEmailTests { get; set; }

    public static void DoSomeTest(ApplicationDbContext context)
    {

        for (int i = 0; i < 5; i++)
        {
            var user = context.UserTest.Add(new UserTest() { UserTestname = "Test" + i });
            var address = context.EmailTest.Add(new EmailTest() { Address = "address@" + i });
        }
        context.SaveChanges();

        foreach (var user in context.UserTest.Include(t => t.UserTestEmailTests))
        {
            foreach (var address in context.EmailTest)
            {
                user.UserTestEmailTests.Add(new UserTestEmailTest() { UserTest = user, EmailTest = address, n1 = user.UserTestID, n2 = address.EmailTestID });
            }
        }
        context.SaveChanges();
    }
}

public class EmailTest
{
    public int EmailTestID { get; set; }
    public string Address { get; set; }

    public ICollection<UserTestEmailTest> UserTestEmailTests { get; set; }
}

public class UserTestEmailTest
{
    public int UserTestID { get; set; }
    public UserTest UserTest { get; set; }
    public int EmailTestID { get; set; }
    public EmailTest EmailTest { get; set; }
    public int n1 { get; set; }
    public int n2 { get; set; }


    //Call this code from ApplicationDbContext.ConfigureMapping
    //and add this lines as well:
    //public System.Data.Entity.DbSet<yournamespace.UserTest> UserTest { get; set; }
    //public System.Data.Entity.DbSet<yournamespace.EmailTest> EmailTest { get; set; }
    internal static void RelateFluent(System.Data.Entity.DbModelBuilder builder)
    {
        // Primary keys
        builder.Entity<UserTest>().HasKey(q => q.UserTestID);
        builder.Entity<EmailTest>().HasKey(q => q.EmailTestID);

        builder.Entity<UserTestEmailTest>().HasKey(q =>
            new
            {
                q.UserTestID,
                q.EmailTestID
            });

        // Relationships
        builder.Entity<UserTestEmailTest>()
            .HasRequired(t => t.EmailTest)
            .WithMany(t => t.UserTestEmailTests)
            .HasForeignKey(t => t.EmailTestID);

        builder.Entity<UserTestEmailTest>()
            .HasRequired(t => t.UserTest)
            .WithMany(t => t.UserTestEmailTests)
            .HasForeignKey(t => t.UserTestID);
    }
}
#endregion

Add an image in a WPF button

I found that I also had to set the Access Modifier in the Resources tab to 'Public' - by default it was set to Internal and my icon only appeared in design mode but not when I ran the application.

Qt jpg image display

If the only thing you want to do is drop in an image onto a widget withouth the complexity of the graphics API, you can also just create a new QWidget and set the background with StyleSheets. Something like this:

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    ...
    QWidget *pic = new QWidget(this);
    pic->setStyleSheet("background-image: url(test.png)");
    pic->setGeometry(QRect(50,50,128,128));
    ...
}

Overriding !important style

https://developer.mozilla.org/en-US/docs/Web/CSS/initial

use initial property in css3

 <p style="color:red!important"> 
    this text is red 
       <em style="color:initial"> 
          this text is in the initial color (e.g. black)
       </em>
    this is red again
 </p>

ggplot with 2 y axes on each side and different scales

The following incorporates Dag Hjermann's basic data and programming, improves upon user4786271's strategy to create a "transformation function" to optimally combine the plots and data axis, and responds to baptist's note that such a function can be created within R.

#Climatogram for Oslo (1961-1990)
climate <- tibble(
  Month = 1:12,
  Temp = c(-4,-4,0,5,11,15,16,15,11,6,1,-3),
  Precip = c(49,36,47,41,53,65,81,89,90,84,73,55))

#y1 identifies the position, relative to the y1 axis, 
#the locations of the minimum and maximum of the y2 graph.
#Usually this will be the min and max of y1.
#y1<-(c(max(climate$Precip), 0))
#y1<-(c(150, 55))
y1<-(c(max(climate$Precip), min(climate$Precip)))

#y2 is the Minimum and maximum of the secondary axis data.
y2<-(c(max(climate$Temp), min(climate$Temp)))

#axis combines y1 and y2 into a dataframe used for regressions.
axis<-cbind(y1,y2)
axis<-data.frame(axis)

#Regression of Temperature to Precipitation:
T2P<-lm(formula = y1 ~ y2, data = axis)
T2P_summary <- summary(lm(formula = y1 ~ y2, data = axis))
T2P_summary   

#Identifies the intercept and slope of regressing Temperature to Precipitation:
T2PInt<-T2P_summary$coefficients[1, 1] 
T2PSlope<-T2P_summary$coefficients[2, 1] 


#Regression of Precipitation to Temperature:
P2T<-lm(formula = y2 ~ y1, data = axis)
P2T_summary <- summary(lm(formula = y2 ~ y1, data = axis))
P2T_summary   

#Identifies the intercept and slope of regressing Precipitation to Temperature:
P2TInt<-P2T_summary$coefficients[1, 1] 
P2TSlope<-P2T_summary$coefficients[2, 1] 


#Create Plot:
ggplot(climate, aes(Month, Precip)) +
  geom_col() +
  geom_line(aes(y = T2PSlope*Temp + T2PInt), color = "red") +
  scale_y_continuous("Precipitation", sec.axis = sec_axis(~.*P2TSlope + P2TInt, name = "Temperature")) +
  scale_x_continuous("Month", breaks = 1:12) +
  theme(axis.line.y.right = element_line(color = "red"), 
        axis.ticks.y.right = element_line(color = "red"),
        axis.text.y.right = element_text(color = "red"), 
        axis.title.y.right = element_text(color = "red")) +
  ggtitle("Climatogram for Oslo (1961-1990)")

Most noteworthy is that a new "transformation function" works better with just two data points from the data set of each axes—usually the maximum and minimum values of each set. The resulting slopes and intercepts of the two regressions enable ggplot2 to exactly pair the plots of the minimums and maximums of each axis. As user4786271 pointed out, the two regressions transform each data set and plot to the other. One transforms the break points of the first y axis to the values of the second y axis. The second transforms the data of the secondary y axis to be "normalized" according to the first y axis. The following output shows how the axis align the minimums and maximums of each dataset:

enter image description here

Having the maximums and minimums match may be most appropriate; however, another benefit of this method is that the plot associated with the secondary axis can be easily shifted, if desired, by altering a programming line related to the primary axis data. The output below simply changes the minimum precipitation input in the programming line of y1 to "0", and thus aligns the minimum Temperature level with the "0" Precipitation level.

From: y1<-(c(max(climate$Precip), min(climate$Precip)))

To: y1<-(c(max(climate$Precip), 0))

enter image description here

Notice how the resulting new regressions and ggplot2 automatically adjusted the plot and axis to correctly align the minimum Temperature to the new "base" of the "0" Precipitation level. Likewise, one is easily able to elevate the Temperature plot so that it is more obvious. The following graph is created by simply changing the above-noted line to:

"y1<-(c(150, 55))"

The above line tells the maximum of the Temperature graph to coincide with the "150" Precipitation level, and the minimum of the temperature line to coincide with the "55" Precipitation level. Again, notice how ggplot2 and the resulting new regression outputs enable the graph to maintain correct alignment with the axis.

enter image description here

The above may not be a desirable output; however, it is an example of how the graph can be easily manipulated and still have correct relationships between the plots and the axis. The incorporation of Dag Hjermann's theme improves identification of the axis corresponding to the plot.

enter image description here

What are the differences between "git commit" and "git push"?

Just want to add the following points:

Yon can not push until you commit as we use git push to push commits made on your local branch to a remote repository.

The git push command takes two arguments:

A remote name, for example, origin A branch name, for example, master

For example:

git push  <REMOTENAME> <BRANCHNAME> 
git push  origin       master

How to find the date of a day of the week from a date using PHP?

<?php echo date("H:i", time()); ?>
<?php echo $days[date("l", time())] . date(", d.m.Y", time()); ?>

Simple, this should do the trick

Shadow Effect for a Text in Android?

Perhaps you'd consider using android:shadowColor, android:shadowDx, android:shadowDy, android:shadowRadius; alternatively setShadowLayer() ?

Allow all remote connections, MySQL

Install and setup mysql to connect from anywhere remotely DOES NOT WORK WITH mysql_secure_installation ! (https://dev.mysql.com/doc/refman/5.5/en/mysql-secure-installation.html)

On Ubuntu, Install mysql using:

sudo apt-get install mysql-server

Have just the below in /etc/mysql/my.cnf

[mysqld]
#### Unix socket settings (making localhost work)
user            = mysql
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock

#### TCP Socket settings (making all remote logins work)
port            = 3306
bind-address = 0.0.0.0

Login into DB from server using

mysql -u root -p

Create DB user using the below statement

grant all privileges on *.* to ‘username’@‘%’ identified by ‘password’;

Open firewall:

sudo ufw allow 3306

Restart mysql

sudo service mysql restart

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

USE YourDB
GO
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO

OR YOU CAN USE ANOTHER WAY

INSERT INTO MyTable (FirstCol, SecondCol)
VALUES 
('First',1),
('Second',2),
('Third',3),
('Fourth',4),
('Fifth',5)

Jump into interface implementation in Eclipse IDE

If you are really looking to speed your code navigation, you might want to take a look at nWire for Java. It is a code exploration plugin for Eclipse. You can instantly see all the related artifacts. So, in that case, you will focus on the method call and instantly see all possible implementations, declarations, invocations, etc.

Get css top value as number not as string?

You can use the parseInt() function to convert the string to a number, e.g:

parseInt($('#elem').css('top'));

Update: (as suggested by Ben): You should give the radix too:

parseInt($('#elem').css('top'), 10);

Forces it to be parsed as a decimal number, otherwise strings beginning with '0' might be parsed as an octal number (might depend on the browser used).

Difference between abstraction and encapsulation?

A lot of good answers are provided above but I am going to present my(Java) viewpoint here.

Data Encapsulation simply means wrapping and controlling access of logically grouped data in a class. It is generally associated with another keyword - Data Hiding. This is achieved in Java using access modifiers.

A simple example would be defining a private variable and giving access to it using getter and setter methods or making a method private as it's only use is withing the class. There is no need for user to know about these methods and variables.

Note : It should not be misunderstood that encapsulation is all about data hiding only. When we say encapsulation, emphasis should be on grouping or packaging or bundling related data and behavior together.

Data Abstraction on the other hand is concept of generalizing so that the underneath complex logic is not exposed to the user. In Java this is achieved by using interfaces and abstract classes.

Example -

Lets say we have an interface Animal and it has a function makeSound(). There are two concrete classes Dog and Cat that implement this interface. These concrete classes have separate implementations of makeSound() function. Now lets say we have a animal(We get this from some external module). All user knows is that the object that it is receiving is some Animal and it is the users responsibility to print the animal sound. One brute force way is to check the object received to identify it's type, then typecast it to that Animal type and then call makeSound() on it. But a neater way is to abstracts thing out. Use Animal as a polymorphic reference and call makeSound() on it. At runtime depending on what the real Object type is proper function will be invoked.

More details here.

enter image description here

Complex logic is in the circuit board which is encapsulated in a touchpad and a nice interface(buttons) is provided to abstract it out to the user.

PS: Above links are to my personal blog.

How can I stop python.exe from closing immediately after I get an output?

Just declare a variable like k or m or any other you want, now just add this piece of code at the end of your program

k=input("press close to exit") 

Here I just assumed k as variable to pause the program, you can use any variable you like.

Register comdlg32.dll gets Regsvr32: DllRegisterServer entry point was not found

I also had the similar problem while registering myinfo.dll file in windows 7. Following work for me: Create a short cut on your desktop C:\Windows\System32\regsvr32.exe c:\windows\system32\myinfo.dll right click on the short cut just created and select as Run as administrator.

XAMPP installation on Win 8.1 with UAC Warning

I don't know if you are still having this problem, but I had the same problem and had a different fix than what was listed in the other answer. I did install XAMPP under C:\xampp\, and my user is an admin, but there was also something else.

I had to manually go give my user full access to the C:\Users\XAMPP\ directory. By default (at least on my machine) Windows did not give my admin user rights to this new user's directory, but this is where XAMPP stores all of it's config files. Once I gave myself full access to this, everything worked perfectly.

Hope this helps!

UPDATE!

In retrospect, I think that I must have accidentally typed in "C:\Users\XAMPP\" as the install folder during the installation process. So I think the most important thing is to make sure that the user you are actually signed into Windows as when you start XAMPP has full access to the folder that it was actually installed to.

What is the maximum length of data I can put in a BLOB column in MySQL?

A BLOB can be 65535 bytes maximum. If you need more consider using a MEDIUMBLOB for 16777215 bytes or a LONGBLOB for 4294967295 bytes.

Hope, it will help you.

How to serialize SqlAlchemy result to JSON?

While the original question goes back awhile, the number of answers here (and my own experiences) suggest it's a non-trivial question with a lot of different approaches of varying complexity with different trade-offs.

That's why I built the SQLAthanor library that extends SQLAlchemy's declarative ORM with configurable serialization/de-serialization support that you might want to take a look at.

The library supports:

  • Python 2.7, 3.4, 3.5, and 3.6.
  • SQLAlchemy versions 0.9 and higher
  • serialization/de-serialization to/from JSON, CSV, YAML, and Python dict
  • serialization/de-serialization of columns/attributes, relationships, hybrid properties, and association proxies
  • enabling and disabling of serialization for particular formats and columns/relationships/attributes (e.g. you want to support an inbound password value, but never include an outbound one)
  • pre-serialization and post-deserialization value processing (for validation or type coercion)
  • a pretty straightforward syntax that is both Pythonic and seamlessly consistent with SQLAlchemy's own approach

You can check out the (I hope!) comprehensive docs here: https://sqlathanor.readthedocs.io/en/latest

Hope this helps!

Android studio: emulator is running but not showing up in Run App "choose a running device"

Probably the project you are running is not compatible (API version/Hardware requirements) with the emulator settings. Check in your build.gradle file if the targetSDK and minimumSdk version is lower or equal to the sdk version of your Emulator.

You should also uncheck Tools > Android > Enable ADB Integration

If your case is different then restart your Android Studio and run the emulator again.

How to combine two or more querysets in a Django view?

You can use the QuerySetChain class below. When using it with Django's paginator, it should only hit the database with COUNT(*) queries for all querysets and SELECT() queries only for those querysets whose records are displayed on the current page.

Note that you need to specify template_name= if using a QuerySetChain with generic views, even if the chained querysets all use the same model.

from itertools import islice, chain

class QuerySetChain(object):
    """
    Chains multiple subquerysets (possibly of different models) and behaves as
    one queryset.  Supports minimal methods needed for use with
    django.core.paginator.
    """

    def __init__(self, *subquerysets):
        self.querysets = subquerysets

    def count(self):
        """
        Performs a .count() for all subquerysets and returns the number of
        records as an integer.
        """
        return sum(qs.count() for qs in self.querysets)

    def _clone(self):
        "Returns a clone of this queryset chain"
        return self.__class__(*self.querysets)

    def _all(self):
        "Iterates records in all subquerysets"
        return chain(*self.querysets)

    def __getitem__(self, ndx):
        """
        Retrieves an item or slice from the chained set of results from all
        subquerysets.
        """
        if type(ndx) is slice:
            return list(islice(self._all(), ndx.start, ndx.stop, ndx.step or 1))
        else:
            return islice(self._all(), ndx, ndx+1).next()

In your example, the usage would be:

pages = Page.objects.filter(Q(title__icontains=cleaned_search_term) |
                            Q(body__icontains=cleaned_search_term))
articles = Article.objects.filter(Q(title__icontains=cleaned_search_term) |
                                  Q(body__icontains=cleaned_search_term) |
                                  Q(tags__icontains=cleaned_search_term))
posts = Post.objects.filter(Q(title__icontains=cleaned_search_term) |
                            Q(body__icontains=cleaned_search_term) | 
                            Q(tags__icontains=cleaned_search_term))
matches = QuerySetChain(pages, articles, posts)

Then use matches with the paginator like you used result_list in your example.

The itertools module was introduced in Python 2.3, so it should be available in all Python versions Django runs on.

Update Angular model after setting input value with jQuery

ngModel listens for "input" event, so to "fix" your code you'd need to trigger that event after setting the value:

$('button').click(function(){
    var input = $('input');
    input.val('xxx');
    input.trigger('input'); // Use for Chrome/Firefox/Edge
    input.trigger('change'); // Use for Chrome/Firefox/Edge + IE11
});

For the explanation of this particular behaviour check out this answer that I gave a while ago: "How does AngularJS internally catch events like 'onclick', 'onchange'?"


But unfortunately, this is not the only problem you have. As pointed out with other post comments, your jQuery-centric approach is plain wrong. For more info take a look at this post: How do I “think in AngularJS” if I have a jQuery background?).

How to copy static files to build directory with Webpack?

Above suggestions are good. But to try to answer your question directly I'd suggest using cpy-cli in a script defined in your package.json.

This example expects node to somewhere on your path. Install cpy-cli as a development dependency:

npm install --save-dev cpy-cli

Then create a couple of nodejs files. One to do the copy and the other to display a checkmark and message.

copy.js

#!/usr/bin/env node

var shelljs = require('shelljs');
var addCheckMark = require('./helpers/checkmark');
var path = require('path');

var cpy = path.join(__dirname, '../node_modules/cpy-cli/cli.js');

shelljs.exec(cpy + ' /static/* /build/', addCheckMark.bind(null, callback));

function callback() {
  process.stdout.write(' Copied /static/* to the /build/ directory\n\n');
}

checkmark.js

var chalk = require('chalk');

/**
 * Adds mark check symbol
 */
function addCheckMark(callback) {
  process.stdout.write(chalk.green(' ?'));
  callback();
}

module.exports = addCheckMark;

Add the script in package.json. Assuming scripts are in <project-root>/scripts/

...
"scripts": {
  "copy": "node scripts/copy.js",
...

To run the sript:

npm run copy

How can I list all the deleted files in a Git repository?

Since Windows doesn't have a grep command, this worked for me in PowerShell:

git log --find-renames --diff-filter=D --summary | Select-String -Pattern "delete mode" | sort -u > deletions.txt

How to get child process from parent process

Just use :

pgrep -P $your_process1_pid

How do I decode a URL parameter using C#?

Try this:

string decodedUrl = HttpUtility.UrlDecode("my.aspx?val=%2Fxyz2F");

How to use onBlur event on Angular2?

/*for reich text editor */
  public options: Object = {
    charCounterCount: true,
    height: 300,
    inlineMode: false,
    toolbarFixed: false,
    fontFamilySelection: true,
    fontSizeSelection: true,
    paragraphFormatSelection: true,

    events: {
      'froalaEditor.blur': (e, editor) => { this.handleContentChange(editor.html.get()); }}

How to post a file from a form with Axios

Add the file to a formData object, and set the Content-Type header to multipart/form-data.

var formData = new FormData();
var imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
})

lodash: mapping array to object

You should be using _.keyBy to easily convert an array to an object.

Docs here

Example usage below:

_x000D_
_x000D_
var params = [_x000D_
    { name: 'foo', input: 'bar' },_x000D_
    { name: 'baz', input: 'zle' }_x000D_
];_x000D_
console.log(_.keyBy(params, 'name'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

If required, you can manipulate the array before using _.keyBy or the object after using _.keyBy to get the exact desired result.

Force IE8 Into IE7 Compatiblity Mode

I might have found it now. http://blog.lroot.com/articles/the-ie7-compatibility-tag-force-ie8-to-use-the-ie7-rendering-mode/

The site says adding this meta tag:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7">

or adding this to .htaccess

Header set X-UA-Compatible: IE=EmulateIE7 

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

Maybe we can create a function to do what João proposed? Something like:

def cursor_exec(cursor, query, params):
    expansion_params= []
    real_params = []
    for p in params:
       if isinstance(p, (tuple, list)):
         real_params.extend(p)
         expansion_params.append( ("%s,"*len(p))[:-1] )
       else:
         real_params.append(p)
         expansion_params.append("%s")
    real_query = query % expansion_params
    cursor.execute(real_query, real_params)

.includes() not working in Internet Explorer

It works for me:

function stringIncludes(a, b) {
      return a.indexOf(b) !== -1;
}

Getting Current time to display in Label. VB.net

Use Date.Now instead of DateTime.Now

What precisely does 'Run as administrator' do?

The Run as *Anything command saves you from logging out and logging in as the user for which you use the runas command for.

The reason programs ask for this elevated privilege started with Black Comb and the Panther folder. There is 0 access to the Kernel in windows unless through the Admin prompt and then it is only a virtual relation with the O/S kernel.

Hoorah!

What does "opt" mean (as in the "opt" directory)? Is it an abbreviation?

Add-on software packages.

See http://www.pathname.com/fhs/2.2/fhs-3.12.html for details.

Also described at Wikipedia.

Its use dates back at least to the late 1980s, when it was a standard part of System V UNIX. These days, it's also seen in Linux, Solaris (which is SysV), OSX Cygwin, etc. Other BSD unixes (FreeBSD, NetBSD, etc) tend to follow other rules, so you don't usually see BSD systems with an /opt unless they're administered by someone who is more comfortable in other environments.

Trigger validation of all fields in Angular Form submit

I know, it's a tad bit too late to answer, but all you need to do is, force all forms dirty. Take a look at the following snippet:

angular.forEach($scope.myForm.$error.required, function(field) {
    field.$setDirty();
});

and then you can check if your form is valid using:

if($scope.myForm.$valid) {
    //Do something
}   

and finally, I guess, you would want to change your route if everything looks good:

$location.path('/somePath');

Edit: form won't register itself on the scope until submit event is trigger. Just use ng-submit directive to call a function, and wrap the above in that function, and it should work.

Remove blue border from css custom-styled button in Chrome

Wait! There's a reason for that ugly outline!

Before removing that ugly blue outline, you may want to take accessibility into consideration. By default, that blue outline is placed on focusable elements. This is so that users with accessibility issues are able to focus that button by tabbing to it. Some users do not have the motor skills to use a mouse and must use only the keyboard (or some other input device) for computer interaction. When you remove the blue outline, there is no longer a visual indicator on what element is focused. If you are going to remove the blue outline, you should replace it with another type of visual indication that the button is focused.

Possible Solution: Darken Buttons when focused

For the examples below, Chrome's blue outline was first removed by using button:focus { outline:0 !important; }

Here are your basic Bootstrap buttons as they appear normally: Bootstrap Buttons in Normal State

Here are the buttons when they receive focus: Bootstrap Buttons in Focused State

Here the buttons when they are pressed: enter image description here

As you can see, the buttons are a little darker when they receive focus. Personally, I would recommend making the focused buttons even darker so that there is a very noticeable difference between the focused state and the normal state of the button.

It's not just for disabled users

Making your site more accessible is something that is often overlooked but can help create a more productive experience in your website. There are many normal users that use keyboard commands to navigate through websites in order to keep hands on the keyboard.

How to Convert double to int in C?

int b;
double a;
a=3669.0;
b=a;
printf("b=%d",b);

this code gives the output as b=3669 only you check it clearly.

Spring MVC 4: "application/json" Content Type is not being set correctly

Not exactly for this OP, but for those who encountered 404 and cannot set response content-type to "application/json" (any content-type). One possibility is a server actually responds 406 but explorer (e.g., chrome) prints it as 404.

If you do not customize message converter, spring would use AbstractMessageConverterMethodProcessor.java. It would run:

List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(request);
List<MediaType> producibleMediaTypes = getProducibleMediaTypes(request, valueType, declaredType);

and if they do not have any overlapping (the same item), it would throw HttpMediaTypeNotAcceptableException and this finally causes 406. No matter if it is an ajax, or GET/POST, or form action, if the request uri ends with a .html or any suffix, the requestedMediaTypes would be "text/[that suffix]", and this conflicts with producibleMediaTypes, which is usually:

"application/json"  
"application/xml"   
"text/xml"          
"application/*+xml" 
"application/json"  
"application/*+json"
"application/json"  
"application/*+json"
"application/xml"   
"text/xml"          
"application/*+xml"
"application/xml"  
"text/xml"         
"application/*+xml"

Calling pylab.savefig without display in ipython

This is a matplotlib question, and you can get around this by using a backend that doesn't display to the user, e.g. 'Agg':

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

plt.plot([1,2,3])
plt.savefig('/tmp/test.png')

EDIT: If you don't want to lose the ability to display plots, turn off Interactive Mode, and only call plt.show() when you are ready to display the plots:

import matplotlib.pyplot as plt

# Turn interactive plotting off
plt.ioff()

# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('/tmp/test0.png')
plt.close(fig)

# Create a new figure, plot into it, then don't close it so it does get displayed
plt.figure()
plt.plot([1,3,2])
plt.savefig('/tmp/test1.png')

# Display all "open" (non-closed) figures
plt.show()

Using a custom (ttf) font in CSS

This is not a system font. this font is not supported in other systems. you can use font-face, convert font from this Site or from this

enter image description here

Does JavaScript pass by reference?

Primitives are passed by value, and Objects are passed by "copy of a reference".

Specifically, when you pass an object (or array) you are (invisibly) passing a reference to that object, and it is possible to modify the contents of that object, but if you attempt to overwrite the reference it will not affect the copy of the reference held by the caller - i.e. the reference itself is passed by value:

function replace(ref) {
    ref = {};           // this code does _not_ affect the object passed
}

function update(ref) {
    ref.key = 'newvalue';  // this code _does_ affect the _contents_ of the object
}

var a = { key: 'value' };
replace(a);  // a still has its original value - it's unmodfied
update(a);   // the _contents_ of 'a' are changed

Mysql command not found in OS X 10.7

This is the problem with your $PATH:

/usr/local//usr/local/mysql/bin/private/var/mysql/private/var/mysql/bin.

$PATH is where the shell searches for command files. Folders to search in need to be separated with a colon. And so you want /usr/local/mysql/bin/ in your path but instead it searches in /usr/local//usr/local/mysql/bin/private/var/mysql/private/var/mysql/bin, which probably doesn't exist.

Instead you want ${PATH}:/usr/local/mysql/bin.

So do export PATH=${PATH}:/usr/local/mysql/bin.

If you want this to be run every time you open terminal put it in the file .bash_profile, which is run when Terminal opens.

How to select a record and update it, with a single queryset in Django?

only in a case in serializer things, you can update in very simple way!

my_model_serializer = MyModelSerializer(
    instance=my_model, data=validated_data)
if my_model_serializer.is_valid():

    my_model_serializer.save()

only in a case in form things!

instance = get_object_or_404(MyModel, id=id)
form = MyForm(request.POST or None, instance=instance)
if form.is_valid():
    form.save()

Solving "adb server version doesn't match this client" error

If you are using android studio then give it a try:

Remove and path variable of adb from system variable/user variable. Then go to terminal of android studio and then type there command adb start-service.

I tried this and it worked for me.

pass parameter by link_to ruby on rails

You probably don't want to pass the car object as a parameter, try just passing car.id. What do you get when you inspect(params) after clicking "Add to cart"?

C string append

I write a function support dynamic variable string append, like PHP str append: str + str + ... etc.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>

int str_append(char **json, const char *format, ...)
{
    char *str = NULL;
    char *old_json = NULL, *new_json = NULL;

    va_list arg_ptr;
    va_start(arg_ptr, format);
    vasprintf(&str, format, arg_ptr);

    // save old json
    asprintf(&old_json, "%s", (*json == NULL ? "" : *json));

    // calloc new json memory
    new_json = (char *)calloc(strlen(old_json) + strlen(str) + 1, sizeof(char));

    strcat(new_json, old_json);
    strcat(new_json, str);

    if (*json) free(*json);
    *json = new_json;

    free(old_json);
    free(str);

    return 0;
}

int main(int argc, char *argv[])
{
    char *json = NULL;

    str_append(&json, "name: %d, %d, %d", 1, 2, 3);
    str_append(&json, "sex: %s", "male");
    str_append(&json, "end");
    str_append(&json, "");
    str_append(&json, "{\"ret\":true}");

    int i;
    for (i = 0; i < 10; i++) {
        str_append(&json, "id-%d", i);
    }

    printf("%s\n", json);

    if (json) free(json);

    return 0;
}

Reading input files by line using read command in shell scripting skips last line

Below code with Redirected "while-read" loop works fine for me

while read LINE
do
      let count++
      echo "$count $LINE"

done < $FILENAME

echo -e "\nTotal $count Lines read"

How do I uniquely identify computers visiting my web site?

Because i want the solution to work on all machines and all browsers (within reason) I am trying to create a solution using javascript.

Isn't that a really good reason not to use javascript?

As others have said - cookies are probably your best option - just be aware of the limitations.

What's the difference between "&nbsp;" and " "?

As already mentioned, you will not receive a line break where there is a "no-break space".

Also be wary, that elements containing only a " " may show up incorrectly, where &nbsp; will work. In i.e. 6 at least (as far as I remember, IE7 has the same issue), if you have an empty table element, it will not apply styling, for example borders, to the element, if there is no content, or only white space. So the following will not be rendered with borders:

<td></td>
<td> <td>

Whereas the borders will show up in this example:

<td>& nbsp;</td>

Hmm -had to put in a dummy space to get it to render correctly here

How can I remove the decimal part from JavaScript number?

toFixed will behave like round.

For a floor like behavior use %:

var num = 3.834234;
var floored_num = num - (num % 1); // floored_num will be 3

I'm getting favicon.ico error

It's a nightmare since each browser/device handles it differently.

Favicon generator helps me a lot for those applications where we need to cover the most possible scenarios.

https://realfavicongenerator.net/

You just need a png image 260px x 260px (at least) and from there the generator will create all references you need within your web page.

You just need to add this references and images to your application.

enter image description here

How to recover corrupted Eclipse workspace?

I have succesfully recovered my existing workspace from a totally messed up situation (all kinds of core components giving NPE's and ClassCastExceptions and the like) by using this procedure:

  • Open Eclipse
  • Close error dialog
  • Select first project in the workspace
  • Right-click -> Refresh
  • Close error dialog
  • Close Eclipse
  • Close error dialog
  • Repeat for all projects in the workspace
  • (if your projects are in CVS/SVN etc, synchronize them)
  • Clean and rebuild all projects
  • Fixed

This whole procedure took me over half an hour for a big workspace, but it did fix it in the end.

How to specify in crontab by what user to run script?

Mike's suggestion sounds like the "right way". I came across this thread wanting to specify the user to run vncserver under on reboot and wanted to keep all my cron jobs in one place.

I was getting the following error for the VNC cron:

vncserver: The USER environment variable is not set. E.g.:

In my case, I was able to use sudo to specify who to run the task as.

@reboot sudo -u [someone] vncserver ...

Uppercase first letter of variable

Easiest Way to uppercase first letter in JS

var string = "made in india";

string =string .toLowerCase().replace(/\b[a-z]/g, function(letter){return  letter.toUpperCase();});

alert(string );

Result: "Made In India"

How to generate .NET 4.0 classes from xsd?

I show you here the easiest way using Vs2017 and Vs2019 Open your xsd with Visual Studio and generate a sample xml file as in the url suggested.

  1. Once you opened your xsd in design view as below, click on xml schema explorer enter image description here

2. Within “XML Schema Explorer” scroll all the way down to find the root/data node. Right click on root/data node and it will show “Generate Sample XML”. If it does not show, it means you are not on the data element node but you are on any of the data definition node.

enter image description here

  1. Copy your generated Xml into the clipboard
  2. Create a new empty class in your solution and delete the class definition. Only Namespace should remain
  3. While your mouse pointer focused inside your class, choose EDIT-> Paste Special-> Paste Xml as Classes

Exec : display stdout "live"

I'd just like to add that one small issue with outputting the buffer strings from a spawned process with console.log() is that it adds newlines, which can spread your spawned process output over additional lines. If you output stdout or stderr with process.stdout.write() instead of console.log(), then you'll get the console output from the spawned process 'as is'.

I saw that solution here: Node.js: printing to console without a trailing newline?

Hope that helps someone using the solution above (which is a great one for live output, even if it is from the documentation).

How to open .SQLite files

SQLite is database engine, .sqlite or .db should be a database. If you don't need to program anything, you can use a GUI like sqlitebrowser or anything like that to view the database contents.

There is also spatialite, https://www.gaia-gis.it/fossil/spatialite_gui/index

How do you clear the SQL Server transaction log?

Database ? right click Properties ? file ? add another log file with a different name and set the path the same as the old log file with a different file name.

The database automatically picks up the newly created log file.

How to Copy Text to Clip Board in Android?

int sdk = android.os.Build.VERSION.SDK_INT;

    if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) DetailView.this
                .getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setText("" + yourMessage.toString());
        Toast.makeText(AppCstVar.getAppContext(),
                "" + getResources().getString(R.string.txt_copiedtoclipboard),
                Toast.LENGTH_SHORT).show();
    } else {
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) DetailView.this
                .getSystemService(Context.CLIPBOARD_SERVICE);
        android.content.ClipData clip = android.content.ClipData
                .newPlainText("message", "" + yourMessage.toString());
        clipboard.setPrimaryClip(clip);
        Toast.makeText(AppCstVar.getAppContext(),
                "" + getResources().getString(R.string.txt_copiedtoclipboard),
                Toast.LENGTH_SHORT).show();
    }

When to encode space to plus (+) or %20?

Its better to always encode spaces as %20, not as "+".

It was RFC-1866 (HTML 2.0 specification), which specified that space characters should be encoded as "+" in "application/x-www-form-urlencoded" content-type key-value pairs. (see paragraph 8.2.1. subparagraph 1.). This way of encoding form data is also given in later HTML specifications, look for relevant paragraphs about application/x-www-form-urlencoded.

Here is an example of such a string in URL where RFC-1866 allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses, according to RFC-1866. In other cases, spaces should be encoded to %20. But since it's hard to determine the context, it's the best practice to never encode spaces as "+".

I would recommend to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3

unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"

javascript function wait until another function to finish

In my opinion, deferreds/promises (as you have mentionned) is the way to go, rather than using timeouts.

Here is an example I have just written to demonstrate how you could do it using deferreds/promises.

Take some time to play around with deferreds. Once you really understand them, it becomes very easy to perform asynchronous tasks.

Hope this helps!

$(function(){
    function1().done(function(){
        // function1 is done, we can now call function2
        console.log('function1 is done!');

        function2().done(function(){
            //function2 is done
            console.log('function2 is done!');
        });
    });
});

function function1(){
    var dfrd1 = $.Deferred();
    var dfrd2= $.Deferred();

    setTimeout(function(){
        // doing async stuff
        console.log('task 1 in function1 is done!');
        dfrd1.resolve();
    }, 1000);

    setTimeout(function(){
        // doing more async stuff
        console.log('task 2 in function1 is done!');
        dfrd2.resolve();
    }, 750);

    return $.when(dfrd1, dfrd2).done(function(){
        console.log('both tasks in function1 are done');
        // Both asyncs tasks are done
    }).promise();
}

function function2(){
    var dfrd1 = $.Deferred();
    setTimeout(function(){
        // doing async stuff
        console.log('task 1 in function2 is done!');
        dfrd1.resolve();
    }, 2000);
    return dfrd1.promise();
}

Paste multiple columns together

I benchmarked the answers of Anthony Damico, Brian Diggs and data_steve on a small sample tbl_df and got the following results.

> data <- data.frame('a' = 1:3, 
+                    'b' = c('a','b','c'), 
+                    'c' = c('d', 'e', 'f'), 
+                    'd' = c('g', 'h', 'i'))
> data <- tbl_df(data)
> cols <- c("b", "c", "d")
> microbenchmark(
+     do.call(paste, c(data[cols], sep="-")),
+     apply( data[ , cols ] , 1 , paste , collapse = "-" ),
+     tidyr::unite_(data, "x", cols, sep="-")$x,
+     times=1000
+ )
Unit: microseconds
                                         expr     min      lq      mean  median       uq       max neval
do.call(paste, c(data[cols], sep = "-"))       65.248  78.380  93.90888  86.177  99.3090   436.220  1000
apply(data[, cols], 1, paste, collapse = "-") 223.239 263.044 313.11977 289.514 338.5520   743.583  1000
tidyr::unite_(data, "x", cols, sep = "-")$x   376.716 448.120 556.65424 501.877 606.9315 11537.846  1000

However, when I evaluated on my own tbl_df with ~1 million rows and 10 columns the results were quite different.

> microbenchmark(
+     do.call(paste, c(data[c("a", "b")], sep="-")),
+     apply( data[ , c("a", "b") ] , 1 , paste , collapse = "-" ),
+     tidyr::unite_(data, "c", c("a", "b"), sep="-")$c,
+     times=25
+ )
Unit: milliseconds
                                                       expr        min         lq      mean     median        uq       max neval
do.call(paste, c(data[c("a", "b")], sep="-"))                 930.7208   951.3048  1129.334   997.2744  1066.084  2169.147    25
apply( data[ , c("a", "b") ] , 1 , paste , collapse = "-" )  9368.2800 10948.0124 11678.393 11136.3756 11878.308 17587.617    25
tidyr::unite_(data, "c", c("a", "b"), sep="-")$c              968.5861  1008.4716  1095.886  1035.8348  1082.726  1759.349    25

Solve error javax.mail.AuthenticationFailedException

Just in case anyone comes looking a solution for this problem.

The Authentication problems can be alleviated by activating the google 2-step verification for the account in use and creating an app specific password. I had the same problem as the OP. Enabling 2-step worked.

How to remove the last character from a bash grep output

In Bash using only one external utility:

IFS='= ' read -r discard COMPANY_NAME <<< $(grep "company_name" file.txt)
COMPANY_NAME=${COMPANY_NAME/%?}

do { ... } while (0) — what is it good for?

Generically, do/while is good for any sort of loop construct where one must execute the loop at least once. It is possible to emulate this sort of looping through either a straight while or even a for loop, but often the result is a little less elegant. I'll admit that specific applications of this pattern are fairly rare, but they do exist. One which springs to mind is a menu-based console application:

do {
    char c = read_input();

    process_input(c);
} while (c != 'Q');

Updating to latest version of CocoaPods?

This is a really quick & detailed solution

Open the Terminal and execute the following to get the latest stable version:

sudo gem install cocoapods

Add --pre to get the latest pre release:

sudo gem install cocoapods --pre

Incase any error occured

Try uninstall and install again:

sudo gem uninstall cocoapods
sudo gem install cocoapods

Run after updating CocoaPods

sudo gem clean cocoapods

After updating CocoaPods, also need to update Podfile.lock file in your project.

Go to your project directory

pod install

log4j configuration via JVM argument(s)?

If you are using gradle. You can apply 'aplication' plugin and use the following command

  applicationDefaultJvmArgs = [
             "-Dlog4j.configurationFile=your.xml",
                              ]

Can't connect to local MySQL server through socket homebrew

Looks like your mysql server is not started. I usually run the stop command and then start it again:

mysqld stop
mysql.server start

Same error, and this works for me.

Unresolved Import Issues with PyDev and Eclipse

I am using eclipse kepler 4.3, PyDev 3.9.2 and on my ubuntu 14.04 I encountered with the same problem. I tried and spent hours, with all the above most of the options but in vain. Then I tried the following which was great:

  • Select Project-> RightClick-> PyDev-> Remove PyDev Project Config
  • file-> restart

And I was using Python 2.7 as an interpreter, although it doesn’t effect, I think.

How to get TimeZone from android mobile?

All the answers here seem to suggest setting the daylite parameter to false. This is incorrect for many timezones which change abbreviated names depending on the time of the year (e.g. EST vs EDT).

The solution below will give you the correct abbreviation according to the current date for the timezone.

val tz = TimeZone.getDefault()
val isDaylite = tz.inDaylightTime(Date())
val timezone = tz.getDisplayName(isDaylite, TimeZone.SHORT)

Case in Select Statement

The MSDN is a good reference for these type of questions regarding syntax and usage. This is from the Transact SQL Reference - CASE page.

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

USE AdventureWorks2012;
GO
SELECT   ProductNumber, Name, "Price Range" = 
  CASE 
     WHEN ListPrice =  0 THEN 'Mfg item - not for resale'
     WHEN ListPrice < 50 THEN 'Under $50'
     WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
     WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
     ELSE 'Over $1000'
  END
FROM Production.Product
ORDER BY ProductNumber ;
GO

Another good site you may want to check out if you're using SQL Server is SQL Server Central. This has a large variety of resources available for whatever area of SQL Server you would like to learn.

Redirect to a page/URL after alert button is pressed

if (window.confirm('Really go to another page?'))
{
    alert('message');
    window.location = '/some/url';
}
else
{
    die();
}

How to delete a column from a table in MySQL

Use ALTER:

ALTER TABLE `tbl_Country` DROP COLUMN `column_name`;

How can I remove or replace SVG content?

If you want to get rid of all children,

svg.selectAll("*").remove();

will remove all content associated with the svg.

HTTP vs HTTPS performance

In addition to everything mentioned so far, please keep in mind that some (all?) web browsers do not store cached content obtained over HTTPS on the local hard-drive for security reasons. This means that from the user's perspective pages with plenty of static content will appear to load slower after the browser is restarted, and from your server's perspective the volume of requests for static content over HTTPS will be higher than would have been over HTTP.

Get only records created today in laravel

No need to use Carbon::today because laravel uses function now() instead as a helper function

So to get any records that have been created today you can use the below code:

Model::whereDay('created_at', now()->day)->get();

You need to use whereDate so created_at will be converted to date.

Why an abstract class implementing an interface can miss the declaration/implementation of one of the interface's methods?

Interface means a class that has no implementation of its method, but with just declaration.
Other hand, abstract class is a class that can have implementation of some method along with some method with just declaration, no implementation.
When we implement an interface to an abstract class, its means that the abstract class inherited all the methods of the interface. As, it is not important to implement all the method in abstract class however it comes to abstract class (by inheritance too), so the abstract class can left some of the method in interface without implementation here. But, when this abstract class will inherited by some concrete class, they must have to implements all those unimplemented method there in abstract class.

Passing variables to the next middleware using next() in Express.js

As mentioned above, res.locals is a good (recommended) way to do this. See here for a quick tutorial on how to do this in Express.

Merging arrays with the same keys

I just wrote this function, it should do the trick for you, but it does left join

public function mergePerKey($array1,$array2)
    {
        $mergedArray = [];

        foreach ($array1 as $key => $value) 
        {
            if(isset($array2[$key]))
             {
               $mergedArray[$value] = null;

               continue;
             }
            $mergedArray[$value] = $array2[$key];
        }

        return $mergedArray;
    }

Android Service needs to run always (Never pause or stop)

"Is it possible to run this service always as when the application pause and anything else?"

Yes.

  1. In the service onStartCommand method return START_STICKY.

    public int onStartCommand(Intent intent, int flags, int startId) {
            return START_STICKY;
    }
    
  2. Start the service in the background using startService(MyService) so that it always stays active regardless of the number of bound clients.

    Intent intent = new Intent(this, PowerMeterService.class);
    startService(intent);
    
  3. Create the binder.

    public class MyBinder extends Binder {
            public MyService getService() {
                    return MyService.this;
            }
    }
    
  4. Define a service connection.

    private ServiceConnection m_serviceConnection = new ServiceConnection() {
            public void onServiceConnected(ComponentName className, IBinder service) {
                    m_service = ((MyService.MyBinder)service).getService();
            }
    
            public void onServiceDisconnected(ComponentName className) {
                    m_service = null;
            }
    };
    
  5. Bind to the service using bindService.

            Intent intent = new Intent(this, MyService.class);
            bindService(intent, m_serviceConnection, BIND_AUTO_CREATE);
    
  6. For your service you may want a notification to launch the appropriate activity once it has been closed.

    private void addNotification() {
            // create the notification
            Notification.Builder m_notificationBuilder = new Notification.Builder(this)
                    .setContentTitle(getText(R.string.service_name))
                    .setContentText(getResources().getText(R.string.service_status_monitor))
                    .setSmallIcon(R.drawable.notification_small_icon);
    
            // create the pending intent and add to the notification
            Intent intent = new Intent(this, MyService.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
            m_notificationBuilder.setContentIntent(pendingIntent);
    
            // send the notification
            m_notificationManager.notify(NOTIFICATION_ID, m_notificationBuilder.build());
    }
    
  7. You need to modify the manifest to launch the activity in single top mode.

              android:launchMode="singleTop"
    
  8. Note that if the system needs the resources and your service is not very active it may be killed. If this is unacceptable bring the service to the foreground using startForeground.

            startForeground(NOTIFICATION_ID, m_notificationBuilder.build());
    

Maximum length for MD5 input/output

You may want to use SHA-1 instead of MD5, as MD5 is considered broken.

You can read more about MD5 vulnerabilities in this Wikipedia article.

How do I apply a style to all children of an element

Instead of the * selector you can use the :not(selector) with the > selector and set something that definitely wont be a child.

Edit: I thought it would be faster but it turns out I was wrong. Disregard.

Example:

.container > :not(marquee){
        color:red;
    }


<div class="container">
    <p></p>
    <span></span>
<div>

What is the difference between an annotated and unannotated tag?

Push annotated tags, keep lightweight local

man git-tag says:

Annotated tags are meant for release while lightweight tags are meant for private or temporary object labels.

And certain behaviors do differentiate between them in ways that this recommendation is useful e.g.:

  • annotated tags can contain a message, creator, and date different than the commit they point to. So you could use them to describe a release without making a release commit.

    Lightweight tags don't have that extra information, and don't need it, since you are only going to use it yourself to develop.

  • git push --follow-tags will only push annotated tags
  • git describe without command line options only sees annotated tags

Internals differences

  • both lightweight and annotated tags are a file under .git/refs/tags that contains a SHA-1

  • for lightweight tags, the SHA-1 points directly to a commit:

    git tag light
    cat .git/refs/tags/light
    

    prints the same as the HEAD's SHA-1.

    So no wonder they cannot contain any other metadata.

  • annotated tags point to a tag object in the object database.

    git tag -as -m msg annot
    cat .git/refs/tags/annot
    

    contains the SHA of the annotated tag object:

    c1d7720e99f9dd1d1c8aee625fd6ce09b3a81fef
    

    and then we can get its content with:

    git cat-file -p c1d7720e99f9dd1d1c8aee625fd6ce09b3a81fef
    

    sample output:

    object 4284c41353e51a07e4ed4192ad2e9eaada9c059f
    type commit
    tag annot
    tagger Ciro Santilli <[email protected]> 1411478848 +0200
    
    msg
    -----BEGIN PGP SIGNATURE-----
    Version: GnuPG v1.4.11 (GNU/Linux)
    
    <YOUR PGP SIGNATURE>
    -----END PGP SIGNAT
    

    And this is how it contains extra metadata. As we can see from the output, the metadata fields are:

    A more detailed analysis of the format is present at: What is the format of a git tag object and how to calculate its SHA?

Bonuses

  • Determine if a tag is annotated:

    git cat-file -t tag
    

    Outputs

    • commit for lightweight, since there is no tag object, it points directly to the commit
    • tag for annotated, since there is a tag object in that case
  • List only lightweight tags: How can I list all lightweight tags?

How can I make the Android emulator show the soft keyboard?

  1. Edit your virtual device using AVD.
  2. Press the "show advance setting" button to show more option scroll down to the bottom and check "Enable keyboard input" press "finish" button
    at the bottom corner of your window
  3. then start the emulator device that you just set up.
  4. inside the emulator, go to the "Settings" -> "Language & Input"
  5. and in the "Keyboard & Input Methods" -> "Default" then "choose input method" is shown
  6. and switch off "Hardware Physical Keyboard" toggle button

CMD: Export all the screen content to a text file

If you want to output ALL verbosity, not just stdout. But also any printf statements made by the program, any warnings, infos, etc, you have to add 2>&1 at the end of the command line.

In your case, the command will be

Program.exe > file.txt 2>&1

passing several arguments to FUN of lapply (and others *apply)

As suggested by Alan, function 'mapply' applies a function to multiple Multiple Lists or Vector Arguments:

mapply(myfun, arg1, arg2)

See man page: https://stat.ethz.ch/R-manual/R-devel/library/base/html/mapply.html

Upgrade python without breaking yum

Alright so for me, the error being fixed is when there are different versions of python installed and yum can't find a certain .so file and throws an exception.
yum wants 2.7.5 according to the error.

which python gives me /usr/bin/python
python --version gives me 2.7.5

The fix for me was append /lib64 to the LD_LIBRARY_PATH environment variable. The relevant content is /lib64/python2.7 and /lib64/python3.6.

export LD_LIBRARY_PATH=/lib64:$LD_LIBRARY_PATH

Fixed the yum error for me with multiple python versions installed.

In Chart.js set chart title, name of x axis and y axis?

In Chart.js version 2.0, it is possible to set labels for axes:

options = {
  scales: {
    yAxes: [{
      scaleLabel: {
        display: true,
        labelString: 'probability'
      }
    }]
  }     
}

See Labelling documentation for more details.

What's the best way to break from nested loops in JavaScript?

Hmmm hi to the 10 years old party ?

Why not put some condition in your for ?

var condition = true
for (var i = 0 ; i < Args.length && condition ; i++) {
    for (var j = 0 ; j < Args[i].length && condition ; j++) {
        if (Args[i].obj[j] == "[condition]") {
            condition = false
        }
    }
}

Like this you stop when you want

In my case, using Typescript, we can use some() which go through the array and stop when condition is met So my code become like this :

Args.some((listObj) => {
    return listObj.some((obj) => {
        return !(obj == "[condition]")
    })
})

Like this, the loop stopped right after the condition is met

Reminder : This code run in TypeScript

Python Graph Library

Also, you might want to take a look at NetworkX

What does the 'static' keyword do in a class?

Static means that you don't have to create an instance of the class to use the methods or variables associated with the class. In your example, you could call:

Hello.main(new String[]()) //main(...) is declared as a static function in the Hello class

directly, instead of:

Hello h = new Hello();
h.main(new String[]()); //main(...) is a non-static function linked with the "h" variable

From inside a static method (which belongs to a class) you cannot access any members which are not static, since their values depend on your instantiation of the class. A non-static Clock object, which is an instance member, would have a different value/reference for each instance of your Hello class, and therefore you could not access it from the static portion of the class.

Java reading a file into an ArrayList?

List<String> words = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("words.txt"));
String line;
while ((line = reader.readLine()) != null) {
    words.add(line);
}
reader.close();

Postgresql : syntax error at or near "-"

I have reproduced the issue in my system,

postgres=# alter user my-sys with password 'pass11';
ERROR:  syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
                       ^

Here is the issue,

psql is asking for input and you have given again the alter query see postgres-#That's why it's giving error at alter

postgres-# alter user "my-sys" with password 'pass11';
ERROR:  syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
        ^

Solution is as simple as the error,

postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE

Basic Authentication Using JavaScript

Today we use Bearer token more often that Basic Authentication but if you want to have Basic Authentication first to get Bearer token then there is a couple ways:

const request = new XMLHttpRequest();
request.open('GET', url, false, username,password)
request.onreadystatechange = function() {
        // D some business logics here if you receive return
   if(request.readyState === 4 && request.status === 200) {
       console.log(request.responseText);
   }
}
request.send()

Full syntax is here

Second Approach using Ajax:

$.ajax
({
  type: "GET",
  url: "abc.xyz",
  dataType: 'json',
  async: false,
  username: "username",
  password: "password",
  data: '{ "key":"sample" }',
  success: function (){
    alert('Thanks for your up vote!');
  }
});

Hopefully, this provides you a hint where to start API calls with JS. In Frameworks like Angular, React, etc there are more powerful ways to make API call with Basic Authentication or Oauth Authentication. Just explore it.

sort files by date in PHP

$files = array_diff(scandir($dir,SCANDIR_SORT_DESCENDING), array('..', '.'));
print_r($files);

Turn on torch/flash on iPhone

iWasRobbed's answer is great, except there is an AVCaptureSession running in the background all the time. On my iPhone 4s it takes about 12% CPU power according to Instrument so my app took about 1% battery in a minute. In other words if the device is prepared for AV capture it's not cheap.

Using the code below my app requires 0.187% a minute so the battery life is more than 5x longer.

This code works just fine on any device (tested on both 3GS (no flash) and 4s). Tested on 4.3 in simulator as well.

#import <AVFoundation/AVFoundation.h>

- (void) turnTorchOn:(BOOL)on {

    Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
    if (captureDeviceClass != nil) {
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([device hasTorch] && [device hasFlash]){

            [device lockForConfiguration:nil];
            if (on) {
                [device setTorchMode:AVCaptureTorchModeOn];
                [device setFlashMode:AVCaptureFlashModeOn];
                torchIsOn = YES;
            } else {
                [device setTorchMode:AVCaptureTorchModeOff];
                [device setFlashMode:AVCaptureFlashModeOff];
                torchIsOn = NO;            
            }
            [device unlockForConfiguration];
        }
    }
}

Ways to implement data versioning in MongoDB

The first big question when diving in to this is "how do you want to store changesets"?

  1. Diffs?
  2. Whole record copies?

My personal approach would be to store diffs. Because the display of these diffs is really a special action, I would put the diffs in a different "history" collection.

I would use the different collection to save memory space. You generally don't want a full history for a simple query. So by keeping the history out of the object you can also keep it out of the commonly accessed memory when that data is queried.

To make my life easy, I would make a history document contain a dictionary of time-stamped diffs. Something like this:

{
    _id : "id of address book record",
    changes : { 
                1234567 : { "city" : "Omaha", "state" : "Nebraska" },
                1234568 : { "city" : "Kansas City", "state" : "Missouri" }
               }
}

To make my life really easy, I would make this part of my DataObjects (EntityWrapper, whatever) that I use to access my data. Generally these objects have some form of history, so that you can easily override the save() method to make this change at the same time.

UPDATE: 2015-10

It looks like there is now a spec for handling JSON diffs. This seems like a more robust way to store the diffs / changes.

How to stop asynctask thread in android?

u can check onCancelled() once then :

protected Object doInBackground(Object... x) {

while (/* condition */) {
  if (isCancelled()) break;
}
return null;

}

Regex allow digits and a single dot

Try this

boxValue = boxValue.replace(/[^0-9\.]/g,"");

This Regular Expression will allow only digits and dots in the value of text box.

Check box size change with CSS

You might want to do this.

input[type=checkbox] {

 -ms-transform: scale(2); /* IE */
 -moz-transform: scale(2); /* FF */
 -webkit-transform: scale(2); /* Safari and Chrome */
 -o-transform: scale(2); /* Opera */
  padding: 10px;
}

Set a div width, align div center and text align left

Use auto margins.

div {
   margin-left: auto;
   margin-right: auto;
   width: NNNpx;

   /* NOTE: Only works for non-floated block elements */
   display: block;
   float: none;
}

Further reading at SimpleBits CSS Centering 101

At runtime, find all classes in a Java application that extend a base class

Java dynamically loads classes, so your universe of classes would be only those that have already been loaded (and not yet unloaded). Perhaps you can do something with a custom class loader that could check the supertypes of each loaded class. I don't think there's an API to query the set of loaded classes.

Parse XML using JavaScript

The following will parse an XML string into an XML document in all major browsers, including Internet Explorer 6. Once you have that, you can use the usual DOM traversal methods/properties such as childNodes and getElementsByTagName() to get the nodes you want.

var parseXml;
if (typeof window.DOMParser != "undefined") {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" &&
       new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    throw new Error("No XML parser found");
}

Example usage:

var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);

Which I got from https://stackoverflow.com/a/8412989/1232175.

MySQL - count total number of rows in php

for PHP 5.3 using PDO

<?php
    $staff=$dbh->prepare("SELECT count(*) FROM staff_login");
    $staff->execute();
    $staffrow = $staff->fetch(PDO::FETCH_NUM);
    $staffcount = $staffrow[0];


    echo $staffcount;
?>

How do I execute .js files locally in my browser?

If you're using Google Chrome you can use the Chrome Dev Editor: https://github.com/dart-lang/chromedeveditor

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

Google Maps shows "For development purposes only"

As recommended in a comment, I used the "Google Maps Platform API Checker" Chrome add-in to identify and resolve the issue.

Essentially, this add-in directed me to here where I was able to sign in to Google and create a free API key.

Afterwards, I updated my JavaScript and it immediately resolved this issue.

Old JavaScript: ...script src="https://maps.googleapis.com/maps/api/js?v=3" ...

Updated Javascript:...script src="https://maps.googleapis.com/maps/api/js?key=*****GOOGLE API KEY******&v=3" ...

The add-in then validated the JS API call. Hope this helps someone resolve the issue quickly!

enter image description here

Simple CSS Animation Loop – Fading In & Out "Loading" Text

As King King said, you must add the browser specific prefix. This should cover most browsers:

_x000D_
_x000D_
@keyframes flickerAnimation {_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-o-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-moz-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-webkit-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
.animate-flicker {_x000D_
   -webkit-animation: flickerAnimation 1s infinite;_x000D_
   -moz-animation: flickerAnimation 1s infinite;_x000D_
   -o-animation: flickerAnimation 1s infinite;_x000D_
    animation: flickerAnimation 1s infinite;_x000D_
}
_x000D_
<div class="animate-flicker">Loading...</div>
_x000D_
_x000D_
_x000D_

Generating an array of letters in the alphabet

Surprised no one has suggested a yield solution:

public static IEnumerable<char> Alphabet()
{
    for (char letter = 'A'; letter <= 'Z'; letter++)
    {
        yield return letter;
    }
}

Example:

foreach (var c in Alphabet())
{
    Console.Write(c);
}

Problems after upgrading to Xcode 10: Build input file cannot be found

For Swift files or files that belong to the project such as:

Build input file cannot be found: PATH/TO/FILE/FILE.swift

This issue can happen when files or folders have been removed or moved in the project.

To fix it:

  1. Go in the project-navigator, select your project

  2. Select Build Phasestab

  3. In Compile Sources section, check for the file(s) that Xcode is complaining of

  4. Notice that the file(s) have the wrong path, and delete them by clicking on the minus icon

  5. Re-add the file(s) by clicking the plus icon and search in the project.

  6. Product > Clean Build Folder

  7. Build

You generally find these missing files in the Recovered References folder of Xcode in the project tree (look for the search bar at the bottom-left of Xcode and search for your complaining file):

Deleting them from this folder can also solve the error.

Can I set max_retries for requests.request?

It is the underlying urllib3 library that does the retrying. To set a different maximum retry count, use alternative transport adapters:

from requests.adapters import HTTPAdapter

s = requests.Session()
s.mount('http://stackoverflow.com', HTTPAdapter(max_retries=5))

The max_retries argument takes an integer or a Retry() object; the latter gives you fine-grained control over what kinds of failures are retried (an integer value is turned into a Retry() instance which only handles connection failures; errors after a connection is made are by default not handled as these could lead to side-effects).


Old answer, predating the release of requests 1.2.1:

The requests library doesn't really make this configurable, nor does it intend to (see this pull request). Currently (requests 1.1), the retries count is set to 0. If you really want to set it to a higher value, you'll have to set this globally:

import requests

requests.adapters.DEFAULT_RETRIES = 5

This constant is not documented; use it at your own peril as future releases could change how this is handled.

Update: and this did change; in version 1.2.1 the option to set the max_retries parameter on the HTTPAdapter() class was added, so that now you have to use alternative transport adapters, see above. The monkey-patch approach no longer works, unless you also patch the HTTPAdapter.__init__() defaults (very much not recommended).

How to exclude rows that don't join with another table?

This was helpful to use in COGNOS because creating a SQL "Not in" statement in Cognos was allowed, but it took too long to run. I had manually coded table A to join to table B in in Cognos as A.key "not in" B.key, but the query was taking too long/not returning results after 5 minutes.

For anyone else that is looking for a "NOT IN" solution in Cognos, here is what I did. Create a Query that joins table A and B with a LEFT JOIN in Cognos by selecting link type: table A.Key has "0 to N" values in table B, then added a Filter (these correspond to Where Clauses) for: table B.Key is NULL.

Ran fast and like a charm.

How to create exe of a console application

For .net core 2.1 console application, the following approaches worked for me:

1 - from CLI (after building the application and navigating to debug or release folders based on the build type specified):

dotnet appName.dll

2 - from Visual Studio

R.C solution and click publish
'Target location' -> 'configure' ->
   'Deployment Mode' = 'Self-Contained'
   'Target Runtime' = 'win-x64 or win-x86 depending on the OS'

References:

For an in depth explanation of all the deployment options available for .net core applications, checkout the following articles:

Converting char[] to byte[]

Convert without creating String object:

import java.nio.CharBuffer;
import java.nio.ByteBuffer;
import java.util.Arrays;

byte[] toBytes(char[] chars) {
  CharBuffer charBuffer = CharBuffer.wrap(chars);
  ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
  byte[] bytes = Arrays.copyOfRange(byteBuffer.array(),
            byteBuffer.position(), byteBuffer.limit());
  Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data
  return bytes;
}

Usage:

char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
byte[] bytes = toBytes(chars);
/* do something with chars/bytes */
Arrays.fill(chars, '\u0000'); // clear sensitive data
Arrays.fill(bytes, (byte) 0); // clear sensitive data

Solution is inspired from Swing recommendation to store passwords in char[]. (See Why is char[] preferred over String for passwords?)

Remember not to write sensitive data to logs and ensure that JVM won't hold any references to it.


The code above is correct but not effective. If you don't need performance but want security you can use it. If security also not a goal then do simply String.getBytes. Code above is not effective if you look down of implementation of encode in JDK. Besides you need to copy arrays and create buffers. Another way to convert is inline all code behind encode (example for UTF-8):

val xs: Array[Char] = "A ß € ?  ".toArray
val len = xs.length
val ys: Array[Byte] = new Array(3 * len) // worst case
var i = 0; var j = 0 // i for chars; j for bytes
while (i < len) { // fill ys with bytes
  val c = xs(i)
  if (c < 0x80) {
    ys(j) = c.toByte
    i = i + 1
    j = j + 1
  } else if (c < 0x800) {
    ys(j) = (0xc0 | (c >> 6)).toByte
    ys(j + 1) = (0x80 | (c & 0x3f)).toByte
    i = i + 1
    j = j + 2
  } else if (Character.isHighSurrogate(c)) {
    if (len - i < 2) throw new Exception("overflow")
    val d = xs(i + 1)
    val uc: Int = 
      if (Character.isLowSurrogate(d)) {
        Character.toCodePoint(c, d)
      } else {
        throw new Exception("malformed")
      }
    ys(j) = (0xf0 | ((uc >> 18))).toByte
    ys(j + 1) = (0x80 | ((uc >> 12) & 0x3f)).toByte
    ys(j + 2) = (0x80 | ((uc >>  6) & 0x3f)).toByte
    ys(j + 3) = (0x80 | (uc & 0x3f)).toByte
    i = i + 2 // 2 chars
    j = j + 4
  } else if (Character.isLowSurrogate(c)) {
    throw new Exception("malformed")
  } else {
    ys(j) = (0xe0 | (c >> 12)).toByte
    ys(j + 1) = (0x80 | ((c >> 6) & 0x3f)).toByte
    ys(j + 2) = (0x80 | (c & 0x3f)).toByte
    i = i + 1
    j = j + 3
  }
}
// check
println(new String(ys, 0, j, "UTF-8"))

Excuse me for using Scala language. If you have problems with converting this code to Java I can rewrite it. What about performance always check on real data (with JMH for example). This code looks very similar to what you can see in JDK[2] and Protobuf[3].

Select a random sample of results from a query result

SELECT  *
FROM    (
        SELECT  *
        FROM    mytable
        ORDER BY
                dbms_random.value
        )
WHERE rownum <= 1000

CORS: credentials mode is 'include'

If you are using CORS middleware and you want to send withCredentials boolean true, you can configure CORS like this:

_x000D_
_x000D_
var cors = require('cors');    _x000D_
app.use(cors({credentials: true, origin: 'http://localhost:5000'}));
_x000D_
_x000D_
_x000D_

`

Change image onmouseover

Thy to put a dot or two before the /

('src','./ico/view.hover.png')"

Installing Python 3 on RHEL

Three steps using Python 3.5 by Software Collections:

sudo yum install centos-release-scl
sudo yum install rh-python35
scl enable rh-python35 bash

Note that sudo is not needed for the last command. Now we can see that python 3 is the default for the current shell:

python --version
Python 3.5.1

Simply skip the last command if you'd rather have Python 2 as the default for the current shell.

Now let's say that your Python 3 scripts give you an error like /usr/bin/env: python3: No such file or directory. That's because the installation is usually done to an unusual path:

/opt/rh/rh-python35/root/bin/python3

The above would normally be a symlink. If you want python3 to be automatically added to the $PATH for all users on startup, one way to do this is adding a file like:

sudo vim /etc/profile.d/rh-python35.sh

Which would have something like:

#!/bin/bash

PATH=$PATH:/opt/rh/rh-python35/root/bin/

And now after a reboot, if we do

python3 --version

It should just work. One exception would be an auto-generated user like "jenkins" in a Jenkins server which doesn't have a shell. In that case, manually adding the path to $PATH in scripts would be one way to go.

Finally, if you're using sudo pip3 to install packages, but it tells you that pip3 cannot be found, it could be that you have a secure_path in /etc/sudoers. Checking with sudo visudo should confirm that. To temporarily use the standard PATH when running commands you can do, for example:

sudo env "PATH=$PATH" pip3 --version

See this question for more details.

NOTE: There is a newer Python 3.6 by Software Collections, but I wouldn't recommend it at this time, because I had major headaches trying to install Pycurl. For Python 3.5 that isn't an issue because I just did sudo yum install sclo-python35-python-pycurl which worked out of the box.

Error handling in C code

There's a nice set of slides from CMU's CERT with recommendations for when to use each of the common C (and C++) error handling techniques. One of the best slides is this decision tree:

Error Handling Decision Tree

I would personally change two things about this flowcart.

First, I would clarify that sometimes objects should use return values to indicate errors. If a function only extracts data from an object but doesn't mutate the object, then the integrity of the object itself is not at risk and indicating errors using a return value is more appropriate.

Second, it's not always appropriate to use exceptions in C++. Exceptions are good because they can reduce the amount of source code devoted to error handling, they mostly don't affect function signatures, and they're very flexible in what data they can pass up the callstack. On the other hand, exceptions might not be the right choice for a few reasons:

  1. C++ exceptions have very particular semantics. If you don't want those semantics, then C++ exceptions are a bad choice. An exception must be dealt with immediately after being thrown and the design favors the case where an error will need to unwind the callstack a few levels.

  2. C++ functions that throw exceptions can't later be wrapped to not throw exceptions, at least not without paying the full cost of exceptions anyway. Functions that return error codes can be wrapped to throw C++ exceptions, making them more flexible. C++'s new gets this right by providing a non-throwing variant.

  3. C++ exceptions are relatively expensive but this downside is mostly overblown for programs making sensible use of exceptions. A program simply shouldn't throw exceptions on a codepath where performance is a concern. It doesn't really matter how fast your program can report an error and exit.

  4. Sometimes C++ exceptions are not available. Either they're literally not available in one's C++ implementation, or one's code guidelines ban them.


Since the original question was about a multithreaded context, I think the local error indicator technique (what's described in SirDarius's answer) was underappreciated in the original answers. It's threadsafe, doesn't force the error to be immediately dealt with by the caller, and can bundle arbitrary data describing the error. The downside is that it must be held by an object (or I suppose somehow associated externally) and is arguably easier to ignore than a return code.

How to access private data members outside the class without making "friend"s?


EDIT:
Just saw you edited the question to say that you don't want to use friend.
Then the answer is:

NO you can't, atleast not in a portable way approved by the C++ standard.


The later part of the Answer, was previous to the Q edit & I leave it here for benefit of >those who would want to understand a few concepts & not just looking an Answer to the >Question.


If you have members under a Private access specifier then those members are only accessible from within the class. No outside Access is allowed.

An Source Code Example:

class MyClass
{
    private:
        int c;
    public:
    void doSomething()
    {
        c = 10;    //Allowed 
    }
};

int main()
{
    MyClass obj;
    obj.c = 30;     //Not Allowed, gives compiler error
    obj.doSomething();  //Allowed
}

A Workaround: friend to rescue
To access the private member, you can declare a function/class as friend of that particular class, and then the member will be accessible inside that function or class object without access specifier check.

Modified Code Sample:

class MyClass
{
    private:
        int c;

    public:
    void doSomething()
    {
        c = 10;    //Allowed 
    }

    friend void MytrustedFriend();    
};

void MytrustedFriend()
{
        MyClass obj;
        obj.c = 10; //Allowed
}

int main()
{
    MyClass obj;
    obj.c = 30;     //Not Allowed, gives compiler error
    obj.doSomething();  //Allowed
    //Call the friend function
    MytrustedFriend();
    return 0;
}

In git, what is the difference between merge --squash and rebase?

Both git merge --squash and git rebase --interactive can produce a "squashed" commit.
But they serve different purposes.

will produce a squashed commit on the destination branch, without marking any merge relationship.
(Note: it does not produce a commit right away: you need an additional git commit -m "squash branch")
This is useful if you want to throw away the source branch completely, going from (schema taken from SO question):

 git checkout stable

      X                   stable
     /                   
a---b---c---d---e---f---g tmp

to:

git merge --squash tmp
git commit -m "squash tmp"

      X-------------------G stable
     /                   
a---b---c---d---e---f---g tmp

and then deleting tmp branch.


Note: git merge has a --commit option, but it cannot be used with --squash. It was never possible to use --commit and --squash together.
Since Git 2.22.1 (Q3 2019), this incompatibility is made explicit:

See commit 1d14d0c (24 May 2019) by Vishal Verma (reloadbrain).
(Merged by Junio C Hamano -- gitster -- in commit 33f2790, 25 Jul 2019)

merge: refuse --commit with --squash

Previously, when --squash was supplied, 'option_commit' was silently dropped. This could have been surprising to a user who tried to override the no-commit behavior of squash using --commit explicitly.

git/git builtin/merge.c#cmd_merge() now includes:

if (option_commit > 0)
    die(_("You cannot combine --squash with --commit."));

replays some or all of your commits on a new base, allowing you to squash (or more recently "fix up", see this SO question), going directly to:

git checkout tmp
git rebase -i stable

      stable
      X-------------------G tmp
     /                     
a---b

If you choose to squash all commits of tmp (but, contrary to merge --squash, you can choose to replay some, and squashing others).

So the differences are:

  • squash does not touch your source branch (tmp here) and creates a single commit where you want.
  • rebase allows you to go on on the same source branch (still tmp) with:
    • a new base
    • a cleaner history

Oracle : how to subtract two dates and get minutes of the result

When you subtract two dates in Oracle, you get the number of days between the two values. So you just have to multiply to get the result in minutes instead:

SELECT (date2 - date1) * 24 * 60 AS minutesBetween
FROM ...

How to align an indented line in a span that wraps into multiple lines?

display:block;

then you've got a block element and the margin is added to all lines.

While it's true that a span is semantically not a block element, there are cases where you don't have control of the pages DOM. This answer is inteded for those.

Add floating point value to android resources/values

Although I've used the accepted answer in the past, it seems with the current Build Tools it is possible to do:

   <dimen name="listAvatarWidthPercent">0.19</dimen>

I'm using Build Tools major version 29.

How to minify php page html output?

You can use a well tested Java minifier like HTMLCompressor by invoking it using passthru (exec).
Remember to redirect console using 2>&1

This however may not be useful, if speed is a concern. I use it for static php output

What are the First and Second Level caches in (N)Hibernate?

1.1) First-level cache

First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.

1.2) Second-level cache

Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will be available to the entire application, not bound to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also.

Quoted from: http://javabeat.net/introduction-to-hibernate-caching/

Count how many files in directory PHP

<?php echo(count(array_slice(scandir($directory),2))); ?>

array_slice works similary like substr function, only it works with arrays.

For example, this would chop out first two array keys from array:

$key_zero_one = array_slice($someArray, 0, 2);

And if You ommit the first parameter, like in first example, array will not contain first two key/value pairs *('.' and '..').

How to initialize HashSet values by construction?

With Eclipse Collections there are a few different ways to initialize a Set containing the characters 'a' and 'b' in one statement. Eclipse Collections has containers for both object and primitive types, so I illustrated how you could use a Set<String> or CharSet in addition to mutable, immutable, synchronized and unmodifiable versions of both.

Set<String> set =
    Sets.mutable.with("a", "b");
HashSet<String> hashSet =
    Sets.mutable.with("a", "b").asLazy().into(new HashSet<String>());
Set<String> synchronizedSet =
    Sets.mutable.with("a", "b").asSynchronized();
Set<String> unmodifiableSet =
    Sets.mutable.with("a", "b").asUnmodifiable();

MutableSet<String> mutableSet =
    Sets.mutable.with("a", "b");
MutableSet<String> synchronizedMutableSet =
    Sets.mutable.with("a", "b").asSynchronized();
MutableSet<String> unmodifiableMutableSet =
    Sets.mutable.with("a", "b").asUnmodifiable();

ImmutableSet<String> immutableSet =
    Sets.immutable.with("a", "b");
ImmutableSet<String> immutableSet2 =
    Sets.mutable.with("a", "b").toImmutable();

CharSet charSet =
    CharSets.mutable.with('a', 'b');
CharSet synchronizedCharSet =
    CharSets.mutable.with('a', 'b').asSynchronized();
CharSet unmodifiableCharSet =
    CharSets.mutable.with('a', 'b').asUnmodifiable();
MutableCharSet mutableCharSet =
    CharSets.mutable.with('a', 'b');
ImmutableCharSet immutableCharSet =
    CharSets.immutable.with('a', 'b');
ImmutableCharSet immutableCharSet2 =
    CharSets.mutable.with('a', 'b').toImmutable();

Note: I am a committer for Eclipse Collections.

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

If the class uses as a parameterized type, it can declare an array of type T[], but it cannot directly instantiate such an array. Instead, a common approach is to instantiate an array of type Object[], and then make a narrowing cast to type T[], as shown in the following:

  public class Portfolio<T> {
  T[] data;
 public Portfolio(int capacity) {
   data = new T[capacity];                 // illegal; compiler error
   data = (T[]) new Object[capacity];      // legal, but compiler warning
 }
 public T get(int index) { return data[index]; }
 public void set(int index, T element) { data[index] = element; }
}

How to Update Multiple Array Elements in mongodb

I'm amazed this still hasn't been addressed in mongo. Overall mongo doesn't seem to be great when dealing with sub-arrays. You can't count sub-arrays simply for example.

I used Javier's first solution. Read the array into events then loop through and build the set exp:

var set = {}, i, l;
for(i=0,l=events.length;i<l;i++) {
  if(events[i].profile == 10) {
    set['events.' + i + '.handled'] = 0;
  }
}

.update(objId, {$set:set});

This can be abstracted into a function using a callback for the conditional test

Detect if an input has text in it using CSS -- on a page I am visiting and do not control?

do it on the HTML part like this:

<input type="text" name="Example" placeholder="Example" required/>

The required parameter will require it to have text in the input field in order to be valid.

Errors in pom.xml with dependencies (Missing artifact...)

SIMPLE..

First check with the closing tag of project. It should be placed after all the dependency tags are closed.This way I solved my error. --Sush happy coding :)

Sending HTTP Post request with SOAP action using org.apache.http

This is a full working example :

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public void callWebService(String soapAction, String soapEnvBody)  throws IOException {
    // Create a StringEntity for the SOAP XML.
    String body ="<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://example.com/v1.0/Records\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><SOAP-ENV:Body>"+soapEnvBody+"</SOAP-ENV:Body></SOAP-ENV:Envelope>";
    StringEntity stringEntity = new StringEntity(body, "UTF-8");
    stringEntity.setChunked(true);

    // Request parameters and other properties.
    HttpPost httpPost = new HttpPost("http://example.com?soapservice");
    httpPost.setEntity(stringEntity);
    httpPost.addHeader("Accept", "text/xml");
    httpPost.addHeader("SOAPAction", soapAction);

    // Execute and get the response.
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity entity = response.getEntity();

    String strResponse = null;
    if (entity != null) {
        strResponse = EntityUtils.toString(entity);
    }
}

Could not resolve Spring property placeholder

It's definitely not a problem with propeties file not being found, since in that case another exception is thrown.

Make sure that you actually have a value with key idm.url in your idm.properties.

What is the equivalent of "none" in django templates?

isoperator : New in Django 1.10

{% if somevar is None %}
  This appears if somevar is None, or if somevar is not found in the context.
{% endif %}

How to show a GUI message box from a bash script in linux?

Zenity is really the exact tool that I think that you are looking for.

or

zenity --help

String to char array Java

A string to char array is as simple as

String str = "someString"; 
char[] charArray = str.toCharArray();

Can you explain a little more on what you are trying to do?

* Update *

if I am understanding your new comment, you can use a byte array and example is provided.

byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();

for (byte b : bytes) {
   System.out.format("0x%x ", b);
}

With the following output

0x65 0x10 0xf3 0x29

How can I count the number of elements with same class?

Simplest example:

_x000D_
_x000D_
document.getElementById("demo").innerHTML = "count: " + document.querySelectorAll('.test').length;
_x000D_
<html>_x000D_
    <body>_x000D_
    _x000D_
    <p id="demo"></p>_x000D_
    <ul>_x000D_
      <li class="test">Coffee</li>_x000D_
      <li class="test">Milk</li>_x000D_
      <li class="test">Soda</li>_x000D_
    </ul>_x000D_
_x000D_
 </body> _x000D_
 </html>
_x000D_
_x000D_
_x000D_

Why do symbols like apostrophes and hyphens get replaced with black diamonds on my website?

I have the same issue in my asp.net web application. I solved by this link

I just replace ' with &rsquo; text like below and my site in browser show apostrophe without rectangle around as in question ask.

Original text in html page
Click the Edit button to change a field's label, width and type-ahead options

Replace text in html page
Click the Edit button to change a field&rsquo;s label, width and type-ahead options

Fetching data from MySQL database to html dropdown list

# here database details      
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');

$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);

echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
    echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";
}
echo "</select>";

# here username is the column of my table(userregistration)
# it works perfectly

Why does git perform fast-forward merges by default?

Fast-forward merging makes sense for short-lived branches, but in a more complex history, non-fast-forward merging may make the history easier to understand, and make it easier to revert a group of commits.

Warning: Non-fast-forwarding has potential side effects as well. Please review https://sandofsky.com/blog/git-workflow.html, avoid the 'no-ff' with its "checkpoint commits" that break bisect or blame, and carefully consider whether it should be your default approach for master.

alt text
(From nvie.com, Vincent Driessen, post "A successful Git branching model")

Incorporating a finished feature on develop

Finished features may be merged into the develop branch to add them to the upcoming release:

$ git checkout develop
Switched to branch 'develop'
$ git merge --no-ff myfeature
Updating ea1b82a..05e9557
(Summary of changes)
$ git branch -d myfeature
Deleted branch myfeature (was 05e9557).
$ git push origin develop

The --no-ff flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward. This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature.

Jakub Narebski also mentions the config merge.ff:

By default, Git does not create an extra merge commit when merging a commit that is a descendant of the current commit. Instead, the tip of the current branch is fast-forwarded.
When set to false, this variable tells Git to create an extra merge commit in such a case (equivalent to giving the --no-ff option from the command line).
When set to 'only', only such fast-forward merges are allowed (equivalent to giving the --ff-only option from the command line).


The fast-forward is the default because:

  • short-lived branches are very easy to create and use in Git
  • short-lived branches often isolate many commits that can be reorganized freely within that branch
  • those commits are actually part of the main branch: once reorganized, the main branch is fast-forwarded to include them.

But if you anticipate an iterative workflow on one topic/feature branch (i.e., I merge, then I go back to this feature branch and add some more commits), then it is useful to include only the merge in the main branch, rather than all the intermediate commits of the feature branch.

In this case, you can end up setting this kind of config file:

[branch "master"]
# This is the list of cmdline options that should be added to git-merge 
# when I merge commits into the master branch.

# The option --no-commit instructs git not to commit the merge
# by default. This allows me to do some final adjustment to the commit log
# message before it gets commited. I often use this to add extra info to
# the merge message or rewrite my local branch names in the commit message
# to branch names that are more understandable to the casual reader of the git log.

# Option --no-ff instructs git to always record a merge commit, even if
# the branch being merged into can be fast-forwarded. This is often the
# case when you create a short-lived topic branch which tracks master, do
# some changes on the topic branch and then merge the changes into the
# master which remained unchanged while you were doing your work on the
# topic branch. In this case the master branch can be fast-forwarded (that
# is the tip of the master branch can be updated to point to the tip of
# the topic branch) and this is what git does by default. With --no-ff
# option set, git creates a real merge commit which records the fact that
# another branch was merged. I find this easier to understand and read in
# the log.

mergeoptions = --no-commit --no-ff

The OP adds in the comments:

I see some sense in fast-forward for [short-lived] branches, but making it the default action means that git assumes you... often have [short-lived] branches. Reasonable?

Jefromi answers:

I think the lifetime of branches varies greatly from user to user. Among experienced users, though, there's probably a tendency to have far more short-lived branches.

To me, a short-lived branch is one that I create in order to make a certain operation easier (rebasing, likely, or quick patching and testing), and then immediately delete once I'm done.
That means it likely should be absorbed into the topic branch it forked from, and the topic branch will be merged as one branch. No one needs to know what I did internally in order to create the series of commits implementing that given feature.

More generally, I add:

it really depends on your development workflow:

  • if it is linear, one branch makes sense.
  • If you need to isolate features and work on them for a long period of time and repeatedly merge them, several branches make sense.

See "When should you branch?"

Actually, when you consider the Mercurial branch model, it is at its core one branch per repository (even though you can create anonymous heads, bookmarks and even named branches)
See "Git and Mercurial - Compare and Contrast".

Mercurial, by default, uses anonymous lightweight codelines, which in its terminology are called "heads".
Git uses lightweight named branches, with injective mapping to map names of branches in remote repository to names of remote-tracking branches.
Git "forces" you to name branches (well, with the exception of a single unnamed branch, which is a situation called a "detached HEAD"), but I think this works better with branch-heavy workflows such as topic branch workflow, meaning multiple branches in a single repository paradigm.

SELECT list is not in GROUP BY clause and contains nonaggregated column

As @Brian Riley already said you should either remove 1 column in your select

select countrylanguage.language ,sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language
order by sum(country.population*countrylanguage.percentage) desc ;

or add it to your grouping

select countrylanguage.language, country.code, sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language, country.code
order by sum(country.population*countrylanguage.percentage) desc ;

'git status' shows changed files, but 'git diff' doesn't

I added the file to the index:

git add file_name

and then ran:

git diff --cached file_name

You can see the description of git diff here.

If you need to undo your git add, then please see here: How to undo 'git add' before commit?

Creating an abstract class in Objective-C

Can't you just create a delegate?

A delegate is like an abstract base class in the sense that you say what functions need to be defined, but you don't actually define them.

Then whenever you implement your delegate (i.e abstract class) you are warned by the compiler of what optional and mandatory functions you need to define behavior for.

This sounds like an abstract base class to me.

Accessing localhost (xampp) from another computer over LAN network - how to?

Sometimes your firewall can be the problem. Make sure you've disabled your antivirus firewall monitoring. It worked for me.

Calculate MD5 checksum for a file

Here is a slightly simpler version that I found. It reads the entire file in one go and only requires a single using directive.

byte[] ComputeHash(string filePath)
{
    using (var md5 = MD5.Create())
    {
        return md5.ComputeHash(File.ReadAllBytes(filePath));
    }
}

Use curly braces to initialize a Set in Python

You need to do empty_set = set() to initialize an empty set. {} is an empty dict.

How to run sql script using SQL Server Management Studio?

Open SQL Server Management Studio > File > Open > File > Choose your .sql file (the one that contains your script) > Press Open > the file will be opened within SQL Server Management Studio, Now all what you need to do is to press Execute button.

How to remove multiple indexes from a list at the same time?

another option (in place, any combination of indices):

_marker = object()

for i in indices:
    my_list[i] = _marker  # marked for deletion

obj[:] = [v for v in my_list if v is not _marker]

Bootstrap table without stripe / borders

Use hidden instead of none:

.hide-bottom {
    border-bottom-style: hidden;
}

Convert Json String to C# Object List

Please make sure that all properties are both the getter and setter. In case, any property is getter only, it will cause the reverting the List to original data as the JSON string is typed.

Please refer to the following code snippet for the same: Model:

 public class Person
{
    public int ID { get; set; }
    // following 2 lines are cause of error
    //public string Name { get { return string.Format("{0} {1}", First, Last); } }
    //public string Country { get { return Countries[CountryID]; } }
    public int CountryID { get; set; }
    public bool Active { get; set; }
    public string First { get; set; }
    public string Last { get; set; }
    public DateTime Hired { get; set; }
}
public class ModelObj
    {
        public string Str { get; set; }
        public List<Person> Persons { get; set; }
    }

Controller:

 [HttpPost]
    public ActionResult Index(FormCollection collection)
    {
        var data = new ModelObj();
        data.Str = (string)collection.GetValue("Str").ConvertTo(typeof(string));
        var personsString = (string)collection.GetValue("Persons").ConvertTo(typeof(string));
        using (var textReader = new StringReader(personsString))
        {
            using (var reader = new JsonTextReader(textReader))
            {
                data.Persons = new JsonSerializer().Deserialize(reader, typeof(List<Person>)) as List<Person>; 
            }
        }

        return View(data);
    }

How to have a a razor action link open in a new tab?

That won't compile since UrlHelper.Action(string,string,object,object) doesn't exist.

UrlHelper.Action will only generate Urls based on the action you provide, not <a> markup. If you want to add an HtmlAttribute (like target="_blank", to open link in new tab) you can either:

  • Add the target attribute to the <a> element by yourself:

    <a href="@Url.Action("RunReport", "Performance",
        new { reportView = Model.ReportView.ToString() })",
        target = "_blank" type="submit" id="runReport" class="button Secondary">
        @Reports.RunReport
    </a>
    
  • Use Html.ActionLink to generate an <a> markup element:

    @Html.ActionLink("Report View", "RunReport", null, new { target = "_blank" })
    

Python datetime to string without microsecond component

Keep the first 19 characters that you wanted via slicing:

>>> str(datetime.datetime.now())[:19]
'2011-11-03 14:37:50'

Why I can't access remote Jupyter Notebook server?

I'm using Anaconda3 on Windows 10. When you install it rembember to flag "add to Enviroment Variables".


Prerequisite: A notebook configuration file

Check to see if you have a notebook configuration file, jupyter_notebook_config.py. The default location for this file is your Jupyter folder located in your home directory:

  • Windows: C:\\Users\\USERNAME\\.jupyter\\jupyter_notebook_config.py
  • OS X: /Users/USERNAME/.jupyter/jupyter_notebook_config.py
  • Linux: /home/USERNAME/.jupyter/jupyter_notebook_config.py

If you don't already have a Jupyter folder, or if your Jupyter folder doesn't contain a notebook configuration file, run the following command:

$ jupyter notebook --generate-config

This command will create the Jupyter folder if necessary, and create notebook configuration file, jupyter_notebook_config.py, in this folder.


By default, Jupyter Notebook only accepts connections from localhost.

Edit the jupyter_notebook_config.py file as following to accept all incoming connections:

c.NotebookApp.allow_origin = '*' #allow all origins

You'll also need to change the IPs that the notebook will listen on:

c.NotebookApp.ip = '0.0.0.0' # listen on all IPs

How to switch back to 'master' with git?

I'm trying to sort of get my head around what's going on over there. Is there anything IN your "example" folder? Git doesn't track empty folders.

If you branched and switched to your new branch then made a new folder and left it empty, and then did "git commit -a", you wouldn't get that new folder in the commit.

Which means it's untracked, which means checking out a different branch wouldn't remove it.

Android: Difference between onInterceptTouchEvent and dispatchTouchEvent?

Supplemental Answer

Here are some visual supplements to the other answers. My full answer is here.

enter image description here

enter image description here

The dispatchTouchEvent() method of a ViewGroup uses onInterceptTouchEvent() to choose whether it should immediately handle the touch event (with onTouchEvent()) or continue notifying the dispatchTouchEvent() methods of its children.

How to use componentWillMount() in React Hooks?

You can hack the useMemo hook to imitate a componentWillMount lifecycle event. Just do:

const Component = () => {
   useMemo(() => {
     // componentWillMount events
   },[]);
   useEffect(() => {
     // componentDidMount events
     return () => {
       // componentWillUnmount events
     }
   }, []);
};

You would need to keep the useMemo hook before anything that interacts with your state. This is not how it is intended but it worked for me for all componentWillMount issues.

This works because useMemo doesnt require to actually return a value and you dont have to actually use it as anything, but since it memorizes a value based on dependencies which will only run once ("[]") and its on top of our component it runs once when the component mounts before anything else.

How do I define a method in Razor?

You can simply declare them as local functions in a razor block (i.e. @{}).

@{
    int Add(int x, int y)
    {
        return x + y;
    }
}

<div class="container">
    <p>
        @Add(2, 5)
    </p>
</div>

Convert ndarray from float64 to integer

Use .astype.

>>> a = numpy.array([1, 2, 3, 4], dtype=numpy.float64)
>>> a
array([ 1.,  2.,  3.,  4.])
>>> a.astype(numpy.int64)
array([1, 2, 3, 4])

See the documentation for more options.

Reading int values from SqlDataReader

you can use

reader.GetInt32(3);

to read an 32 bit int from the data reader.

If you know the type of your data I think its better to read using the Get* methods which are strongly typed rather than just reading an object and casting.

Have you considered using

reader.GetInt32(reader.GetOrdinal(columnName)) 

rather than accessing by position. This makes your code less brittle and will not break if you change the query to add new columns before the existing ones. If you are going to do this in a loop, cache the ordinal first.

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

How to get store information in Magento?

Just for information sake, in regards to my need... The answer I was looking for here was:

Mage::app()->getStore()->getGroup()->getName()

That is referenced on the admin page, where one can manage multiple stores... admin/system_store, I wanted to retrieve the store group title...

SQL Server - Adding a string to a text column (concat equivalent)

UPDATE test SET a = CONCAT(a, "more text")

How to generate keyboard events?

user648852's idea at least for me works great for OS X, here is the code to do it:

#!/usr/bin/env python

import time
from Quartz.CoreGraphics import CGEventCreateKeyboardEvent
from Quartz.CoreGraphics import CGEventPost

# Python releases things automatically, using CFRelease will result in a scary error
#from Quartz.CoreGraphics import CFRelease

from Quartz.CoreGraphics import kCGHIDEventTap

# From http://stackoverflow.com/questions/281133/controlling-the-mouse-from-python-in-os-x
# and from https://developer.apple.com/library/mac/documentation/Carbon/Reference/QuartzEventServicesRef/index.html#//apple_ref/c/func/CGEventCreateKeyboardEvent


def KeyDown(k):
    keyCode, shiftKey = toKeyCode(k)

    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))
        time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))
    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))
        time.sleep(0.0001)

def KeyUp(k):
    keyCode, shiftKey = toKeyCode(k)

    time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))
    time.sleep(0.0001)

def KeyPress(k):
    keyCode, shiftKey = toKeyCode(k)

    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))
        time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))
    time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))
    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))
        time.sleep(0.0001)



# From http://stackoverflow.com/questions/3202629/where-can-i-find-a-list-of-mac-virtual-key-codes

def toKeyCode(c):
    shiftKey = False
    # Letter
    if c.isalpha():
        if not c.islower():
            shiftKey = True
            c = c.lower()

    if c in shiftChars:
        shiftKey = True
        c = shiftChars[c]
    if c in keyCodeMap:
        keyCode = keyCodeMap[c]
    else:
        keyCode = ord(c)
    return keyCode, shiftKey

shiftChars = {
    '~': '`',
    '!': '1',
    '@': '2',
    '#': '3',
    '$': '4',
    '%': '5',
    '^': '6',
    '&': '7',
    '*': '8',
    '(': '9',
    ')': '0',
    '_': '-',
    '+': '=',
    '{': '[',
    '}': ']',
    '|': '\\',
    ':': ';',
    '"': '\'',
    '<': ',',
    '>': '.',
    '?': '/'
}


keyCodeMap = {
    'a'                 : 0x00,
    's'                 : 0x01,
    'd'                 : 0x02,
    'f'                 : 0x03,
    'h'                 : 0x04,
    'g'                 : 0x05,
    'z'                 : 0x06,
    'x'                 : 0x07,
    'c'                 : 0x08,
    'v'                 : 0x09,
    'b'                 : 0x0B,
    'q'                 : 0x0C,
    'w'                 : 0x0D,
    'e'                 : 0x0E,
    'r'                 : 0x0F,
    'y'                 : 0x10,
    't'                 : 0x11,
    '1'                 : 0x12,
    '2'                 : 0x13,
    '3'                 : 0x14,
    '4'                 : 0x15,
    '6'                 : 0x16,
    '5'                 : 0x17,
    '='                 : 0x18,
    '9'                 : 0x19,
    '7'                 : 0x1A,
    '-'                 : 0x1B,
    '8'                 : 0x1C,
    '0'                 : 0x1D,
    ']'                 : 0x1E,
    'o'                 : 0x1F,
    'u'                 : 0x20,
    '['                 : 0x21,
    'i'                 : 0x22,
    'p'                 : 0x23,
    'l'                 : 0x25,
    'j'                 : 0x26,
    '\''                : 0x27,
    'k'                 : 0x28,
    ';'                 : 0x29,
    '\\'                : 0x2A,
    ','                 : 0x2B,
    '/'                 : 0x2C,
    'n'                 : 0x2D,
    'm'                 : 0x2E,
    '.'                 : 0x2F,
    '`'                 : 0x32,
    'k.'                : 0x41,
    'k*'                : 0x43,
    'k+'                : 0x45,
    'kclear'            : 0x47,
    'k/'                : 0x4B,
    'k\n'               : 0x4C,
    'k-'                : 0x4E,
    'k='                : 0x51,
    'k0'                : 0x52,
    'k1'                : 0x53,
    'k2'                : 0x54,
    'k3'                : 0x55,
    'k4'                : 0x56,
    'k5'                : 0x57,
    'k6'                : 0x58,
    'k7'                : 0x59,
    'k8'                : 0x5B,
    'k9'                : 0x5C,

    # keycodes for keys that are independent of keyboard layout
    '\n'                : 0x24,
    '\t'                : 0x30,
    ' '                 : 0x31,
    'del'               : 0x33,
    'delete'            : 0x33,
    'esc'               : 0x35,
    'escape'            : 0x35,
    'cmd'               : 0x37,
    'command'           : 0x37,
    'shift'             : 0x38,
    'caps lock'         : 0x39,
    'option'            : 0x3A,
    'ctrl'              : 0x3B,
    'control'           : 0x3B,
    'right shift'       : 0x3C,
    'rshift'            : 0x3C,
    'right option'      : 0x3D,
    'roption'           : 0x3D,
    'right control'     : 0x3E,
    'rcontrol'          : 0x3E,
    'fun'               : 0x3F,
    'function'          : 0x3F,
    'f17'               : 0x40,
    'volume up'         : 0x48,
    'volume down'       : 0x49,
    'mute'              : 0x4A,
    'f18'               : 0x4F,
    'f19'               : 0x50,
    'f20'               : 0x5A,
    'f5'                : 0x60,
    'f6'                : 0x61,
    'f7'                : 0x62,
    'f3'                : 0x63,
    'f8'                : 0x64,
    'f9'                : 0x65,
    'f11'               : 0x67,
    'f13'               : 0x69,
    'f16'               : 0x6A,
    'f14'               : 0x6B,
    'f10'               : 0x6D,
    'f12'               : 0x6F,
    'f15'               : 0x71,
    'help'              : 0x72,
    'home'              : 0x73,
    'pgup'              : 0x74,
    'page up'           : 0x74,
    'forward delete'    : 0x75,
    'f4'                : 0x76,
    'end'               : 0x77,
    'f2'                : 0x78,
    'page down'         : 0x79,
    'pgdn'              : 0x79,
    'f1'                : 0x7A,
    'left'              : 0x7B,
    'right'             : 0x7C,
    'down'              : 0x7D,
    'up'                : 0x7E
}

AWS Lambda import module error in python

@nithin, AWS released layers concept inside Lambda functions. You can create your layer and there you can upload as much as libraries and then you can connect the layer with the lambda functions. For more details: https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html

"unmappable character for encoding" warning in Java

I had the same problem, where the character index reported in the java error message was incorrect. I narrowed it down to the double quote characters just prior to the reported position being hex 094 (cancel instead of quote, but represented as a quote) instead of hex 022. As soon as I swapped for the hex 022 variant all was fine.

How can I stop .gitignore from appearing in the list of untracked files?

The idea is to put files that are specific to your project into the .gitignore file and (as already mentioned) add it to the repository. For example .pyc and .o files, logs that the testsuite creates, some fixtures etc.

For files that your own setup creates but which will not necessarily appear for every user (like .swp files if you use vim, hidden ecplise directories and the like), you should use .git/info/exclude (as already mentioned).

Horizontal line using HTML/CSS

This might be your problem:

height: .05em;

Chrome is a bit funky with decimals, so try a fixed-pixel height:

height: 2px;

Can I assume (bool)true == (int)1 for any C++ compiler?

According to the standard, you should be safe with that assumption. The C++ bool type has two values - true and false with corresponding values 1 and 0.

The thing to watch about for is mixing bool expressions and variables with BOOL expression and variables. The latter is defined as FALSE = 0 and TRUE != FALSE, which quite often in practice means that any value different from 0 is considered TRUE.

A lot of modern compilers will actually issue a warning for any code that implicitly tries to cast from BOOL to bool if the BOOL value is different than 0 or 1.

Font Awesome & Unicode

Add font weight 900..its working for me

font-weight: 900;

log4j logging hierarchy order

OFF
FATAL
ERROR
WARN
INFO
DEBUG
TRACE
ALL

Reset MySQL root password using ALTER USER statement after install on Mac

ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';

Use this line...

Move UIView up when the keyboard appears in iOS

Here you go. I have used this code with UIView, though. You should be able to make those adjustments for scrollview.

    func addKeyboardNotifications() {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(keyboardWillShow(notification:)),
                                               name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(keyboardWillHide(notification:)),
                                               name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    func keyboardWillShow(notification: NSNotification) {

        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
// if using constraints            
// bottomViewBottomSpaceConstraint.constant = keyboardSize.height
self.view.frame.origin.y -= keyboardSize.height
            UIView.animate(withDuration: duration) {
                self.view.layoutIfNeeded()
            }
        }
    }
    func keyboardWillHide(notification: NSNotification) {

        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
//if using constraint
//        bottomViewBottomSpaceConstraint.constant = 0
self.view.frame.origin.y = 0
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
    }

Don't forget to remove notifications at right place.

func removeKeyboardNotifications() {
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

Displaying all table names in php from MySQL database

Queries should look like :

SHOW TABLES

SHOW TABLES FROM mydatabase

SHOW TABLES FROM mydatabase LIKE "tab%"

Things from the MySQL documentation in square brackets [] are optional.

Styling the last td in a table with css

For IE, how about using a CSS expression:

<style type="text/css">
table td { 
  h: expression(this.style.border = (this == this.parentNode.lastChild ? 'none' : '1px solid #000' ) );
}
</style>

Using NSLog for debugging

The proper way of using NSLog, as the warning tries to explain, is the use of a formatter, instead of passing in a literal:

Instead of:

NSString *digit = [[sender titlelabel] text];
NSLog(digit);

Use:

NSString *digit = [[sender titlelabel] text];
NSLog(@"%@",digit);

It will still work doing that first way, but doing it this way will get rid of the warning.

Use jquery to set value of div tag

When using the .html() method, a htmlString must be the parameter. (source) Put your string inside a HTML tag and it should work or use .text() as suggested by farzad.

Example:

<div class="demo-container">
    <div class="demo-box">Demonstration Box</div>
</div>

<script type="text/javascript">
$("div.demo-container").html( "<p>All new content. <em>You bet!</em></p>" );
</script>

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

BeautifulSoup getText from between <p>, not picking up subsequent paragraphs

This works well for specific articles where the text is all wrapped in <p> tags. Since the web is an ugly place, it's not always the case.

Often, websites will have text scattered all over, wrapped in different types of tags (e.g. maybe in a <span> or a <div>, or an <li>).

To find all text nodes in the DOM, you can use soup.find_all(text=True).

This is going to return some undesired text, like the contents of <script> and <style> tags. You'll need to filter out the text contents of elements you don't want.

blacklist = [
  'style',
  'script',
  # other elements,
]

text_elements = [t for t in soup.find_all(text=True) if t.parent.name not in blacklist]

If you are working with a known set of tags, you can tag the opposite approach:

whitelist = [
  'p'
]

text_elements = [t for t in soup.find_all(text=True) if t.parent.name in whitelist]

What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?

For any array of length n, elements of the array will have an index from 0 to n-1.

If your program is trying to access any element (or memory) having array index greater than n-1, then Java will throw ArrayIndexOutOfBoundsException

So here are two solutions that we can use in a program

  1. Maintaining count:

    for(int count = 0; count < array.length; count++) {
        System.out.println(array[count]);
    }
    

    Or some other looping statement like

    int count = 0;
    while(count < array.length) {
        System.out.println(array[count]);
        count++;
    }
    
  2. A better way go with a for each loop, in this method a programmer has no need to bother about the number of elements in the array.

    for(String str : array) {
        System.out.println(str);
    }
    

How to display databases in Oracle 11g using SQL*Plus

Oracle does not have a simple database model like MySQL or MS SQL Server. I find the closest thing is to query the tablespaces and the corresponding users within them.

For example, I have a DEV_DB tablespace with all my actual 'databases' within them:

SQL> SELECT TABLESPACE_NAME FROM USER_TABLESPACES;

Resulting in:

SYSTEM
SYSAUX
UNDOTBS1
TEMP
USERS
EXAMPLE
DEV_DB

It is also possible to query the users in all tablespaces:

SQL> select USERNAME, DEFAULT_TABLESPACE from DBA_USERS;

Or within a specific tablespace (using my DEV_DB tablespace as an example):

SQL> select USERNAME, DEFAULT_TABLESPACE from DBA_USERS where DEFAULT_TABLESPACE = 'DEV_DB';

ROLES DEV_DB
DATAWARE DEV_DB
DATAMART DEV_DB
STAGING DEV_DB

$('body').on('click', '.anything', function(){})

If you want to capture click on everything then do

$("*").click(function(){
//code here
}

I use this for selector: http://api.jquery.com/all-selector/

This is used for handling clicks: http://api.jquery.com/click/

And then use http://api.jquery.com/event.preventDefault/

To stop normal clicking actions.

Calling @Html.Partial to display a partial view belonging to a different controller

That's no problem.

@Html.Partial("../Controller/View", model)

or

@Html.Partial("~/Views/Controller/View.cshtml", model)

Should do the trick.

If you want to pass through the (other) controller, you can use:

@Html.Action("action", "controller", parameters)

or any of the other overloads

Get a list of all the files in a directory (recursive)

The following works for me in Gradle / Groovy for build.gradle for an Android project, without having to import groovy.io.FileType (NOTE: Does not recurse subdirectories, but when I found this solution I no longer cared about recursion, so you may not either):

FileCollection proGuardFileCollection = files { file('./proguard').listFiles() }
proGuardFileCollection.each {
    println "Proguard file located and processed: " + it
}

Simple (non-secure) hash function for JavaScript?

Simple object hasher:

(function () {
    Number.prototype.toHex = function () {
        var ret = ((this<0?0x8:0)+((this >> 28) & 0x7)).toString(16) + (this & 0xfffffff).toString(16);
        while (ret.length < 8) ret = '0'+ret;
        return ret;
    };
    Object.hashCode = function hashCode(o, l) {
        l = l || 2;
        var i, c, r = [];
        for (i=0; i<l; i++)
            r.push(i*268803292);
        function stringify(o) {
            var i,r;
            if (o === null) return 'n';
            if (o === true) return 't';
            if (o === false) return 'f';
            if (o instanceof Date) return 'd:'+(0+o);
            i=typeof o;
            if (i === 'string') return 's:'+o.replace(/([\\\\;])/g,'\\$1');
            if (i === 'number') return 'n:'+o;
            if (o instanceof Function) return 'm:'+o.toString().replace(/([\\\\;])/g,'\\$1');
            if (o instanceof Array) {
                r=[];
                for (i=0; i<o.length; i++) 
                    r.push(stringify(o[i]));
                return 'a:'+r.join(';');
            }
            r=[];
            for (i in o) {
                r.push(i+':'+stringify(o[i]))
            }
            return 'o:'+r.join(';');
        }
        o = stringify(o);
        for (i=0; i<o.length; i++) {
            for (c=0; c<r.length; c++) {
                r[c] = (r[c] << 13)-(r[c] >> 19);
                r[c] += o.charCodeAt(i) << (r[c] % 24);
                r[c] = r[c] & r[c];
            }
        }
        for (i=0; i<r.length; i++) {
            r[i] = r[i].toHex();
        }
        return r.join('');
    }
}());

The meat here is the stringifier, which simply converts any object into a unique string. hashCode then runs over the object, hashing together the characters of the stringified object.

For extra points, export the stringifier and create a parser.

how to convert string into dictionary in python 3.*?

  1. literal_eval, a somewhat safer version of eval (will only evaluate literals ie strings, lists etc):

    from ast import literal_eval
    
    python_dict = literal_eval("{'a': 1}")
    
  2. json.loads but it would require your string to use double quotes:

    import json
    
    python_dict = json.loads('{"a": 1}')
    

How to write character & in android strings.xml

This is a my issues, my solution is as following: Use &gt; for <, &lt;for > , &amp; for & ,"'" for ' , &quot for \"\"

Center icon in a div - horizontally and vertically

Horizontal centering is as easy as:

text-align: center

Vertical centering when the container is a known height:

height: 100px;
line-height: 100px;
vertical-align: middle

Vertical centering when the container isn't a known height AND you can set the image in the background:

background: url(someimage) no-repeat center center;

How to sort strings in JavaScript

Answer (in Modern ECMAScript)

list.sort((a, b) => (a.attr > b.attr) - (a.attr < b.attr))

Or

list.sort((a, b) => +(a.attr > b.attr) || -(a.attr < b.attr))

Description

Casting a boolean value to a number yields the following:

  • true -> 1
  • false -> 0

Consider three possible patterns:

  • x is larger than y: (x > y) - (y < x) -> 1 - 0 -> 1
  • x is equal to y: (x > y) - (y < x) -> 0 - 0 -> 0
  • x is smaller than y: (x > y) - (y < x) -> 0 - 1 -> -1

(Alternative)

  • x is larger than y: +(x > y) || -(x < y) -> 1 || 0 -> 1
  • x is equal to y: +(x > y) || -(x < y) -> 0 || 0 -> 0
  • x is smaller than y: +(x > y) || -(x < y) -> 0 || -1 -> -1

So these logics are equivalent to typical sort comparator functions.

if (x == y) {
    return 0;
}
return x > y ? 1 : -1;

How to know the version of pip itself

For windows just type:

python -m pip --version