Programs & Examples On #Custom fields

WordPress custom fields: author-entered post metadata

Map a 2D array onto a 1D array

The typical formula for recalculation of 2D array indices into 1D array index is

index = indexX * arrayWidth + indexY;

Alternatively you can use

index = indexY * arrayHeight + indexX;

(assuming that arrayWidth is measured along X axis, and arrayHeight along Y axis)

Of course, one can come up with many different formulae that provide alternative unique mappings, but normally there's no need to.

In C/C++ languages built-in multidimensional arrays are stored in memory so that the last index changes the fastest, meaning that for an array declared as

int xy[10][10];

element xy[5][3] is immediately followed by xy[5][4] in memory. You might want to follow that convention as well, choosing one of the above two formulae depending on which index (X or Y) you consider to be the "last" of the two.

Accessing the web page's HTTP Headers in JavaScript

Using XmlHttpRequest you can pull up the current page and then examine the http headers of the response.

Best case is to just do a HEAD request and then examine the headers.

For some examples of doing this have a look at http://www.jibbering.com/2002/4/httprequest.html

Just my 2 cents.

Replacing last character in a String with java

Try this:

s = s.replaceAll("[,]$", "");

Multiple controllers with AngularJS in single page app

I'm currently in the process of building a single page application. Here is what I have thus far that I believe would be answering your question. I have a base template (base.html) that has a div with the ng-view directive in it. This directive tells angular where to put the new content in. Note that I'm new to angularjs myself so I by no means am saying this is the best way to do it.

app = angular.module('myApp', []);                                                                             

app.config(function($routeProvider, $locationProvider) {                        
  $routeProvider                                                                
       .when('/home/', {                                            
         templateUrl: "templates/home.html",                                               
         controller:'homeController',                                
        })                                                                      
        .when('/about/', {                                       
            templateUrl: "templates/about.html",     
            controller: 'aboutController',  
        }) 
        .otherwise({                      
            template: 'does not exists'   
        });      
});

app.controller('homeController', [              
    '$scope',                              
    function homeController($scope,) {        
        $scope.message = 'HOME PAGE';                  
    }                                                
]);                                                  

app.controller('aboutController', [                  
    '$scope',                               
    function aboutController($scope) {        
        $scope.about = 'WE LOVE CODE';                       
    }                                                
]); 

base.html

<html>
<body>

    <div id="sideMenu">
        <!-- MENU CONTENT -->
    </div>

    <div id="content" ng-view="">
        <!-- Angular view would show here -->
    </div>

<body>
</html>

How to handle screen orientation change when progress dialog and background thread active?

The original perceived problem was that the code would not survive a screen orientation change. Apparently this was "solved" by having the program handle the screen orientation change itself, instead of letting the UI framework do it (via calling onDestroy)).

I would submit that if the underlying problem is that the program will not survive onDestroy(), then the accepted solution is just a workaround that leaves the program with serious other problems and vulnerabilities. Remember that the Android framework specifically states that your activity is at risk for being destroyed almost at any time due to circumstances outside your control. Therefore, your activity must be able to survive onDestroy() and subsequent onCreate() for any reason, not just a screen orientation change.

If you are going to accept handling screen orientation changes yourself to solve the OP's problem, you need to verify that other causes of onDestroy() do not result in the same error. Are you able to do this? If not, I would question whether the "accepted" answer is really a very good one.

DNS caching in linux

Firefox contains a dns cache. To disable the DNS cache:

  1. Open your browser
  2. Type in about:config in the address bar
  3. Right click on the list of Properties and select New > Integer in the Context menu
  4. Enter 'network.dnsCacheExpiration' as the preference name and 0 as the integer value

When disabled, Firefox will use the DNS cache provided by the OS.

jquery data selector

I've created a new data selector that should enable you to do nested querying and AND conditions. Usage:

$('a:data(category==music,artist.name==Madonna)');

The pattern is:

:data( {namespace} [{operator} {check}]  )

"operator" and "check" are optional. So, if you only have :data(a.b.c) it will simply check for the truthiness of a.b.c.

You can see the available operators in the code below. Amongst them is ~= which allows regex testing:

$('a:data(category~=^mus..$,artist.name~=^M.+a$)');

I've tested it with a few variations and it seems to work quite well. I'll probably add this as a Github repo soon (with a full test suite), so keep a look out!

The code:

(function(){

    var matcher = /\s*(?:((?:(?:\\\.|[^.,])+\.?)+)\s*([!~><=]=|[><])\s*("|')?((?:\\\3|.)*?)\3|(.+?))\s*(?:,|$)/g;

    function resolve(element, data) {

        data = data.match(/(?:\\\.|[^.])+(?=\.|$)/g);

        var cur = jQuery.data(element)[data.shift()];

        while (cur && data[0]) {
            cur = cur[data.shift()];
        }

        return cur || undefined;

    }

    jQuery.expr[':'].data = function(el, i, match) {

        matcher.lastIndex = 0;

        var expr = match[3],
            m,
            check, val,
            allMatch = null,
            foundMatch = false;

        while (m = matcher.exec(expr)) {

            check = m[4];
            val = resolve(el, m[1] || m[5]);

            switch (m[2]) {
                case '==': foundMatch = val == check; break;
                case '!=': foundMatch = val != check; break;
                case '<=': foundMatch = val <= check; break;
                case '>=': foundMatch = val >= check; break;
                case '~=': foundMatch = RegExp(check).test(val); break;
                case '>': foundMatch = val > check; break;
                case '<': foundMatch = val < check; break;
                default: if (m[5]) foundMatch = !!val;
            }

            allMatch = allMatch === null ? foundMatch : allMatch && foundMatch;

        }

        return allMatch;

    };

}());

How to tell CRAN to install package dependencies automatically?

Another possibility is to select the Install Dependencies checkbox In the R package installer, on the bottom right:

enter image description here

JavaScript - Getting HTML form values

Expanding on Atrur Klesun's idea... you can just access it by its name if you use getElementById to reach the form. In one line:

document.getElementById('form_id').elements['select_name'].value;

I used it like so for radio buttons and worked fine. I guess it's the same here.

How do I get a YouTube video thumbnail from the YouTube API?

In YouTube API V3 we can also use these URLs for obtaining thumbnails... They are classified based on their quality.

https://i1.ytimg.com/vi/<insert-youtube-video-id-here>/default.jpg -   default
https://i1.ytimg.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg - medium 
https://i1.ytimg.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg - high
https://i1.ytimg.com/vi/<insert-youtube-video-id-here>/sddefault.jpg - standard

And for the maximum resolution..

https://i1.ytimg.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg

One advantage of these URLs over the URLs in the first answer is that these URLs don't get blocked by firewalls.

How to insert text into the textarea at the current cursor position?

 /**
 * Usage "foo baz".insertInside(4, 0, "bar ") ==> "foo bar baz"
 */
String.prototype.insertInside = function(start, delCount, newSubStr) {
    return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};


 $('textarea').bind("keydown keypress", function (event) {
   var val = $(this).val();
   var indexOf = $(this).prop('selectionStart');
   if(event.which === 13) {
       val = val.insertInside(indexOf, 0,  "<br>\n");
       $(this).val(val);
       $(this).focus();
    }
})

Flask Python Buttons

I handle it in the following way:

<html>
    <body>

        <form method="post" action="/">

                <input type="submit" value="Encrypt" name="Encrypt"/>
                <input type="submit" value="Decrypt" name="Decrypt" />

        </form>
    </body>
</html>
    

Python Code :

    from flask import Flask, render_template, request
    
    
    app = Flask(__name__)
    
    
    @app.route("/", methods=['GET', 'POST'])
    def index():
        print(request.method)
        if request.method == 'POST':
            if request.form.get('Encrypt') == 'Encrypt':
                # pass
                print("Encrypted")
            elif  request.form.get('Decrypt') == 'Decrypt':
                # pass # do something else
                print("Decrypted")
            else:
                # pass # unknown
                return render_template("index.html")
        elif request.method == 'GET':
            # return render_template("index.html")
            print("No Post Back Call")
        return render_template("index.html")
    
    
    if __name__ == '__main__':
        app.run()

How do I set log4j level on the command line?

Based on Thorbjørn Ravn Andersens suggestion I wrote some code that makes this work

Add the following early in the main method and it is now possible to set the log level from the comand line. This have been tested in a project of mine but I'm new to log4j and might have made some mistake. If so please correct me.

    Logger.getRootLogger().setLevel(Level.WARN);
    HashMap<String,Level> logLevels=new HashMap<String,Level>();
    logLevels.put("ALL",Level.ALL);
    logLevels.put("TRACE",Level.TRACE);
    logLevels.put("DEBUG",Level.DEBUG);
    logLevels.put("INFO",Level.INFO);
    logLevels.put("WARN",Level.WARN);
    logLevels.put("ERROR",Level.ERROR);
    logLevels.put("FATAL",Level.FATAL);
    logLevels.put("OFF",Level.OFF);
    for(String name:System.getProperties().stringPropertyNames()){
        String logger="log4j.logger.";
        if(name.startsWith(logger)){
            String loggerName=name.substring(logger.length());
            String loggerValue=System.getProperty(name);
            if(logLevels.containsKey(loggerValue))
                Logger.getLogger(loggerName).setLevel(logLevels.get(loggerValue));
            else
                Logger.getRootLogger().warn("unknown log4j logg level on comand line: "+loggerValue);
        }
    }

what is the use of "response.setContentType("text/html")" in servlet

Content types are included in HTTP responses because the same, byte for byte sequence of values in the content could be interpreted in more than one way.(*)

Remember that http can transport more than just HTML (js, css and images are obvious examples), and in some cases, the receiver will not know what type of object it's going to receive.


(*) the obvious one here is XHTML - which is XML. If it's served with a content type of application/xml, the receiver ought to just treat it as XML. If it's served up as application/xhtml+xml, then it ought to be treated as XHTML.

Can you recommend a free light-weight MySQL GUI for Linux?

i suggest using phpmyadmin

it’s definitely the best free tool out there and it works on every system with php+mysql

Python: Find index of minimum item in list of floats

You're effectively scanning the list once to find the min value, then scanning it again to find the index, you can do both in one go:

from operator import itemgetter
min(enumerate(a), key=itemgetter(1))[0] 

Select Tag Helper in ASP.NET Core MVC

I created an Interface and a <options> tag helper for this. So I didn't have to convert the IEnumerable<T> items into IEnumerable<SelectListItem> every time I have to populate the <select> control.

And I think it works beautifully...

The usage is something like:

<select asp-for="EmployeeId">
    <option value="">Please select...</option>
    <options asp-items="@Model.EmployeesList" />
</select>

And to make it work with the tag helper you have to implement that interface in your class:

public class Employee : IIntegerListItem
{
   public int Id { get; set; }
   public string FullName { get; set; }

   public int Value { return Id; }
   public string Text{ return FullName ; }
}

These are the needed codes:

The interface:

public interface IIntegerListItem
{
    int Value { get; }
    string Text { get; }
}

The <options> tag helper:

[HtmlTargetElement("options", Attributes = "asp-items")]
public class OptionsTagHelper : TagHelper
{
    public OptionsTagHelper(IHtmlGenerator generator)
    {
        Generator = generator;
    }

    [HtmlAttributeNotBound]
    public IHtmlGenerator Generator { get; set; }

    [HtmlAttributeName("asp-items")]
    public object Items { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.SuppressOutput();
        // Is this <options /> element a child of a <select/> element the SelectTagHelper targeted?
        object formDataEntry;
        context.Items.TryGetValue(typeof(SelectTagHelper), out formDataEntry);

        var selectedValues = formDataEntry as ICollection<string>;
        var encodedValues = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
        if (selectedValues != null && selectedValues.Count != 0)
        {
            foreach (var selectedValue in selectedValues)
            {
                encodedValues.Add(Generator.Encode(selectedValue));
            }
        }

        IEnumerable<SelectListItem> items = null;
        if (Items != null)
        {
            if (Items is IEnumerable)
            {
                var enumerable = Items as IEnumerable;
                if (Items is IEnumerable<SelectListItem>)
                    items = Items as IEnumerable<SelectListItem>;
                else if (Items is IEnumerable<IIntegerListItem>)
                    items = ((IEnumerable<IIntegerListItem>)Items).Select(x => new SelectListItem() { Selected = false, Value = ((IIntegerListItem)x).Value.ToString(), Text = ((IIntegerListItem)x).Text });
                else
                    throw new InvalidOperationException(string.Format("The {2} was unable to provide metadata about '{1}' expression value '{3}' for <options>.",
                        "<options>",
                        "ForAttributeName",
                        nameof(IModelMetadataProvider),
                        "For.Name"));
            }
            else
            {
                throw new InvalidOperationException("Invalid items for <options>");
            }

            foreach (var item in items)
            {
                bool selected = (selectedValues != null && selectedValues.Contains(item.Value)) || encodedValues.Contains(item.Value);
                var selectedAttr = selected ? "selected='selected'" : "";

                if (item.Value != null)
                    output.Content.AppendHtml($"<option value='{item.Value}' {selectedAttr}>{item.Text}</option>");
                else
                    output.Content.AppendHtml($"<option>{item.Text}</option>");
            }
        }
    }
}

There may be some typo but the aim is clear I think. I had to edit a little bit.

Unfamiliar symbol in algorithm: what does ? mean?

Can be read, "For all s such that s does not equal s[start]"

Annotation-specified bean name conflicts with existing, non-compatible bean def

If none of the other answers fix your problem and it started occurring after change any configuration direct or indirectly (via git pull / merge / rebase) and your project is a Maven project:

mvn clean

Hope this fixes your problem. Or someones

QtCreator: No valid kits found

In my case, it goes well after I installed CMake in my system:)

sudo pacman -S cmake

for manjaro operating system.

MySQL OPTIMIZE all tables?

Following example php script can help you to optimize all tables in your database

<?php

dbConnect();

$alltables = mysql_query("SHOW TABLES");

while ($table = mysql_fetch_assoc($alltables))
{
   foreach ($table as $db => $tablename)
   {
       mysql_query("OPTIMIZE TABLE '".$tablename."'")
       or die(mysql_error());

   }
}

?>

Delete specific line number(s) from a text file using sed?

You can delete a particular single line with its line number by

sed -i '33d' file

This will delete the line on 33 line number and save the updated file.

How to put the legend out of the plot

Just call legend() call after the plot() call like this:

# matplotlib
plt.plot(...)
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))

# Pandas
df.myCol.plot().legend(loc='center left', bbox_to_anchor=(1, 0.5))

Results would look something like this:

enter image description here

What does an exclamation mark mean in the Swift language?

IN SIMPLE WORDS

USING Exclamation mark indicates that variable must consists non nil value (it never be nil)

How to get the max of two values in MySQL?

You can use GREATEST function with not nullable fields. If one of this values (or both) can be NULL, don't use it (result can be NULL).

select 
    if(
        fieldA is NULL, 
        if(fieldB is NULL, NULL, fieldB), /* second NULL is default value */
        if(fieldB is NULL, field A, GREATEST(fieldA, fieldB))
    ) as maxValue

You can change NULL to your preferred default value (if both values is NULL).

Expression must have class type

It's a pointer, so instead try:

a->f();

Basically the operator . (used to access an object's fields and methods) is used on objects and references, so:

A a;
a.f();
A& ref = a;
ref.f();

If you have a pointer type, you have to dereference it first to obtain a reference:

A* ptr = new A();
(*ptr).f();
ptr->f();

The a->b notation is usually just a shorthand for (*a).b.

A note on smart pointers

The operator-> can be overloaded, which is notably used by smart pointers. When you're using smart pointers, then you also use -> to refer to the pointed object:

auto ptr = make_unique<A>();
ptr->f();

Delete all documents from index/type without deleting type

Elasticsearch 2.3 the option

    action.destructive_requires_name: true

in elasticsearch.yml do the trip

    curl -XDELETE http://localhost:9200/twitter/tweet

How to style the <option> with only CSS?

I've played around with select items before and without overriding the functionality with JavaScript, I don't think it's possible in Chrome. Whether you use a plugin or write your own code, CSS only is a no go for Chrome/Safari and as you said, Firefox is better at dealing with it.

JavaScript/jQuery: replace part of string?

It should be like this

$(this).text($(this).text().replace('N/A, ', ''))

Convert int to ASCII and back in Python

>>> ord("a")
97
>>> chr(97)
'a'

How do I display an alert dialog on Android?

Kotlin Custom dialog: In Case if you want to create custom dialog

Dialog(activity!!, R.style.LoadingIndicatorDialogStyle)
        .apply {
            // requestWindowFeature(Window.FEATURE_NO_TITLE)
            setCancelable(true)
            setContentView(R.layout.define_your_custom_view_id_here)

            //access your custom view buttons/editText like below.z
            val createBt = findViewById<TextView>(R.id.clipboard_create_project)
            val cancelBt = findViewById<TextView>(R.id.clipboard_cancel_project)
            val clipboard_et = findViewById<TextView>(R.id.clipboard_et)
            val manualOption =
                findViewById<TextView>(R.id.clipboard_manual_add_project_option)

            //if you want to perform any operation on the button do like this

            createBt.setOnClickListener {
                //handle your button click here
                val enteredData = clipboard_et.text.toString()
                if (enteredData.isEmpty()) {
                    Utils.toast("Enter project details")
                } else {
                    navigateToAddProject(enteredData, true)
                    dismiss()
                }
            }

            cancelBt.setOnClickListener {
                dismiss()
            }
            manualOption.setOnClickListener {
                navigateToAddProject("", false)
                dismiss()
            }
            show()
        }

Create LoadingIndicatorDialogStyle in style.xml

<style name="LoadingIndicatorDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:statusBarColor">@color/black_transperant</item>
<item name="android:layout_gravity">center</item>
<item name="android:background">@android:color/transparent</item>
<!--<item name="android:windowAnimationStyle">@style/MaterialDialogSheetAnimation</item>-->

START_STICKY and START_NOT_STICKY

  • START_STICKY: It will restart the service in case if it terminated and the Intent data which is passed to the onStartCommand() method is NULL. This is suitable for the service which are not executing commands but running independently and waiting for the job.
  • START_NOT_STICKY: It will not restart the service and it is useful for the services which will run periodically. The service will restart only when there are a pending startService() calls. It’s the best option to avoid running a service in case if it is not necessary.
  • START_REDELIVER_INTENT: It’s same as STAR_STICKY and it recreates the service, call onStartCommand() with last intent that was delivered to the service.

python capitalize first letter only

This is similar to @Anon's answer in that it keeps the rest of the string's case intact, without the need for the re module.

def sliceindex(x):
    i = 0
    for c in x:
        if c.isalpha():
            i = i + 1
            return i
        i = i + 1

def upperfirst(x):
    i = sliceindex(x)
    return x[:i].upper() + x[i:]

x = '0thisIsCamelCase'

y = upperfirst(x)

print(y)
# 0ThisIsCamelCase

As @Xan pointed out, the function could use more error checking (such as checking that x is a sequence - however I'm omitting edge cases to illustrate the technique)

Updated per @normanius comment (thanks!)

Thanks to @GeoStoneMarten in pointing out I didn't answer the question! -fixed that

Difference between IISRESET and IIS Stop-Start command

The following was tested for IIS 8.5 and Windows 8.1.

As of IIS 7, Windows recommends restarting IIS via net stop/start. Via the command prompt (as Administrator):

> net stop WAS
> net start W3SVC

net stop WAS will stop W3SVC as well. Then when starting, net start W3SVC will start WAS as a dependency.

Round up to Second Decimal Place in Python

from math import ceil

num = 0.1111111111000
num = ceil(num * 100) / 100.0

See:
math.ceil documentation
round documentation - You'll probably want to check this out anyway for future reference

How do I diff the same file between two different commits on the same branch?

Here is a Perl script that prints out Git diff commands for a given file as found in a Git log command.

E.g.

git log pom.xml | perl gldiff.pl 3 pom.xml

Yields:

git diff 5cc287:pom.xml e8e420:pom.xml
git diff 3aa914:pom.xml 7476e1:pom.xml
git diff 422bfd:pom.xml f92ad8:pom.xml

which could then be cut and pasted in a shell window session or piped to /bin/sh.

Notes:

  1. the number (3 in this case) specifies how many lines to print
  2. the file (pom.xml in this case) must agree in both places (you could wrap it in a shell function to provide the same file in both places) or put it in a binary directory as a shell script

Code:

# gldiff.pl
use strict;

my $max  = shift;
my $file = shift;

die "not a number" unless $max =~ m/\d+/;
die "not a file"   unless -f $file;

my $count;
my @lines;

while (<>) {
    chomp;
    next unless s/^commit\s+(.*)//;
    my $commit = $1;
    push @lines, sprintf "%s:%s", substr($commit,0,6),$file;
    if (@lines == 2) {
        printf "git diff %s %s\n", @lines;
        @lines = ();
    }
    last if ++$count >= $max *2;
}

Python name 'os' is not defined

The problem is that you forgot to import os. Add this line of code:

import os

And everything should be fine. Hope this helps!

Add a space (" ") after an element using :after

element::after { 
    display: block;
    content: " ";
}

This worked for me.

What is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!

If you're teaching engineers, this bit of Prolog might get their attention:

d(x,x,1).
d(C,x,0):-number(C).
d(C*x,x,C):-number(C).
d(-U, X, -DU) :- d(U, X, DU).
d( U + V, x, RU + RV ):-d(U,x,RU), d(V,x,RV).
d( U - V, x, RU - RV ):-d(U,x,RU), d(V,x,RV).
d(U * V,x, U * DV + V * DU):- d(U,x,DU), d(V,x,DV).
d(U^N, x, N*U^(N-1)*DU) :- integer(N), d(U, x, DU).

Just write down the rules, and you have a program that can do all of first semester calculus, in 8 lines of code.

How to determine if a list of polygon points are in clockwise order?

Another solution for this;

const isClockwise = (vertices=[]) => {
    const len = vertices.length;
    const sum = vertices.map(({x, y}, index) => {
        let nextIndex = index + 1;
        if (nextIndex === len) nextIndex = 0;

        return {
            x1: x,
            x2: vertices[nextIndex].x,
            y1: x,
            y2: vertices[nextIndex].x
        }
    }).map(({ x1, x2, y1, y2}) => ((x2 - x1) * (y1 + y2))).reduce((a, b) => a + b);

    if (sum > -1) return true;
    if (sum < 0) return false;
}

Take all the vertices as an array like this;

const vertices = [{x: 5, y: 0}, {x: 6, y: 4}, {x: 4, y: 5}, {x: 1, y: 5}, {x: 1, y: 0}];
isClockwise(vertices);

Fast way of finding lines in one file that are not in another?

The comm command (short for "common") may be useful comm - compare two sorted files line by line

#find lines only in file1
comm -23 file1 file2 

#find lines only in file2
comm -13 file1 file2 

#find lines common to both files
comm -12 file1 file2 

The man file is actually quite readable for this.

excel - if cell is not blank, then do IF statement

You need to use AND statement in your formula

=IF(AND(IF(NOT(ISBLANK(Q2));TRUE;FALSE);Q2<=R2);"1";"0")

And if both conditions are met, return 1.

You could also add more conditions in your AND statement.

JavaScript unit test tools for TDD

The JavaScript section of the Wikipedia entry, List of Unit Testing Frameworks, provides a list of available choices. It indicates whether they work client-side, server-side, or both.

In Python, what does dict.pop(a,b) mean?

So many questions here. I see at least two, maybe three:

  • What does pop(a,b) do?/Why are there a second argument?
  • What is *args being used for?

The first question is trivially answered in the Python Standard Library reference:

pop(key[, default])

If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.


The second question is covered in the Python Language Reference:

If the form “*identifier” is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form “**identifier” is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary.

In other words, the pop function takes at least two arguments. The first two get assigned the names self and key; and the rest are stuffed into a tuple called args.

What's happening on the next line when *args is passed along in the call to self.data.pop is the inverse of this - the tuple *args is expanded to of positional parameters which get passed along. This is explained in the Python Language Reference:

If the syntax *expression appears in the function call, expression must evaluate to a sequence. Elements from this sequence are treated as if they were additional positional arguments

In short, a.pop() wants to be flexible and accept any number of positional parameters, so that it can pass this unknown number of positional parameters on to self.data.pop().

This gives you flexibility; data happens to be a dict right now, and so self.data.pop() takes either one or two parameters; but if you changed data to be a type which took 19 parameters for a call to self.data.pop() you wouldn't have to change class a at all. You'd still have to change any code that called a.pop() to pass the required 19 parameters though.

Java file path in Linux

I think Todd is correct, but I think there's one other thing you should consider. You can reliably get the home directory from the JVM at runtime, and then you can create files objects relative to that location. It's not that much more trouble, and it's something you'll appreciate if you ever move to another computer or operating system.

File homedir = new File(System.getProperty("user.home"));
File fileToRead = new File(homedir, "java/ex.txt");

Convert any object to a byte[]

Use the BinaryFormatter:

byte[] ObjectToByteArray(object obj)
{
    if(obj == null)
        return null;
    BinaryFormatter bf = new BinaryFormatter();
    using (MemoryStream ms = new MemoryStream())
    {
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }
}

Note that obj and any properties/fields within obj (and so-on for all of their properties/fields) will all need to be tagged with the Serializable attribute to successfully be serialized with this.

PHP Function Comments

Functions:

/**
 * Does something interesting
 *
 * @param Place   $where  Where something interesting takes place
 * @param integer $repeat How many times something interesting should happen
 * 
 * @throws Some_Exception_Class If something interesting cannot happen
 * @author Monkey Coder <[email protected]>
 * @return Status
 */ 

Classes:

/**
 * Short description for class
 *
 * Long description for class (if any)...
 *
 * @copyright  2006 Zend Technologies
 * @license    http://www.zend.com/license/3_0.txt   PHP License 3.0
 * @version    Release: @package_version@
 * @link       http://dev.zend.com/package/PackageName
 * @since      Class available since Release 1.2.0
 */ 

Sample File:

<?php

/**
 * Short description for file
 *
 * Long description for file (if any)...
 *
 * PHP version 5.6
 *
 * LICENSE: This source file is subject to version 3.01 of the PHP license
 * that is available through the world-wide-web at the following URI:
 * http://www.php.net/license/3_01.txt.  If you did not receive a copy of
 * the PHP License and are unable to obtain it through the web, please
 * send a note to [email protected] so we can mail you a copy immediately.
 *
 * @category   CategoryName
 * @package    PackageName
 * @author     Original Author <[email protected]>
 * @author     Another Author <[email protected]>
 * @copyright  1997-2005 The PHP Group
 * @license    http://www.php.net/license/3_01.txt  PHP License 3.01
 * @version    SVN: $Id$
 * @link       http://pear.php.net/package/PackageName
 * @see        NetOther, Net_Sample::Net_Sample()
 * @since      File available since Release 1.2.0
 * @deprecated File deprecated in Release 2.0.0
 */

/**
 * This is a "Docblock Comment," also known as a "docblock."  The class'
 * docblock, below, contains a complete description of how to write these.
 */
require_once 'PEAR.php';

// {{{ constants

/**
 * Methods return this if they succeed
 */
define('NET_SAMPLE_OK', 1);

// }}}
// {{{ GLOBALS

/**
 * The number of objects created
 * @global int $GLOBALS['_NET_SAMPLE_Count']
 */
$GLOBALS['_NET_SAMPLE_Count'] = 0;

// }}}
// {{{ Net_Sample

/**
 * An example of how to write code to PEAR's standards
 *
 * Docblock comments start with "/**" at the top.  Notice how the "/"
 * lines up with the normal indenting and the asterisks on subsequent rows
 * are in line with the first asterisk.  The last line of comment text
 * should be immediately followed on the next line by the closing asterisk
 * and slash and then the item you are commenting on should be on the next
 * line below that.  Don't add extra lines.  Please put a blank line
 * between paragraphs as well as between the end of the description and
 * the start of the @tags.  Wrap comments before 80 columns in order to
 * ease readability for a wide variety of users.
 *
 * Docblocks can only be used for programming constructs which allow them
 * (classes, properties, methods, defines, includes, globals).  See the
 * phpDocumentor documentation for more information.
 * http://phpdoc.org/tutorial_phpDocumentor.howto.pkg.html
 *
 * The Javadoc Style Guide is an excellent resource for figuring out
 * how to say what needs to be said in docblock comments.  Much of what is
 * written here is a summary of what is found there, though there are some
 * cases where what's said here overrides what is said there.
 * http://java.sun.com/j2se/javadoc/writingdoccomments/index.html#styleguide
 *
 * The first line of any docblock is the summary.  Make them one short
 * sentence, without a period at the end.  Summaries for classes, properties
 * and constants should omit the subject and simply state the object,
 * because they are describing things rather than actions or behaviors.
 *
 * Below are the tags commonly used for classes. @category through @version
 * are required.  The remainder should only be used when necessary.
 * Please use them in the order they appear here.  phpDocumentor has
 * several other tags available, feel free to use them.
 *
 * @category   CategoryName
 * @package    PackageName
 * @author     Original Author <[email protected]>
 * @author     Another Author <[email protected]>
 * @copyright  1997-2005 The PHP Group
 * @license    http://www.php.net/license/3_01.txt  PHP License 3.01
 * @version    Release: @package_version@
 * @link       http://pear.php.net/package/PackageName
 * @see        NetOther, Net_Sample::Net_Sample()
 * @since      Class available since Release 1.2.0
 * @deprecated Class deprecated in Release 2.0.0
 */
class Net_Sample
{
    // {{{ properties

    /**
     * The status of foo's universe
     * Potential values are 'good', 'fair', 'poor' and 'unknown'.
     * @var string $foo
     */
    public $foo = 'unknown';

    /**
     * The status of life
     * Note that names of private properties or methods must be
     * preceeded by an underscore.
     * @var bool $_good
     */
    private $_good = true;

    // }}}
    // {{{ setFoo()

    /**
     * Registers the status of foo's universe
     *
     * Summaries for methods should use 3rd person declarative rather
     * than 2nd person imperative, beginning with a verb phrase.
     *
     * Summaries should add description beyond the method's name. The
     * best method names are "self-documenting", meaning they tell you
     * basically what the method does.  If the summary merely repeats
     * the method name in sentence form, it is not providing more
     * information.
     *
     * Summary Examples:
     *   + Sets the label              (preferred)
     *   + Set the label               (avoid)
     *   + This method sets the label  (avoid)
     *
     * Below are the tags commonly used for methods.  A @param tag is
     * required for each parameter the method has.  The @return
     * and @access tags are mandatory.  The @throws tag is required if
     * the method uses exceptions.  @static is required if the method can
     * be called statically.  The remainder should only be used when
     * necessary.  Please use them in the order they appear here.
     * phpDocumentor has several other tags available, feel free to use
     * them.
     *
     * The @param tag contains the data type, then the parameter's
     * name, followed by a description.  By convention, the first noun in
     * the description is the data type of the parameter.  Articles like
     * "a", "an", and  "the" can precede the noun.  The descriptions
     * should start with a phrase.  If further description is necessary,
     * follow with sentences.  Having two spaces between the name and the
     * description aids readability.
     *
     * When writing a phrase, do not capitalize and do not end with a
     * period:
     *   + the string to be tested
     *
     * When writing a phrase followed by a sentence, do not capitalize the
     * phrase, but end it with a period to distinguish it from the start
     * of the next sentence:
     *   + the string to be tested. Must use UTF-8 encoding.
     *
     * Return tags should contain the data type then a description of
     * the data returned.  The data type can be any of PHP's data types
     * (int, float, bool, string, array, object, resource, mixed)
     * and should contain the type primarily returned.  For example, if
     * a method returns an object when things work correctly but false
     * when an error happens, say 'object' rather than 'mixed.'  Use
     * 'void' if nothing is returned.
     *
     * Here's an example of how to format examples:
     * <code>
     * require_once 'Net/Sample.php';
     *
     * $s = new Net_Sample();
     * if (PEAR::isError($s)) {
     *     echo $s->getMessage() . "\n";
     * }
     * </code>
     *
     * Here is an example for non-php example or sample:
     * <samp>
     * pear install net_sample
     * </samp>
     *
     * @param string $arg1 the string to quote
     * @param int    $arg2 an integer of how many problems happened.
     *                     Indent to the description's starting point
     *                     for long ones.
     *
     * @return int the integer of the set mode used. FALSE if foo
     *             foo could not be set.
     * @throws exceptionclass [description]
     *
     * @access public
     * @static
     * @see Net_Sample::$foo, Net_Other::someMethod()
     * @since Method available since Release 1.2.0
     * @deprecated Method deprecated in Release 2.0.0
     */
    function setFoo($arg1, $arg2 = 0)
    {
        /*
         * This is a "Block Comment."  The format is the same as
         * Docblock Comments except there is only one asterisk at the
         * top.  phpDocumentor doesn't parse these.
         */
        if ($arg1 == 'good' || $arg1 == 'fair') {
            $this->foo = $arg1;
            return 1;
        } elseif ($arg1 == 'poor' && $arg2 > 1) {
            $this->foo = 'poor';
            return 2;
        } else {
            return false;
        }
    }

    // }}}
}

// }}}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * c-hanging-comment-ender-p: nil
 * End:
 */

?>

Source: PEAR Docblock Comment standards

How to check the maximum number of allowed connections to an Oracle database?

Note: this only answers part of the question.

If you just want to know the maximum number of sessions allowed, then you can execute in sqlplus, as sysdba:

SQL> show parameter sessions

This gives you an output like:

    NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
java_max_sessionspace_size           integer     0
java_soft_sessionspace_limit         integer     0
license_max_sessions                 integer     0
license_sessions_warning             integer     0
sessions                             integer     248
shared_server_sessions               integer

The sessions parameter is the one what you want.

How to disable a particular checkstyle rule for a particular line of code?

Check out the use of the supressionCommentFilter at http://checkstyle.sourceforge.net/config_filters.html#SuppressionCommentFilter. You'll need to add the module to your checkstyle.xml

<module name="SuppressionCommentFilter"/>

and it's configurable. Thus you can add comments to your code to turn off checkstyle (at various levels) and then back on again through the use of comments in your code. E.g.

//CHECKSTYLE:OFF
public void someMethod(String arg1, String arg2, String arg3, String arg4) {
//CHECKSTYLE:ON

Or even better, use this more tweaked version:

<module name="SuppressionCommentFilter">
    <property name="offCommentFormat" value="CHECKSTYLE.OFF\: ([\w\|]+)"/>
    <property name="onCommentFormat" value="CHECKSTYLE.ON\: ([\w\|]+)"/>
    <property name="checkFormat" value="$1"/>
</module>

which allows you to turn off specific checks for specific lines of code:

//CHECKSTYLE.OFF: IllegalCatch - Much more readable than catching 7 exceptions
catch (Exception e)
//CHECKSTYLE.ON: IllegalCatch

*Note: you'll also have to add the FileContentsHolder:

<module name="FileContentsHolder"/>

See also

<module name="SuppressionFilter">
    <property name="file" value="docs/suppressions.xml"/>
</module>

under the SuppressionFilter section on that same page, which allows you to turn off individual checks for pattern matched resources.

So, if you have in your checkstyle.xml:

<module name="ParameterNumber">
   <property name="id" value="maxParameterNumber"/>
   <property name="max" value="3"/>
   <property name="tokens" value="METHOD_DEF"/>
</module>

You can turn it off in your suppression xml file with:

<suppress id="maxParameterNumber" files="YourCode.java"/>

Another method, now available in Checkstyle 5.7 is to suppress violations via the @SuppressWarnings java annotation. To do this, you will need to add two new modules (SuppressWarningsFilter and SuppressWarningsHolder) in your configuration file:

<module name="Checker">
   ...
   <module name="SuppressWarningsFilter" />
   <module name="TreeWalker">
       ...
       <module name="SuppressWarningsHolder" />
   </module>
</module> 

Then, within your code you can do the following:

@SuppressWarnings("checkstyle:methodlength")
public void someLongMethod() throws Exception {

or, for multiple suppressions:

@SuppressWarnings({"checkstyle:executablestatementcount", "checkstyle:methodlength"})
public void someLongMethod() throws Exception {

NB: The "checkstyle:" prefix is optional (but recommended). According to the docs the parameter name have to be in all lowercase, but practice indicates any case works.

Run batch file as a Windows service

As Doug Currie says use RunAsService.

From my past experience you must remember that the Service you generate will

  • have a completely different set of environment variables
  • have to be carefully inspected for rights/permissions issues
  • might cause havoc if it opens dialogs asking for any kind of input

not sure if the last one still applies ... it was one big night mare in a project I worked on some time ago.

Put a Delay in Javascript

This thread has a good discussion and a useful solution:

function pause( iMilliseconds )
{
    var sDialogScript = 'window.setTimeout( function () { window.close(); }, ' + iMilliseconds + ');';
    window.showModalDialog('javascript:document.writeln ("<script>' + sDialogScript + '<' + '/script>")');
}

Unfortunately it appears that this doesn't work in some versions of IE, but the thread has many other worthy proposals if that proves to be a problem for you.

Link and execute external JavaScript file hosted on GitHub

My use case was to load 'bookmarklets' direclty from my Bitbucket account which has same restrictions as Github. The work around I came up with was to AJAX for the script and run eval on the response string, below snippet is based on that approach.

<script>
    var sScriptURL ='<script-URL-here>'; 
    var oReq = new XMLHttpRequest(); 
    oReq.addEventListener("load", 
       function fLoad() {eval(this.responseText + '\r\n//# sourceURL=' + sScriptURL)}); 
    oReq.open("GET", sScriptURL); oReq.send(); false;
</script>

Note that appending of sourceURL comment is to allow for debuging of the script within browser's developer tools.

Rest-assured. Is it possible to extract value from request json?

There are several ways. I personally use the following ones:

extracting single value:

String user_Id =
given().
when().
then().
extract().
        path("user_id");

work with the entire response when you need more than one:

Response response =
given().
when().
then().
extract().
        response();

String userId = response.path("user_id");

extract one using the JsonPath to get the right type:

long userId =
given().
when().
then().
extract().
        jsonPath().getLong("user_id");

Last one is really useful when you want to match against the value and the type i.e.

assertThat(
    when().
    then().
    extract().
            jsonPath().getLong("user_id"), equalTo(USER_ID)
);

The rest-assured documentation is quite descriptive and full. There are many ways to achieve what you are asking: https://github.com/jayway/rest-assured/wiki/Usage

Strtotime() doesn't work with dd/mm/YYYY format

This is a good solution to many problems:

function datetotime ($date, $format = 'YYYY-MM-DD') {

    if ($format == 'YYYY-MM-DD') list($year, $month, $day) = explode('-', $date);
    if ($format == 'YYYY/MM/DD') list($year, $month, $day) = explode('/', $date);
    if ($format == 'YYYY.MM.DD') list($year, $month, $day) = explode('.', $date);

    if ($format == 'DD-MM-YYYY') list($day, $month, $year) = explode('-', $date);
    if ($format == 'DD/MM/YYYY') list($day, $month, $year) = explode('/', $date);
    if ($format == 'DD.MM.YYYY') list($day, $month, $year) = explode('.', $date);

    if ($format == 'MM-DD-YYYY') list($month, $day, $year) = explode('-', $date);
    if ($format == 'MM/DD/YYYY') list($month, $day, $year) = explode('/', $date);
    if ($format == 'MM.DD.YYYY') list($month, $day, $year) = explode('.', $date);

    return mktime(0, 0, 0, $month, $day, $year);

}

omp parallel vs. omp parallel for

I don't think there is any difference, one is a shortcut for the other. Although your exact implementation might deal with them differently.

The combined parallel worksharing constructs are a shortcut for specifying a parallel construct containing one worksharing construct and no other statements. Permitted clauses are the union of the clauses allowed for the parallel and worksharing contructs.

Taken from http://www.openmp.org/mp-documents/OpenMP3.0-SummarySpec.pdf

The specs for OpenMP are here:

https://openmp.org/specifications/

How to replace all special character into a string using C#

Also, It can be done with LINQ

var str = "Hello@Hello&Hello(Hello)";
var characters = str.Select(c => char.IsLetter(c) ? c : ',')).ToArray();             
var output = new string(characters);
Console.WriteLine(output);

Is there a jQuery unfocus method?

So you can do this

$('#textarea').attr('enable',false)

try it and give feedback

Can media queries resize based on a div element instead of the screen?

You can use the ResizeObserver API. It's still in it's early days so it's not supported by all browsers yet (but there several polyfills that can help you with that).

Basically this API allow you to attach an event listener to the resize of a DOM element.

Demo 1 - Demo 2

SQL Server date format yyyymmdd

try this....

SELECT FORMAT(CAST(DOB AS DATE),'yyyyMMdd') FROM Employees;

Docker error cannot delete docker container, conflict: unable to remove repository reference

If you want to cleanup docker images and containers

CAUTION: this will flush everything

stop all containers

docker stop $(docker ps -a -q)

remove all containers

docker rm $(docker ps -a -q)

remove all images

docker rmi -f $(docker images -a -q)

Redirect on select option in select box

For someone who doesn't want to use inline JS.

<select data-select-name>
    <option value="">Select...</option>
    <option value="http://google.com">Google</option>
    <option value="http://yahoo.com">Yahoo</option>
</select>
<script type="text/javascript">
    document.addEventListener('DOMContentLoaded',function() {
        document.querySelector('select[data-select-name]').onchange=changeEventHandler;
    },false);

    function changeEventHandler(event) {
        window.location.href = this.options[this.selectedIndex].value;
    }
</script>

SpringApplication.run main method

One more way is to extend the application (as my application was to inherit and customize the parent). It invokes the parent and its commandlinerunner automatically.

@SpringBootApplication
public class ChildApplication extends ParentApplication{
    public static void main(String[] args) {
        SpringApplication.run(ChildApplication.class, args);
    }
}

Change the project theme in Android Studio?

In the AndroidManifest.xml, under the application tag, you can set the theme of your choice. To customize the theme, press Ctrl + Click on android:theme = "@style/AppTheme" in the Android manifest file. It will open styles.xml file where you can change the parent attribute of the style tag.

At parent= in styles.xml you can browse all available styles by using auto-complete inside the "". E.g. try parent="Theme." with your cursor right after the . and then pressing Ctrl + Space.

You can also preview themes in the preview window in Android Studio.

enter image description here

Checking for empty queryset in Django

Since version 1.2, Django has QuerySet.exists() method which is the most efficient:

if orgs.exists():
    # Do this...
else:
    # Do that...

But if you are going to evaluate QuerySet anyway it's better to use:

if orgs:
   ...

For more information read QuerySet.exists() documentation.

index.php not loading by default

While adding 'DirectoryIndex index.php' to a .htaccess file may work,

NOTE:

In general, you should never use .htaccess files

This is quoted from http://httpd.apache.org/docs/1.3/howto/htaccess.html
Although this refers to an older version of apache, I believe the principle still applies.

Adding the following to your httpd.conf (if you have access to it) is considered better form, causes less server overhead and has the exact same effect:

<Directory /myapp>
DirectoryIndex index.php
</Directory>

PreparedStatement with list of parameters in a IN clause

public class Test1 {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("helow");
String where="where task in ";
        where+="(";
    //  where+="'task1'";
        int num[]={1,2,3,4};
        for (int i=0;i<num.length+1;i++) {
            if(i==1){
                where +="'"+i+"'";
            }
            if(i>1 && i<num.length)
                where+=", '"+i+"'";
            if(i==num.length){
                System.out.println("This is last number"+i);
            where+=", '"+i+"')";
            }
        }
        System.out.println(where);  
    }
}

Error "There is already an open DataReader associated with this Command which must be closed first" when using 2 distinct commands

I suggest creating an additional connection for the second command, would solve it. Try to combine both queries in one query. Create a subquery for the count.

while (dr3.Read())
{
    dados_historico[4] = dr3["QT"].ToString(); //quantidade de emails lidos naquela verificação
}

Why override the same value again and again?

if (dr3.Read())
{
    dados_historico[4] = dr3["QT"].ToString(); //quantidade de emails lidos naquela verificação
}

Would be enough.

read word by word from file in C++

First of all, don't loop while (!eof()), it will not work as you expect it to because the eofbit will not be set until after a failed read due to end of file.

Secondly, the normal input operator >> separates on whitespace and so can be used to read "words":

std::string word;
while (file >> word)
{
    ...
}

How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?

I'd had this issue with Eclipse 2019-12 where the includes were previously being resolved, but then weren't. This was with a Meson build C/C++ project. I'm not sure exactly what happened, but closing the project and reopening it resolved the issue for me.

Is there a way to list open transactions on SQL Server 2000 database?

For all databases query sys.sysprocesses

SELECT * FROM sys.sysprocesses WHERE open_tran = 1

For the current database use:

DBCC OPENTRAN

How to use http.client in Node.js if there is basic authorization

This code works in my case, after a lot of research. You will require to install the request npm package.

var url = "http://api.example.com/api/v1/?param1=1&param2=2";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
exports.checkApi = function (req, res) {
    // do the GET request
    request.get({
        url: url,
        headers: {
            "Authorization": auth
        }
    }, function (error, response, body) {
        if(error)
       { console.error("Error while communication with api and ERROR is :  " + error);
       res.send(error);
    }
        console.log('body : ', body);
        res.send(body);      

    });    
}

Eloquent get only one column as an array

If you receive multiple entries the correct method is called lists.

    Word_relation::select('word_two')->where('word_one', $word_id)->lists('word_one')->toArray();

What is CDATA in HTML?

CDATA is a sequence of characters from the document character set and may include character entities. User agents should interpret attribute values as follows: Replace character entities with characters,

Ignore line feeds,

Replace each carriage return or tab with a single space.

Node.js get file extension

The following function splits the string and returns the name and extension no matter how many dots there are in the extension. It returns an empty string for the extension if there is none. Names that start with dots and/or white space work also.

function basext(name) {
  name = name.trim()
  const match = name.match(/^(\.+)/)
  let prefix = ''
  if (match) {
    prefix = match[0]
    name = name.replace(prefix, '')
  }
  const index = name.indexOf('.')
  const ext = name.substring(index + 1)
  const base = name.substring(0, index) || ext
  return [prefix + base, base === ext ? '' : ext]
}

const [base, ext] = basext('hello.txt')

Inputting a default image in case the src attribute of an html <img> is not valid?

_x000D_
_x000D_
<img style="background-image: url(image1), url(image2);"></img>                                            
_x000D_
_x000D_
_x000D_

Use background image that let you add multiple images. My case: image1 is the main image, this will get from some place (browser doing a request) image2 is a default local image to show while image1 is being loaded. If image1 returns any kind of error, the user won't see any change and this will be clean for user experience

How to prepare a Unity project for git?

Since Unity 4.3 you also have to enable External option from preferences, so full setup process looks like:

  1. Enable External option in Unity ? Preferences ? Packages ? Repository
  2. Switch to Hidden Meta Files in Editor ? Project Settings ? Editor ? Version Control Mode
  3. Switch to Force Text in Editor ? Project Settings ? Editor ? Asset Serialization Mode
  4. Save scene and project from File menu

Note that the only folders you need to keep under source control are Assets and ProjectSettigns.

More information about keeping Unity Project under source control you can find in this post.

select a value where it doesn't exist in another table

SELECT ID
  FROM A
 WHERE ID NOT IN (
      SELECT ID
        FROM B);

SELECT ID    
  FROM A a
 WHERE NOT EXISTS (
      SELECT 1 
        FROM B b
       WHERE b.ID = a.ID)

         SELECT a.ID 
           FROM A a    
LEFT OUTER JOIN B b 
             ON a.ID = b.ID    
          WHERE b.ID IS NULL

DELETE 
  FROM A 
 WHERE ID NOT IN (
      SELECT ID 
        FROM B) 

Already defined in .obj - no double inclusions

This is one of the method to overcome this issue.

  • Just put the prototype in the header files and include the header files in the .cpp files as shown below.

client.cpp

#ifndef SOCKET_CLIENT_CLASS
#define SOCKET_CLIENT_CLASS
#ifndef BOOST_ASIO_HPP
#include <boost/asio.hpp>
#endif

class SocketClient // Or whatever the name is... {

// ...

    bool read(int, char*); // Or whatever the name is...

//  ... };

#endif

client.h

bool SocketClient::read(int, char*)
{
    // Implementation  goes here...
}

main.cpp

#include <iostream>
#include <string>
#include <sstream>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include "client.h"
//              ^^ Notice this!

main.h

int main()

Add an incremental number in a field in INSERT INTO SELECT query in SQL Server

You can use the row_number() function for this.

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

If you want to start with the maximum already in the table then do:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

Finally, you can just make the sequence column an auto-incrementing identity column. This saves the need to increment it each time:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .
)

Debugging Spring configuration

Yes, Spring framework logging is very detailed, You did not mention in your post, if you are already using a logging framework or not. If you are using log4j then just add spring appenders to the log4j config (i.e to log4j.xml or log4j.properties), If you are using log4j xml config you can do some thing like this

<category name="org.springframework.beans">
    <priority value="debug" />
</category>

or

<category name="org.springframework">
    <priority value="debug" />
</category>

I would advise you to test this problem in isolation using JUnit test, You can do this by using spring testing module in conjunction with Junit. If you use spring test module it will do the bulk of the work for you it loads context file based on your context config and starts container so you can just focus on testing your business logic. I have a small example here

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:springContext.xml"})
@Transactional
public class SpringDAOTest 
{
    @Autowired
    private SpringDAO dao;

    @Autowired
    private ApplicationContext appContext;

    @Test
    public void checkConfig()
    {
        AnySpringBean bean =  appContext.getBean(AnySpringBean.class);
        Assert.assertNotNull(bean);
    }
}

UPDATE

I am not advising you to change the way you load logging but try this in your dev environment, Add this snippet to your web.xml file

<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>/WEB-INF/log4j.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

UPDATE log4j config file


I tested this on my local tomcat and it generated a lot of logging on application start up. I also want to make a correction: use debug not info as @Rayan Stewart mentioned.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="%d{HH:mm:ss} %p [%t]:%c{3}.%M()%L - %m%n" />
        </layout>
    </appender>

    <appender name="springAppender" class="org.apache.log4j.RollingFileAppender"> 
        <param name="file" value="C:/tomcatLogs/webApp/spring-details.log" /> 
        <param name="append" value="true" /> 
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="%d{MM/dd/yyyy HH:mm:ss}  [%t]:%c{5}.%M()%L %m%n" />
        </layout>
    </appender>

    <category name="org.springframework">
        <priority value="debug" />
    </category>

    <category name="org.springframework.beans">
        <priority value="debug" />
    </category>

    <category name="org.springframework.security">
        <priority value="debug" />
    </category>

    <category
        name="org.springframework.beans.CachedIntrospectionResults">
        <priority value="debug" />
    </category>

    <category name="org.springframework.jdbc.core">
        <priority value="debug" />
    </category>

    <category name="org.springframework.transaction.support.TransactionSynchronizationManager">
        <priority value="debug" />
    </category>

    <root>
        <priority value="debug" />
        <appender-ref ref="springAppender" />
        <!-- <appender-ref ref="STDOUT"/>  -->
    </root>
</log4j:configuration>

Setting width of spreadsheet cell using PHPExcel

Tha is because getColumnDimensionByColumn receives the column index (an integer starting from 0), not a string.

The same goes for setCellValueByColumnAndRow

IBOutlet and IBAction

One of the top comments on this Question specifically asks:

All the answers mention the same type of idea.. but nobody explains why Interface Builder seems to work just the same if you DO NOT include IBAction/IBOutlet in your source. Is there another reason for IBAction and IBOutlet or is it ok to leave them off?


This question is answered well by NSHipster:

IBAction

https://nshipster.com/ibaction-iboutlet-iboutletcollection/#ibaction

As early as 2004 (and perhaps earlier), IBAction was no longer necessary for a method to be noticed by Interface Builder. Any method with the signature -(void){name}:(id)sender would be visible in the outlets pane.

Nevertheless, many developers find it useful to still use the IBAction return type in method declarations to denote that a particular method is connected to by an action. Even projects not using Storyboards / XIBs may choose to employ IBAction to call out target / action methods.

IBOutlet:

https://nshipster.com/ibaction-iboutlet-iboutletcollection/#iboutlet

Unlike IBAction, IBOutlet is still required for hooking up properties in code with objects in a Storyboard or XIB.

An IBOutlet connection is usually established between a view or control and its managing view controller (this is often done in addition to any IBActions that a view controller might be targeted to perform by a responder). However, an IBOutlet can also be used to expose a top-level property, like another controller or a property that could then be accessed by a referencing view controller.

What is the difference between Scala's case class and class?

According to Scala's documentation:

Case classes are just regular classes that are:

  • Immutable by default
  • Decomposable through pattern matching
  • Compared by structural equality instead of by reference
  • Succinct to instantiate and operate on

Another feature of the case keyword is the compiler automatically generates several methods for us, including the familiar toString, equals, and hashCode methods in Java.

Django - Static file not found

I found that I moved my DEBUG setting in my local settings to be overwritten by a default False value. Essentially look to make sure the DEBUG setting is actually false if you are developing with DEBUG and runserver.

Why doesn't JUnit provide assertNotEquals methods?

The obvious reason that people wanted assertNotEquals() was to compare builtins without having to convert them to full blown objects first:

Verbose example:

....
assertThat(1, not(equalTo(Integer.valueOf(winningBidderId))));
....

vs.

assertNotEqual(1, winningBidderId);

Sadly since Eclipse doesn't include JUnit 4.11 by default you must be verbose.

Caveat I don't think the '1' needs to be wrapped in an Integer.valueOf() but since I'm newly returned from .NET don't count on my correctness.

What are the differences between a pointer variable and a reference variable in C++?

The difference is that non-constant pointer variable(not to be confused with a pointer to constant) may be changed at some time during program execution, requires pointer semantics to be used(&,*) operators, while references can be set upon initialization only(that's why you can set them in constructor initializer list only, but not somehow else) and use ordinary value accessing semantics. Basically references were introduced to allow support for operators overloading as I had read in some very old book. As somebody stated in this thread - pointer can be set to 0 or whatever value you want. 0(NULL, nullptr) means that the pointer is initialized with nothing. It is an error to dereference null pointer. But actually the pointer may contain a value that doesn't point to some correct memory location. References in their turn try not to allow a user to initialize a reference to something that cannot be referenced due to the fact that you always provide rvalue of correct type to it. Although there are a lot of ways to make reference variable be initialized to a wrong memory location - it is better for you not to dig this deep into details. On machine level both pointer and reference work uniformly - via pointers. Let's say in essential references are syntactic sugar. rvalue references are different to this - they are naturally stack/heap objects.

Determine if char is a num or letter

You'll want to use the isalpha() and isdigit() standard functions in <ctype.h>.

char c = 'a'; // or whatever

if (isalpha(c)) {
    puts("it's a letter");
} else if (isdigit(c)) {
    puts("it's a digit");
} else {
    puts("something else?");
}

Converting a string to int in Groovy

also you can make static import

import static java.lang.Integer.parseInt as asInteger

and after this use

String s = "99"
asInteger(s)

How do you create an asynchronous method in C#?

One very simple way to make a method asynchronous is to use Task.Yield() method. As MSDN states:

You can use await Task.Yield(); in an asynchronous method to force the method to complete asynchronously.

Insert it at beginning of your method and it will then return immediately to the caller and complete the rest of the method on another thread.

private async Task<DateTime> CountToAsync(int num = 1000)
{
    await Task.Yield();
    for (int i = 0; i < num; i++)
    {
        Console.WriteLine("#{0}", i);
    }
    return DateTime.Now;
}

Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;

I was getting this error after adding the facebooksdk.jar to a project that already had dependencies on the android-support-v4.jar. Since the facebooksdk.jar already includes its own android-support-v4.jar there were conflicts. Removing the earlier android-support-v4.jar from the projects Properties / Java Build Path / Libraries resolved the issue for me.

SQL Server - copy stored procedures from one db to another

Late one but gives more details that might be useful…

Here is a list of things you can do with advantages and disadvantages

Generate scripts using SSMS

  • Pros: extremely easy to use and supported by default
  • Cons: scripts might not be in the correct execution order and you might get errors if stored procedure already exists on secondary database. Make sure you review the script before executing.

Third party tools

  • Pros: tools such as ApexSQL Diff (this is what I use but there are many others like tools from Red Gate or Dev Art) will compare two databases in one click and generate script that you can execute immediately
  • Cons: these are not free (most vendors have a fully functional trial though)

System Views

  • Pros: You can easily see which stored procedures exist on secondary server and only generate those you don’t have.
  • Cons: Requires a bit more SQL knowledge

Here is how to get a list of all procedures in some database that don’t exist in another database

select *
from DB1.sys.procedures P
where P.name not in 
 (select name from DB2.sys.procedures P2)

Why use @Scripts.Render("~/bundles/jquery")

You can also use:

@Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}\"></script>", "~/bundles/mybundle")

To specify the format of your output in a scenario where you need to use Charset, Type, etc.

Crop image in android

This library: Android-Image-Cropper is very powerful to CropImages. It has 3,731 stars on github at this time.

You will crop your images with a few lines of code.

1 - Add the dependecies into buid.gradle (Module: app)

compile 'com.theartofdev.edmodo:android-image-cropper:2.7.+'

2 - Add the permissions into AndroidManifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

3 - Add CropImageActivity into AndroidManifest.xml

<activity android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
 android:theme="@style/Base.Theme.AppCompat"/>

4 - Start the activity with one of the cases below, depending on your requirements.

// start picker to get image for cropping and then use the image in cropping activity
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);

// start cropping activity for pre-acquired image saved on the device
CropImage.activity(imageUri)
.start(this);

// for fragment (DO NOT use `getActivity()`)
CropImage.activity()
.start(getContext(), this);

5 - Get the result in onActivityResult

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
    CropImage.ActivityResult result = CropImage.getActivityResult(data);
    if (resultCode == RESULT_OK) {
      Uri resultUri = result.getUri();
    } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
      Exception error = result.getError();
    }
  }
}

You can do several customizations, as set the Aspect Ratio or the shape to RECTANGLE, OVAL and a lot more.

Is there a decent wait function in C++?

Before the return statement in you main, insert this code:

system("pause");

This will hold the console until you hit a key.

#include<iostream>
#include<string>

using namespace std;

int main()
{
    string s;
    cout << "Please enter your first name followed by a newline\n";
    cin >> s;
    cout << "Hello, " << s << '\n';
    system("pause");
    return 0; // this return statement isn't necessary
}

Where does PHP's error log reside in XAMPP?

Look in your configuration file and search for the error_log setting. Or use phpinfo() to find this setting.

How to resize JLabel ImageIcon?

Try this :

ImageIcon imageIcon = new ImageIcon("./img/imageName.png"); // load the image to a imageIcon
Image image = imageIcon.getImage(); // transform it 
Image newimg = image.getScaledInstance(120, 120,  java.awt.Image.SCALE_SMOOTH); // scale it the smooth way  
imageIcon = new ImageIcon(newimg);  // transform it back

(found it here)

How do I retrieve my MySQL username and password?

While you can't directly recover a MySQL password without bruteforcing, there might be another way - if you've used MySQL Workbench to connect to the database, and have saved the credentials to the "vault", you're golden.

On Windows, the credentials are stored in %APPDATA%\MySQL\Workbench\workbench_user_data.dat - encrypted with CryptProtectData (without any additional entropy). Decrypting is easy peasy:

std::vector<unsigned char> decrypt(BYTE *input, size_t length) {
    DATA_BLOB inblob { length, input };
    DATA_BLOB outblob;

    if (!CryptUnprotectData(&inblob, NULL, NULL, NULL, NULL, CRYPTPROTECT_UI_FORBIDDEN, &outblob)) {
            throw std::runtime_error("Couldn't decrypt");
    }

    std::vector<unsigned char> output(length);
    memcpy(&output[0], outblob.pbData, outblob.cbData);

    return output;
}

Or you can check out this DonationCoder thread for source + executable of a quick-and-dirty implementation.

css label width not taking effect

label's default display mode is inline, which means it automatically sizes itself to it's content. To set a width you'll need to set display:block and then do some faffing to get it positioned correctly (probably involving float)

How to format numbers?

 function formatNumber1(number) {
  var comma = ',',
      string = Math.max(0, number).toFixed(0),
      length = string.length,
      end = /^\d{4,}$/.test(string) ? length % 3 : 0;
  return (end ? string.slice(0, end) + comma : '') + string.slice(end).replace(/(\d{3})(?=\d)/g, '$1' + comma);
 }

 function formatNumber2(number) {
  return Math.max(0, number).toFixed(0).replace(/(?=(?:\d{3})+$)(?!^)/g, ',');
 }

Source: http://jsperf.com/number-format

Create a date from day month and year with T-SQL

If you don't want to keep strings out of it, this works as well (Put it into a function):

DECLARE @Day int, @Month int, @Year int
SELECT @Day = 1, @Month = 2, @Year = 2008

SELECT DateAdd(dd, @Day-1, DateAdd(mm, @Month -1, DateAdd(yy, @Year - 2000, '20000101')))

Hash and salt passwords in C#

Bah, this is better! http://sourceforge.net/projects/pwdtknet/ and it is better because ..... it performs Key Stretching AND uses HMACSHA512 :)

Xcode build failure "Undefined symbols for architecture x86_64"

When updating to Xcode 7.1, you might see this type of error, and it can't be resolved by any of the above answers. One of the symptoms in my case was that the app runs on the device not in the simulator. You'll probably see a huge number of errors related to pretty much all of the frameworks you're using.

The fix is actually quite simple. You just need to delete an entry from the "Framework Search Paths" setting, found in your TARGETS > Build Settings > Search Paths section (make sure the "All" tab is selected)

enter image description here

If you see another entry here (besides $(inherited)) for your main target(s) or your test target, just delete the faulty path from all targets and rebuild.

Apache Server (xampp) doesn't run on Windows 10 (Port 80)

I know that maybe this problem was resolved but I had the same problem with different solution. For that, I am going to explain another possible solution. In my case, the port 80 was occupied by Skype (pid: 25252) and I did not know what programme was.

To see the program's pid which is using the port 80 you can use the command that other people said before:

netstat -aon | findstr 0.0:80

To kill the process using the pid (in the case that you do not know the programme) you have to open the CMD with administrator permission and use the next command:

taskkill /pid 25252

Other options with this command are here.

SQL Inner join more than two tables

Try this Here the syntax is

SELECT table1 .columnName, table3 .columnName 
   FROM table1 
     inner join table2 
          ON table1.primarykey = table2.foreignkey 
     inner join table3 
          ON table2.primarykey = table3.foreignkey

for example: Select SalesHeader.invoiceDate,ActualSales,DeptName,tblInvDepartment.DeptCode ,LocationCode from SalesDetail Inner Join SalesHeader on SalesDetail.InvoiceNo = SalesHeader.InvoiceNo inner join tblInvDepartment on tblInvDepartment.DeptCode = SalesDetail.DeptCode

VLook-Up Match first 3 characters of one column with another column

=VLOOKUP(LEFT(A4,LEN(A4)-9),$D:$F,3,0)

I use this if my Lookup_Value needs to be truncated because of the format the name is in the Table_Array. E.g. my Lookup_Value is "Eastbay District", but the Table_Array list I have only shows this as "Eastbay". "Eastbay District" minus 9 characters will result in "Eastbay".

I hope this helps!

ipynb import another ipynb file

Install ipynb from your command prompt

pip install import-ipynb

Import in your notebook file

import import_ipynb

Now use regular import command to import your file

import MyOtherNotebook

Get column from a two dimensional array

Taking a column is easy with the map function.

// a two-dimensional array
var two_d = [[1,2,3],[4,5,6],[7,8,9]];

// take the third column
var col3 = two_d.map(function(value,index) { return value[2]; });

Why bother with the slice at all? Just filter the matrix to find the rows of interest.

var interesting = two_d.filter(function(value,index) {return value[1]==5;});
// interesting is now [[4,5,6]]

Sadly, filter and map are not natively available on IE9 and lower. The MDN documentation provides implementations for browsers without native support.

Content Type text/xml; charset=utf-8 was not supported by service

First Google hit says:

this is usually a mismatch in the client/server bindings, where the message version in the service uses SOAP 1.2 (which expects application/soap+xml) and the version in the client uses SOAP 1.1 (which sends text/xml). WSHttpBinding uses SOAP 1.2, BasicHttpBinding uses SOAP 1.1.

It usually seems to be a wsHttpBinding on one side and a basicHttpBinding on the other.

XMLHttpRequest module not defined/found

With the xhr2 library you can globally overwrite XMLHttpRequest from your JS code. This allows you to use external libraries in node, that were intended to be run from browsers / assume they are run in a browser.

global.XMLHttpRequest = require('xhr2');

Need to perform Wildcard (*,?, etc) search on a string using Regex

d* means that it should match zero or more "d" characters. So any string is a valid match. Try d+ instead!

In order to have support for wildcard patterns I would replace the wildcards with the RegEx equivalents. Like * becomes .* and ? becomes .?. Then your expression above becomes d.*

Error: Can't set headers after they are sent to the client

Came here from nuxt, the problem was in the component's asyncData method, I forgot to return promise which was fetching data and setting header there.

Replace None with NaN in pandas dataframe

If you use df.replace([None], np.nan, inplace=True), this changed all datetime objects with missing data to object dtypes. So now you may have broken queries unless you change them back to datetime which can be taxing depending on the size of your data.

If you want to use this method, you can first identify the object dtype fields in your df and then replace the None:

obj_columns = list(df.select_dtypes(include=['object']).columns.values)
df[obj_columns] = df[obj_columns].replace([None], np.nan)

Nested Recycler view height doesn't wrap its content

Used solution from @sinan-kozak, except fixed a few bugs. Specifically, we shouldn't use View.MeasureSpec.UNSPECIFIED for both the width and height when calling measureScrapChild as that won't properly account for wrapped text in the child. Instead, we will pass through the width and height modes from the parent which will allow things to work for both horizontal and vertical layouts.

public class MyLinearLayoutManager extends LinearLayoutManager {

public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout)    {
    super(context, orientation, reverseLayout);
}

private int[] mMeasuredDimension = new int[2];

@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
                      int widthSpec, int heightSpec) {
    final int widthMode = View.MeasureSpec.getMode(widthSpec);
    final int heightMode = View.MeasureSpec.getMode(heightSpec);
    final int widthSize = View.MeasureSpec.getSize(widthSpec);
    final int heightSize = View.MeasureSpec.getSize(heightSpec);
    int width = 0;
    int height = 0;
    for (int i = 0; i < getItemCount(); i++) {    
        if (getOrientation() == HORIZONTAL) {
            measureScrapChild(recycler, i,
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(heightSize, heightMode),
                mMeasuredDimension);

            width = width + mMeasuredDimension[0];
            if (i == 0) {
                height = mMeasuredDimension[1];
            }
        } else {
            measureScrapChild(recycler, i,
                View.MeasureSpec.makeMeasureSpec(widthSize, widthMode),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                mMeasuredDimension);

            height = height + mMeasuredDimension[1];
            if (i == 0) {
                width = mMeasuredDimension[0];
            }
        }
    }

    // If child view is more than screen size, there is no need to make it wrap content. We can use original onMeasure() so we can scroll view.
    if (height < heightSize && width < widthSize) {

        switch (widthMode) {
            case View.MeasureSpec.EXACTLY:
                width = widthSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        switch (heightMode) {
            case View.MeasureSpec.EXACTLY:
                height = heightSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        setMeasuredDimension(width, height);
    } else {
        super.onMeasure(recycler, state, widthSpec, heightSpec);
    }
}

private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                               int heightSpec, int[] measuredDimension) {

   View view = recycler.getViewForPosition(position);

   // For adding Item Decor Insets to view
   super.measureChildWithMargins(view, 0, 0);
    if (view != null) {
        RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
        int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                    getPaddingLeft() + getPaddingRight() + getDecoratedLeft(view) + getDecoratedRight(view), p.width);
            int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                    getPaddingTop() + getPaddingBottom() + getDecoratedTop(view) + getDecoratedBottom(view) , p.height);
            view.measure(childWidthSpec, childHeightSpec);

            // Get decorated measurements
            measuredDimension[0] = getDecoratedMeasuredWidth(view) + p.leftMargin + p.rightMargin;
            measuredDimension[1] = getDecoratedMeasuredHeight(view) + p.bottomMargin + p.topMargin;
            recycler.recycleView(view);
        }
    }
}

`

how to read a long multiline string line by line in python

What about using .splitlines()?

for line in textData.splitlines():
    print(line)
    lineResult = libLAPFF.parseLine(line)

Reduce git repository size

Thanks for your replies. Here's what I did:

git gc
git gc --aggressive
git prune

That seemed to have done the trick. I started with around 10.5MB and now it's little more than 980KBs.

Is div inside list allowed?

If I recall correctly, a div inside a li used to be invalid.

@Flower @Superstringcheese Div should semantically define a section of a document, but it has already practically lost this role. Span should however contain text.

Paste text on Android Emulator

Just click the left mouse button for 2 or 3 seconds, paste button will be appear. Click the paste button and the test will be copied smoothly.

MAX function in where clause mysql

Use a subselect:

SELECT row  FROM table  WHERE id=(
    SELECT max(id) FROM table
)

Note: ID must be unique, else multiple rows are returned

Get a worksheet name using Excel VBA

Sub FnGetSheetsName()

    Dim mainworkBook As Workbook

    Set mainworkBook = ActiveWorkbook

    For i = 1 To mainworkBook.Sheets.Count

    'Either we can put all names in an array , here we are printing all the names in Sheet 2

    mainworkBook.Sheets("Sheet2").Range("A" & i) = mainworkBook.Sheets(i).Name

    Next i

End Sub

Using the AND and NOT Operator in Python

Use the keyword and, not & because & is a bit operator.

Be careful with this... just so you know, in Java and C++, the & operator is ALSO a bit operator. The correct way to do a boolean comparison in those languages is &&. Similarly | is a bit operator, and || is a boolean operator. In Python and and or are used for boolean comparisons.

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

With C++17 you can use std::basic_string_view & with C++20 std::basic_string::starts_with or std::basic_string_view::starts_with.

The benefit of std::string_view in comparison to std::string - regarding memory management - is that it only holds a pointer to a "string" (contiguous sequence of char-like objects) and knows its size. Example without moving/copying the source strings just to get the integer value:

#include <exception>
#include <iostream>
#include <string>
#include <string_view>

int main()
{
    constexpr auto argument = "--foo=42"; // Emulating command argument.
    constexpr auto prefix = "--foo=";
    auto inputValue = 0;

    constexpr auto argumentView = std::string_view(argument);
    if (argumentView.starts_with(prefix))
    {
        constexpr auto prefixSize = std::string_view(prefix).size();
        try
        {
            // The underlying data of argumentView is nul-terminated, therefore we can use data().
            inputValue = std::stoi(argumentView.substr(prefixSize).data());
        }
        catch (std::exception & e)
        {
            std::cerr << e.what();
        }
    }
    std::cout << inputValue; // 42
}

Convert datatable to JSON in C#

All of these answers are really great for moving data! Where they fail is preserving the column type of data being moved. This becomes a problem when you want to do things like merge datatables that appear to be the same. JsonConvert will look at the first row of data to determine the column datatype, which may be guessed incorrectly.

To get around this;

  • Serialize the DataTable and DataColumn definitions in separate response objects.
  • Deserialize the DataColumn definitions in the response before reading in the table.
  • Deserialize and merge the DataTable ignoring the schema defined by Json.

It sounds like a lot, but its only three additional lines of code.

// Get our Column definitions and serialize them using an anoymous function.
var columns = dt.Columns.Cast<DataColumn>().Select(c => new { DataPropertyName = c.ColumnName, DataPropertyType = c.DataType.ToString()});
resp.ObjSchema = JsonConvert.SerializeObject(columns);
resp.Obj = JsonConvert.SerializeObject(dt);

resp.ObjSchema becomes;

[
  {
    "DataPropertyName": "RowId",
    "DataPropertyType ": "System.Int32"
  },
  {
    "DataPropertyName": "ItemName",
    "DataPropertyType ": "System.String"
  }
]

Instead of letting Json define the column definitions via dt = JsonConvert.DeserializeObject<DataTable>(response) we can use LINQ on our resp.ObjSchema to define them ourselves. We'll use MissingSchemaAction.Ignore to ignore the schema provided by Json.

// If your environment does not support dynamic you'll need to create a class for with DataPropertyName and DataPropertyType.
JsonConvert.DeserializeObject<List<dynamic>>(response.ObjSchema).ForEach(prop =>
{
    dt.Columns.Add(new DataColumn() { ColumnName = prop.DataPropertyName, DataType = Type.GetType(prop.DataPropertyType.ToString()) });
});
// Merge the results ignoring the JSON schema.
dt.Merge(JsonConvert.DeserializeObject<DataTable>(response.Obj), true, MissingSchemaAction.Ignore);

error: use of deleted function

In the current C++0x standard you can explicitly disable default constructors with the delete syntax, e.g.

MyClass() = delete;

Gcc 4.6 is the first version to support this syntax, so maybe that is the problem...

Apache - MySQL Service detected with wrong path. / Ports already in use

This is how I solved similar problem:

  1. Launch XAMPP Control Panel.
  2. Uninstall the MySQL service: click 'green check' button beside MySQL, under Service column. The 'green check' button will change into 'red cross' button.
  3. Exit XAMPP, and relaunch it again.
  4. Click Start.

I hope it can help solve your problem too.

How to get the nvidia driver version from the command line?

Windows version:

cd \Program Files\NVIDIA Corporation\NVSMI

nvidia-smi

Execute SQLite script

For those using PowerShell

PS C:\> Get-Content create.sql -Raw | sqlite3 auction.db

Where does VBA Debug.Print log to?

Debug.Print outputs to the "Immediate" window.

Debug.Print outputs to the Immediate window

Also, you can simply type ? and then a statement directly into the immediate window (and then press Enter) and have the output appear right below, like this:

simply type ? and then a statement directly into the immediate window

This can be very handy to quickly output the property of an object...

? myWidget.name

...to set the property of an object...

myWidget.name = "thingy"

...or to even execute a function or line of code, while in debugging mode:

Sheet1.MyFunction()

Which is better: <script type="text/javascript">...</script> or <script>...</script>

Do you need a type attribute at all? If you're using HTML5, no. Otherwise, yes. HTML 4.01 and XHTML 1.0 specifies the type attribute as required while HTML5 has it as optional, defaulting to text/javascript. HTML5 is now widely implemented, so if you use the HTML5 doctype, <script>...</script> is valid and a good choice.

As to what should go in the type attribute, the MIME type application/javascript registered in 2006 is intended to replace text/javascript and is supported by current versions of all the major browsers (including Internet Explorer 9). A quote from the relevant RFC:

This document thus defines text/javascript and text/ecmascript but marks them as "obsolete". Use of experimental and unregistered media types, as listed in part above, is discouraged. The media types,

  * application/javascript
  * application/ecmascript

which are also defined in this document, are intended for common use and should be used instead.

However, IE up to and including version 8 doesn't execute script inside a <script> element with a type attribute of either application/javascript or application/ecmascript, so if you need to support old IE, you're stuck with text/javascript.

Lombok added but getters and setters not recognized in Intellij IDEA

I had both the Lombok plugin installed and Annotation Processing enabled within IntelliJ and my syntax highlighting still wasn't working properly. This could have been due to the 2017 to 2018 IDEA upgrade. I was getting warnings "access exceeds rights" on private fields within classes I had used @Getter and @Setter on.

I had to uninstall the Lombok plugin, restart IntelliJ, then reinstall the plugin, and restart IntelliJ once more.

Everything is working good now.

JavaScript URL Decode function

//How decodeURIComponent Works

function proURIDecoder(val)
{
  val=val.replace(/\+/g, '%20');
  var str=val.split("%");
  var cval=str[0];
  for (var i=1;i<str.length;i++)
  {
    cval+=String.fromCharCode(parseInt(str[i].substring(0,2),16))+str[i].substring(2);
  }

  return cval;
}

document.write(proURIDecoder(window.location.href));

ASP.Net MVC Redirect To A Different View

Here's what you can do:

return View("another view name", anotherviewmodel);

VBA copy rows that meet criteria to another sheet

You need to specify workseet. Change line

If Worksheet.Cells(i, 1).Value = "X" Then

to

If Worksheets("Sheet2").Cells(i, 1).Value = "X" Then

UPD:

Try to use following code (but it's not the best approach. As @SiddharthRout suggested, consider about using Autofilter):

Sub LastRowInOneColumn()
   Dim LastRow As Long
   Dim i As Long, j As Long

   'Find the last used row in a Column: column A in this example
   With Worksheets("Sheet2")
      LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
   End With

   MsgBox (LastRow)
   'first row number where you need to paste values in Sheet1'
   With Worksheets("Sheet1")
      j = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
   End With 

   For i = 1 To LastRow
       With Worksheets("Sheet2")
           If .Cells(i, 1).Value = "X" Then
               .Rows(i).Copy Destination:=Worksheets("Sheet1").Range("A" & j)
               j = j + 1
           End If
       End With
   Next i
End Sub

Force browser to clear cache

I had a case where I would take photos of clients online and would need to update the div if a photo is changed. Browser was still showing the old photo. So I used the hack of calling a random GET variable, which would be unique every time. Here it is if it could help anybody

<img src="/photos/userid_73.jpg?random=<?php echo rand() ?>" ...

EDIT As pointed out by others, following is much more efficient solution since it will reload images only when they are changed, identifying this change by the file size:

<img src="/photos/userid_73.jpg?modified=<? filemtime("/photos/userid_73.jpg")?>"

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

This is a typical bidirectional consistency problem. It is well discussed in this link as well as this link.

As per the articles in the previous 2 links you need to fix your setters in both sides of the bidirectional relationship. An example setter for the One side is in this link.

An example setter for the Many side is in this link.

After you correct your setters you want to declare the Entity access type to be "Property". Best practice to declare "Property" access type is to move ALL the annotations from the member properties to the corresponding getters. A big word of caution is not to mix "Field" and "Property" access types within the entity class otherwise the behavior is undefined by the JSR-317 specifications.

Angular2 disable button

Using ngClass to disabled the button for invalid form is not good practice in Angular2 when its providing inbuilt features to enable and disable the button if form is valid and invalid respectively without doing any extra efforts/logic.

[disabled] will do all thing like if form is valid then it will be enabled and if form is invalid then it will be disabled automatically.

See Example:

<form (ngSubmit)="f.form.valid" #f="ngForm" novalidate>
<input type="text" placeholder="Name" [(ngModel)]="txtName" name="txtname" #textname="ngModel" required>
<input type="button" class="mdl-button" [disabled]="!f.form.valid" (click)="onSave()" name="">

How to find the number of days between two dates

Get No of Days between two days

DECLARE @date1 DATE='2015-01-01',
 @date2 DATE='2019-01-01',
 @Total int=null

SET @Total=(SELECT DATEDIFF(DAY, @date1, @date2))
PRINT @Total

How to set width of a div in percent in JavaScript?

The question is what do you want the div's height/width to be a percent of?

By default, if you assign a percentage value to a height/width it will be relative to it's direct parent dimensions. If the parent doesn't have a defined height, then it won't work.

So simply, remember to set the height of the parent, then a percentage height will work via the css attribute:

obj.style.width = '50%';

Django auto_now and auto_now_add

I think the easiest (and maybe most elegant) solution here is to leverage the fact that you can set default to a callable. So, to get around admin's special handling of auto_now, you can just declare the field like so:

from django.utils import timezone
date_field = models.DateField(default=timezone.now)

It's important that you don't use timezone.now() as the default value wouldn't update (i.e., default gets set only when the code is loaded). If you find yourself doing this a lot, you could create a custom field. However, this is pretty DRY already I think.

vertical-align: middle with Bootstrap 2

If I remember correctly from my own use of bootstrap, the .spanN classes are floated, which automatically makes them behave as display: block. To make display: table-cell work, you need to remove the float.

What does "static" mean in C?

It is important to note that static variables in functions get initialized at the first entry into that function and persist even after their call has been finished; in case of recursive functions the static variable gets initialized only once and persists as well over all recursive calls and even after the call of the function has been finished.

If the variable has been created outside a function, it means that the programmer is only able to use the variable in the source-file the variable has been declared.

jQuery: Clearing Form Inputs

I figured out what it was! When I cleared the fields using the each() method, it also cleared the hidden field which the php needed to run:

if ($_POST['action'] == 'addRunner') 

I used the :not() on the selection to stop it from clearing the hidden field.

Get timezone from DateTime

You could use TimeZoneInfo class

The TimeZone class recognizes local time zone, and can convert times between Coordinated Universal Time (UTC) and local time. A TimeZoneInfo object can represent any time zone, and methods of the TimeZoneInfo class can be used to convert the time in one time zone to the corresponding time in any other time zone. The members of the TimeZoneInfo class support the following operations:

  1. Retrieving a time zone that is already defined by the operating system.

  2. Enumerating the time zones that are available on a system.

  3. Converting times between different time zones.

  4. Creating a new time zone that is not already defined by the operating system.

    Serializing a time zone for later retrieval.

How to set the height of an input (text) field in CSS?

Form controls are notoriously difficult to style cross-platform/browser. Some browsers will honor a CSS height rule, some won't.

You can try line-height (may need display:block; or display:inline-block;) or top and bottom padding also. If none of those work, that's pretty much it - use a graphic, position the input in the center and set border:none; so it looks like the form control is big but it actually isn't...

How to stick <footer> element at the bottom of the page (HTML5 and CSS3)?

Here is an example using css3:

CSS:

html, body {
    height: 100%;
    margin: 0;
}
#wrap {
    padding: 10px;
    min-height: -webkit-calc(100% - 100px);     /* Chrome */
    min-height: -moz-calc(100% - 100px);     /* Firefox */
    min-height: calc(100% - 100px);     /* native */
}
.footer {
    position: relative;
    clear:both;
}

HTML:

<div id="wrap">
    body content....
</div>
<footer class="footer">
    footer content....
</footer>

jsfiddle

Update
As @Martin pointed, the ´position: relative´ is not mandatory on the .footer element, the same for clear:both. These properties are only there as an example. So, the minimum css necessary to stick the footer on the bottom should be:

html, body {
    height: 100%;
    margin: 0;
}
#wrap {
    min-height: -webkit-calc(100% - 100px);     /* Chrome */
    min-height: -moz-calc(100% - 100px);     /* Firefox */
    min-height: calc(100% - 100px);     /* native */
}

Also, there is an excellent article at css-tricks showing different ways to do this: https://css-tricks.com/couple-takes-sticky-footer/

Breaking up long strings on multiple lines in Ruby without stripping newlines

I had this problem when I try to write a very long url, the following works.

image_url = %w(
    http://minio.127.0.0.1.xip.io:9000/
    bucket29/docs/b7cfab0e-0119-452c-b262-1b78e3fccf38/
    28ed3774-b234-4de2-9a11-7d657707f79c?
    X-Amz-Algorithm=AWS4-HMAC-SHA256&
    X-Amz-Credential=ABABABABABABABABA
    %2Fus-east-1%2Fs3%2Faws4_request&
    X-Amz-Date=20170702T000940Z&
    X-Amz-Expires=3600&X-Amz-SignedHeaders=host&
    X-Amz-Signature=ABABABABABABABABABABAB
    ABABABABABABABABABABABABABABABABABABA
).join

Note, there must not be any newlines, white spaces when the url string is formed. If you want newlines, then use HEREDOC.

Here you have indentation for readability, ease of modification, without the fiddly quotes and backslashes on every line. The cost of joining the strings should be negligible.

Code signing is required for product type 'Application' in SDK 'iOS5.1'

TN2250 Tech document was retired,To resolve this add IOs5.1 or 8.1 sdk field under Anyios SDK field

in code sign problem will solved

How to print the ld(linker) search path

On Linux, you can use ldconfig, which maintains the ld.so configuration and cache, to print out the directories search by ld.so with

ldconfig -v 2>/dev/null | grep -v ^$'\t'

ldconfig -v prints out the directories search by the linker (without a leading tab) and the shared libraries found in those directories (with a leading tab); the grep gets the directories. On my machine, this line prints out

/usr/lib64/atlas:
/usr/lib/llvm:
/usr/lib64/llvm:
/usr/lib64/mysql:
/usr/lib64/nvidia:
/usr/lib64/tracker-0.12:
/usr/lib/wine:
/usr/lib64/wine:
/usr/lib64/xulrunner-2:
/lib:
/lib64:
/usr/lib:
/usr/lib64:
/usr/lib64/nvidia/tls: (hwcap: 0x8000000000000000)
/lib/i686: (hwcap: 0x0008000000000000)
/lib64/tls: (hwcap: 0x8000000000000000)
/usr/lib/sse2: (hwcap: 0x0000000004000000)
/usr/lib64/tls: (hwcap: 0x8000000000000000)
/usr/lib64/sse2: (hwcap: 0x0000000004000000)

The first paths, without hwcap in the line, are either built-in or read from /etc/ld.so.conf. The linker can then search additional directories under the basic library search path, with names like sse2 corresponding to additional CPU capabilities. These paths, with hwcap in the line, can contain additional libraries tailored for these CPU capabilities.

One final note: using -p instead of -v above searches the ld.so cache instead.

How to force cp to overwrite without confirmation

cp is usually aliased like this

alias cp='cp -i'   # i.e. ask questions of overwriting

if you are sure that you want to do the overwrite then use this:

/bin/cp <arguments here> src dest

How can I get just the first row in a result set AFTER ordering?

In 12c, here's the new way:

select bla
  from bla
 where bla
 order by finaldate desc
 fetch first 1 rows only; 

How nice is that!

Getting a browser's name client-side

Based on is.js you can write a helper file for getting browser name like this-

const Browser = {};
const vendor = (navigator && navigator.vendor || '').toLowerCase();
const userAgent = (navigator && navigator.userAgent || '').toLowerCase();

Browser.getBrowserName = () => {
  if(isOpera()) return 'opera'; // Opera
  else if(isChrome()) return 'chrome'; // Chrome
  else if(isFirefox()) return 'firefox'; // Firefox
  else if(isSafari()) return 'safari'; // Safari
  else if(isInternetExplorer()) return 'ie'; // Internet Explorer
}


// Start Detecting browser helpers functions
function isOpera() {
  const isOpera = userAgent.match(/(?:^opera.+?version|opr)\/(\d+)/);
  return isOpera !== null;
}

function isChrome() {
  const isChrome = /google inc/.test(vendor) ? userAgent.match(/(?:chrome|crios)\/(\d+)/) : null;
  return isChrome !== null;
}

function isFirefox() {
  const isFirefox = userAgent.match(/(?:firefox|fxios)\/(\d+)/);
  return isFirefox !== null;
}

function isSafari() {
  const isSafari = userAgent.match(/version\/(\d+).+?safari/);
  return isSafari !== null;
}

function isInternetExplorer() {
  const isInternetExplorer = userAgent.match(/(?:msie |trident.+?; rv:)(\d+)/);
  return isInternetExplorer !== null;
}
// End Detecting browser helpers functions

export default Browser;

And just import this file where you need.

import Browser from './Browser.js';

const userBrowserName = Browser.getBrowserName() // return your browser name
                                                 // opera | chrome | firefox | safari | ie

ToggleButton in C# WinForms

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

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

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

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

Understanding Apache's access log

And what does "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.5 Safari/535.19" means ?

This is the value of User-Agent, the browser identification string.

For this reason, most Web browsers use a User-Agent string value as follows:

Mozilla/[version] ([system and browser information]) [platform] ([platform details]) [extensions]. For example, Safari on the iPad has used the following:

Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405 The components of this string are as follows:

Mozilla/5.0: Previously used to indicate compatibility with the Mozilla rendering engine. (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us): Details of the system in which the browser is running. AppleWebKit/531.21.10: The platform the browser uses. (KHTML, like Gecko): Browser platform details. Mobile/7B405: This is used by the browser to indicate specific enhancements that are available directly in the browser or through third parties. An example of this is Microsoft Live Meeting which registers an extension so that the Live Meeting service knows if the software is already installed, which means it can provide a streamlined experience to joining meetings.

This value will be used to identify what browser is being used by end user.

Refer

How to uninstall Ruby from /usr/local?

do this way :

sudo apt purge ruby

Copy multiple files in Python

Here is another example of a recursive copy function that lets you copy the contents of the directory (including sub-directories) one file at a time, which I used to solve this problem.

import os
import shutil

def recursive_copy(src, dest):
    """
    Copy each file from src dir to dest dir, including sub-directories.
    """
    for item in os.listdir(src):
        file_path = os.path.join(src, item)

        # if item is a file, copy it
        if os.path.isfile(file_path):
            shutil.copy(file_path, dest)

        # else if item is a folder, recurse 
        elif os.path.isdir(file_path):
            new_dest = os.path.join(dest, item)
            os.mkdir(new_dest)
            recursive_copy(file_path, new_dest)

EDIT: If you can, definitely just use shutil.copytree(src, dest). This requires that that destination folder does not already exist though. If you need to copy files into an existing folder, the above method works well!

Difference between View and table in sql

Table: Table is a preliminary storage for storing data and information in RDBMS. A table is a collection of related data entries and it consists of columns and rows.

View: A view is a virtual table whose contents are defined by a query. Unless indexed, a view does not exist as a stored set of data values in a database. Advantages over table are

  • We can combine columns/rows from multiple table or another view and have a consolidated view.
  • Views can be used as security mechanisms by letting users access data through the view, without granting the users permissions to directly access the underlying base tables of the view
  • It acts as abstract layer to downstream systems, so any change in schema is not exposed and hence the downstream systems doesn't get affected.

How to 'insert if not exists' in MySQL?

use INSERT IGNORE INTO table

see http://bogdan.org.ua/2007/10/18/mysql-insert-if-not-exists-syntax.html

there's also INSERT … ON DUPLICATE KEY UPDATE syntax, you can find explanations on dev.mysql.com


Post from bogdan.org.ua according to Google's webcache:

18th October 2007

To start: as of the latest MySQL, syntax presented in the title is not possible. But there are several very easy ways to accomplish what is expected using existing functionality.

There are 3 possible solutions: using INSERT IGNORE, REPLACE, or INSERT … ON DUPLICATE KEY UPDATE.

Imagine we have a table:

CREATE TABLE `transcripts` (
`ensembl_transcript_id` varchar(20) NOT NULL,
`transcript_chrom_start` int(10) unsigned NOT NULL,
`transcript_chrom_end` int(10) unsigned NOT NULL,
PRIMARY KEY (`ensembl_transcript_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Now imagine that we have an automatic pipeline importing transcripts meta-data from Ensembl, and that due to various reasons the pipeline might be broken at any step of execution. Thus, we need to ensure two things:

  1. repeated executions of the pipeline will not destroy our database

  2. repeated executions will not die due to ‘duplicate primary key’ errors.

Method 1: using REPLACE

It’s very simple:

REPLACE INTO `transcripts`
SET `ensembl_transcript_id` = 'ENSORGT00000000001',
`transcript_chrom_start` = 12345,
`transcript_chrom_end` = 12678;

If the record exists, it will be overwritten; if it does not yet exist, it will be created. However, using this method isn’t efficient for our case: we do not need to overwrite existing records, it’s fine just to skip them.

Method 2: using INSERT IGNORE Also very simple:

INSERT IGNORE INTO `transcripts`
SET `ensembl_transcript_id` = 'ENSORGT00000000001',
`transcript_chrom_start` = 12345,
`transcript_chrom_end` = 12678;

Here, if the ‘ensembl_transcript_id’ is already present in the database, it will be silently skipped (ignored). (To be more precise, here’s a quote from MySQL reference manual: “If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted.”.) If the record doesn’t yet exist, it will be created.

This second method has several potential weaknesses, including non-abortion of the query in case any other problem occurs (see the manual). Thus it should be used if previously tested without the IGNORE keyword.

Method 3: using INSERT … ON DUPLICATE KEY UPDATE:

Third option is to use INSERT … ON DUPLICATE KEY UPDATE syntax, and in the UPDATE part just do nothing do some meaningless (empty) operation, like calculating 0+0 (Geoffray suggests doing the id=id assignment for the MySQL optimization engine to ignore this operation). Advantage of this method is that it only ignores duplicate key events, and still aborts on other errors.

As a final notice: this post was inspired by Xaprb. I’d also advise to consult his other post on writing flexible SQL queries.

How do I change the value of a global variable inside of a function

Just reference the variable inside the function; no magic, just use it's name. If it's been created globally, then you'll be updating the global variable.

You can override this behaviour by declaring it locally using var, but if you don't use var, then a variable name used in a function will be global if that variable has been declared globally.

That's why it's considered best practice to always declare your variables explicitly with var. Because if you forget it, you can start messing with globals by accident. It's an easy mistake to make. But in your case, this turn around and becomes an easy answer to your question.

How to paste text to end of every line? Sublime 2

  1. Select all the lines on which you want to add prefix or suffix. (But if you want to add prefix or suffix to only specific lines, you can use ctrl+Left mouse button to create multiple cursors.)
  2. Push Ctrl+Shift+L.
  3. Push Home key and add prefix.
  4. Push End key and add suffix.

Note, disable wordwrap, otherwise it will not work properly if your lines are longer than sublime's width.

Android OnClickListener - identify a button

The best way is by switch-ing between v.getId(). Having separate anonymous OnClickListener for each Button is taking up more memory. Casting View to Button is unnecessary. Using if-else when switch is possible is slower and harder to read. In Android's source you can often notice comparing the references by if-else:

if (b1 == v) {
 // ...
} else if (b2 == v) {

I don't know exactly why they chose this way, but it works too.

How to to send mail using gmail in Laravel?

first login to your gmail account and under My account > Sign In And Security > Sign In to google, enable two step verification, then you can generate app password, and you can use that app password in .env file.

Your .env file will then look something like this

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=apppassword
MAIL_ENCRYPTION=tls

Don't forget to run php artisan config:cache after you make changes in your .env file.

Using client certificate in Curl command

This is how I did it:

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

How to clear radio button in Javascript?

If you have a radio button with same id, then you can clear the selection

Radio Button definition :

<input type="radio" name="paymentType" id="paymentType" value="CASH" /> CASH
<input type="radio" name="paymentType" id="paymentType" value="CHEQUE" /> CHEQUE
<input type="radio" name="paymentType" id="paymentType" value="DD" /> DD

Clearing all values of radio button:

document.formName.paymentType[0].checked = false;
document.formName.paymentType[1].checked = false;
document.formName.paymentType[2].checked = false;
...

How to see tomcat is running or not

open your browser,check whether Tomcat homepage is visible by below command.

http://ipaddress:portnumber

also check this

What is the purpose of Looper and how to use it?

Looper allows tasks to be executed sequentially on a single thread. And handler defines those tasks that we need to be executed. It is a typical scenario that I am trying to illustrate in this example:

class SampleLooper extends Thread {
@Override
public void run() {
  try {
    // preparing a looper on current thread     
    // the current thread is being detected implicitly
    Looper.prepare();

    // now, the handler will automatically bind to the
    // Looper that is attached to the current thread
    // You don't need to specify the Looper explicitly
    handler = new Handler();

    // After the following line the thread will start
    // running the message loop and will not normally
    // exit the loop unless a problem happens or you
    // quit() the looper (see below)
    Looper.loop();
  } catch (Throwable t) {
    Log.e(TAG, "halted due to an error", t);
  } 
}
}

Now we can use the handler in some other threads(say ui thread) to post the task on Looper to execute.

handler.post(new Runnable()
{
public void run() {
//This will be executed on thread using Looper.
    }
});

On UI thread we have an implicit Looper that allow us to handle the messages on ui thread.

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

How to re-sign the ipa file?

Try this app http://www.ketzler.de/2011/01/resign-an-iphone-app-insert-new-bundle-id-and-send-to-xcode-organizer-for-upload/

It supposed to help you resign the IPA file. I tried it myself but couldn't get pass an error with Entitlements.plist. Could just be a problem with my project. You should give it a try.

compareTo with primitives -> Integer / int

May I propose a third

((Integer) a).compareTo(b)  

Set min-width in HTML table's <td>

Try using an invisible element (or psuedoelement) to force the table-cell to expand.

td:before {
  content: '';
  display: block; 
  width: 5em;
}

JSFiddle: https://jsfiddle.net/cibulka/gf45uxr6/1/

How can I convert an Int to a CString?

If you want something more similar to your example try _itot_s. On Microsoft compilers _itot_s points to _itoa_s or _itow_s depending on your Unicode setting:

CString str;
_itot_s( 15, str.GetBufferSetLength( 40 ), 40, 10 );
str.ReleaseBuffer();

it should be slightly faster since it doesn't need to parse an input format.

Visually managing MongoDB documents and collections

I use MongoVUE, it's good for viewing data, but there is almost no editing abilities.

Is there a kind of Firebug or JavaScript console debug for Android?

I also looked for a simple console replacement, just to dump text. So what I did was this function:

function remoteLog (arg) {
    var file = '/files/remoteLog.php';
    $.post(file, {text: arg});
}

The remote PHP file recorded all the output to a database in arg. It took me 5 minutes (OK, on the server side I used a simple logging library that records and displays text messages, but still...).

Get each line from textarea

Old tread...? Well, someone may bump into this...

Please check out http://telamenta.com/techarticle/php-explode-newlines-and-you

Rather than using:

$values = explode("\n", $value_string);

Use a safer method like:

$values = preg_split('/[\n\r]+/', $value_string);

String to HashMap JAVA

In one line :

HashMap<String, Integer> map = (HashMap<String, Integer>) Arrays.asList(str.split(",")).stream().map(s -> s.split(":")).collect(Collectors.toMap(e -> e[0], e -> Integer.parseInt(e[1])));

Details:

1) Split entry pairs and convert string array to List<String> in order to use java.lang.Collection.Stream API from Java 1.8

Arrays.asList(str.split(","))

2) Map the resulting string list "key:value" to a string array with [0] as key and [1] as value

map(s -> s.split(":"))

3) Use collect terminal method from stream API to mutate

collect(Collector<? super String, Object, Map<Object, Object>> collector)

4) Use the Collectors.toMap() static method which take two Function to perform mutation from input type to key and value type.

toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper)

where T is the input type, K the key type and U the value type.

5) Following lambda mutate String to String key and String to Integer value

toMap(e -> e[0], e -> Integer.parseInt(e[1]))



Enjoy the stream and lambda style with Java 8. No more loops !

How to set default value for form field in Symfony2?

Can be use during the creation easily with :

->add('myfield', 'text', array(
     'label' => 'Field',
     'empty_data' => 'Default value'
))

Why can't I push to this bare repository?

I use SourceTree git client, and I see that their initial commit/push command is:

git -c diff.mnemonicprefix=false -c core.quotepath=false push -v --tags --set-upstream origin master:master

What is the canonical way to check for errors using the CUDA runtime API?

Probably the best way to check for errors in runtime API code is to define an assert style handler function and wrapper macro like this:

#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
   if (code != cudaSuccess) 
   {
      fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
      if (abort) exit(code);
   }
}

You can then wrap each API call with the gpuErrchk macro, which will process the return status of the API call it wraps, for example:

gpuErrchk( cudaMalloc(&a_d, size*sizeof(int)) );

If there is an error in a call, a textual message describing the error and the file and line in your code where the error occurred will be emitted to stderr and the application will exit. You could conceivably modify gpuAssert to raise an exception rather than call exit() in a more sophisticated application if it were required.

A second related question is how to check for errors in kernel launches, which can't be directly wrapped in a macro call like standard runtime API calls. For kernels, something like this:

kernel<<<1,1>>>(a);
gpuErrchk( cudaPeekAtLastError() );
gpuErrchk( cudaDeviceSynchronize() );

will firstly check for invalid launch argument, then force the host to wait until the kernel stops and checks for an execution error. The synchronisation can be eliminated if you have a subsequent blocking API call like this:

kernel<<<1,1>>>(a_d);
gpuErrchk( cudaPeekAtLastError() );
gpuErrchk( cudaMemcpy(a_h, a_d, size * sizeof(int), cudaMemcpyDeviceToHost) );

in which case the cudaMemcpy call can return either errors which occurred during the kernel execution or those from the memory copy itself. This can be confusing for the beginner, and I would recommend using explicit synchronisation after a kernel launch during debugging to make it easier to understand where problems might be arising.

Note that when using CUDA Dynamic Parallelism, a very similar methodology can and should be applied to any usage of the CUDA runtime API in device kernels, as well as after any device kernel launches:

#include <assert.h>
#define cdpErrchk(ans) { cdpAssert((ans), __FILE__, __LINE__); }
__device__ void cdpAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
   if (code != cudaSuccess)
   {
      printf("GPU kernel assert: %s %s %d\n", cudaGetErrorString(code), file, line);
      if (abort) assert(0);
   }
}

Lombok annotations do not compile under Intellij idea

In order to solve the problem set:

  • Preferences (Ctrl + Alt + S)
    • Build, Execution, Deployment
      • Compiler
        • Annotation Processors
          • Enable annotation processing

Make sure you have the Lombok plugin for IntelliJ installed!

  • Preferences -> Plugins
  • Search for "Lombok Plugin"
  • Click Browse repositories...
  • Choose Lombok Plugin
  • Install
  • Restart IntelliJ

How can I send large messages with Kafka (over 15MB)?

Minor changes required for Kafka 0.10 and the new consumer compared to laughing_man's answer:

  • Broker: No changes, you still need to increase properties message.max.bytes and replica.fetch.max.bytes. message.max.bytes has to be equal or smaller(*) than replica.fetch.max.bytes.
  • Producer: Increase max.request.size to send the larger message.
  • Consumer: Increase max.partition.fetch.bytes to receive larger messages.

(*) Read the comments to learn more about message.max.bytes<=replica.fetch.max.bytes

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

Place components which are created dynamically to entryComponents under @NgModuledecorator function.

@NgModule({
    imports: [
        FormsModule,
        CommonModule,
        DashbaordRoutingModule
    ],
    declarations: [
        MainComponent,
        TestDialog
    ],
    entryComponents: [
        TestDialog
    ]
})

Use Mockito to mock some methods but not others

What you want is org.mockito.Mockito.CALLS_REAL_METHODS according to the docs:

/**
 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
 * <p>
 * {@link Answer} can be used to define the return values of unstubbed invocations.
 * <p>
 * This implementation can be helpful when working with legacy code.
 * When this implementation is used, unstubbed methods will delegate to the real implementation.
 * This is a way to create a partial mock object that calls real methods by default.
 * <p>
 * As usual you are going to read <b>the partial mock warning</b>:
 * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
 * How does partial mock fit into this paradigm? Well, it just doesn't... 
 * Partial mock usually means that the complexity has been moved to a different method on the same object.
 * In most cases, this is not the way you want to design your application.
 * <p>
 * However, there are rare cases when partial mocks come handy: 
 * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
 * However, I wouldn't use partial mocks for new, test-driven & well-designed code.
 * <p>
 * Example:
 * <pre class="code"><code class="java">
 * Foo mock = mock(Foo.class, CALLS_REAL_METHODS);
 *
 * // this calls the real implementation of Foo.getSomething()
 * value = mock.getSomething();
 *
 * when(mock.getSomething()).thenReturn(fakeValue);
 *
 * // now fakeValue is returned
 * value = mock.getSomething();
 * </code></pre>
 */

Thus your code should look like:

import org.junit.Test;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

public class StockTest {

    public class Stock {
        private final double price;
        private final int quantity;

        Stock(double price, int quantity) {
            this.price = price;
            this.quantity = quantity;
        }

        public double getPrice() {
            return price;
        }

        public int getQuantity() {
            return quantity;
        }

        public double getValue() {
            return getPrice() * getQuantity();
        }
    }

    @Test
    public void getValueTest() {
        Stock stock = mock(Stock.class, withSettings().defaultAnswer(CALLS_REAL_METHODS));
        when(stock.getPrice()).thenReturn(100.00);
        when(stock.getQuantity()).thenReturn(200);
        double value = stock.getValue();

        assertEquals("Stock value not correct", 100.00 * 200, value, .00001);
    }
}

The call to Stock stock = mock(Stock.class); calls org.mockito.Mockito.mock(Class<T>) which looks like this:

 public static <T> T mock(Class<T> classToMock) {
    return mock(classToMock, withSettings().defaultAnswer(RETURNS_DEFAULTS));
}

The docs of the value RETURNS_DEFAULTS tell:

/**
 * The default <code>Answer</code> of every mock <b>if</b> the mock was not stubbed.
 * Typically it just returns some empty value. 
 * <p>
 * {@link Answer} can be used to define the return values of unstubbed invocations. 
 * <p>
 * This implementation first tries the global configuration. 
 * If there is no global configuration then it uses {@link ReturnsEmptyValues} (returns zeros, empty collections, nulls, etc.)
 */

How get data from material-ui TextField, DropDownMenu components?

Here's the simplest solution i came up with, we get the value of the input created by material-ui textField :

      create(e) {
        e.preventDefault();
        let name = this.refs.name.input.value;
        alert(name);
      }

      constructor(){
        super();
        this.create = this.create.bind(this);
      }

      render() {
        return (
              <form>
                <TextField ref="name" hintText="" floatingLabelText="Your name" /><br/>
                <RaisedButton label="Create" onClick={this.create} primary={true} />
              </form>
        )}

hope this helps.

Android, How to limit width of TextView (and add three dots at the end of text)?

Add These two lines in your text

android:ellipsize="end"
android:singleLine="true"

Check existence of directory and create if doesn't exist

Here's the simple check, and creates the dir if doesn't exists:

## Provide the dir name(i.e sub dir) that you want to create under main dir:
output_dir <- file.path(main_dir, sub_dir)

if (!dir.exists(output_dir)){
dir.create(output_dir)
} else {
    print("Dir already exists!")
}

What is syntax for selector in CSS for next element?

no > is a child selector.

the one you want is +

so try h1.hc-reform + p

browser support isn't great

How do you create nested dict in Python?

If you want to create a nested dictionary given a list (arbitrary length) for a path and perform a function on an item that may exist at the end of the path, this handy little recursive function is quite helpful:

def ensure_path(data, path, default=None, default_func=lambda x: x):
    """
    Function:

    - Ensures a path exists within a nested dictionary

    Requires:

    - `data`:
        - Type: dict
        - What: A dictionary to check if the path exists
    - `path`:
        - Type: list of strs
        - What: The path to check

    Optional:

    - `default`:
        - Type: any
        - What: The default item to add to a path that does not yet exist
        - Default: None

    - `default_func`:
        - Type: function
        - What: A single input function that takes in the current path item (or default) and adjusts it
        - Default: `lambda x: x` # Returns the value in the dict or the default value if none was present
    """
    if len(path)>1:
        if path[0] not in data:
            data[path[0]]={}
        data[path[0]]=ensure_path(data=data[path[0]], path=path[1:], default=default, default_func=default_func)
    else:
        if path[0] not in data:
            data[path[0]]=default
        data[path[0]]=default_func(data[path[0]])
    return data

Example:

data={'a':{'b':1}}
ensure_path(data=data, path=['a','c'], default=[1])
print(data) #=> {'a':{'b':1, 'c':[1]}}
ensure_path(data=data, path=['a','c'], default=[1], default_func=lambda x:x+[2])
print(data) #=> {'a': {'b': 1, 'c': [1, 2]}}

SQL Stored Procedure set variables using SELECT

One advantage your current approach does have is that it will raise an error if multiple rows are returned by the predicate. To reproduce that you can use.

SELECT @currentTerm = currentterm,
       @termID = termid,
       @endDate = enddate
FROM   table1
WHERE  iscurrent = 1

IF( @@ROWCOUNT <> 1 )
  BEGIN
      RAISERROR ('Unexpected number of matching rows',
                 16,
                 1)

      RETURN
  END  

call javascript function onchange event of dropdown list

You just try this, Its so easy

 <script>

  $("#YourDropDownId").change(function () {
            alert($("#YourDropDownId").val());
        });

</script>

Declare an array in TypeScript

Few ways of declaring a typed array in TypeScript are

const booleans: Array<boolean> = new Array<boolean>();
// OR, JS like type and initialization
const booleans: boolean[] = [];

// or, if you have values to initialize 
const booleans: Array<boolean> = [true, false, true];
// get a vaue from that array normally
const valFalse = booleans[1];

'True' and 'False' in Python

is compares identity. A string will never be identical to a not-string.

== is equality. But a string will never be equal to either True or False.

You want neither.

path = '/bla/bla/bla'

if path:
    print "True"
else:
    print "False"

.Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned

This solved it for me:
https://gist.github.com/beccasaurus/929007/a8f820b153a1cfdee3d06a9c0a1d7ebfced8bb77

TL;DR:
Problem:
localhost returns expected content, remote IP alters 400 content to "Bad Request"
Solution:
Adding <httpErrors existingResponse="PassThrough"></httpErrors> to web.config/configuration/system.webServer solved this for me; now all servers (local & remote) return the exact same content (generated by me) regardless of the IP address and/or HTTP code I return.

iOS Launching Settings -> Restrictions URL Scheme

As of iOS8 you can open the built-in Settings app with:

NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
if ([[UIApplication sharedApplication] canOpenURL:url]) {
   [[UIApplication sharedApplication] openURL:url];
}

The actual URL string is @"app-settings:". I tried appending different sections to the string ("Bluetooth", "GENERAL", etc.) but seems only linking to the main Settings screen works. Post a reply if you find out otherwise.

How to create a DataTable in C# and how to add rows?

Question 1: How do create a DataTable in C#?

Answer 1:

DataTable dt = new DataTable(); // DataTable created

// Add columns in your DataTable
dt.Columns.Add("Name");
dt.Columns.Add("Marks");

Note: There is no need to Clear() the DataTable after creating it.

Question 2: How to add row(s)?

Answer 2: Add one row:

dt.Rows.Add("Ravi","500");

Add multiple rows: use ForEach loop

DataTable dt2 = (DataTable)Session["CartData"]; // This DataTable contains multiple records
foreach (DataRow dr in dt2.Rows)
{
    dt.Rows.Add(dr["Name"], dr["Marks"]);
}

swift 3.0 Data to String?

If your data is base64 encoded.

if ( dataObj != nil ) {
    let encryptedDataText = dataObj!.base64EncodedString(options: NSData.Base64EncodingOptions())
    NSLog("Encrypted with pubkey: %@", encryptedDataText)
}

sed one-liner to convert all uppercase to lowercase?

I like some of the answers here, but there is a sed command that should do the trick on any platform:

sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/'

Anyway, it's easy to understand. And knowing about the y command can come in handy sometimes.

Execute PHP function with onclick

It can be done and with rather simple php if this is your button

<input type="submit" name="submit>

and this is your php code

if(isset($_POST["submit"])) { php code here }

the code get's called when submit get's posted which happens when the button is clicked.

/exclude in xcopy just for a file type

For excluding multiple file types, you can use '+' to concatenate other lists. For example:

xcopy /r /d /i /s /y /exclude:excludedfileslist1.txt+excludedfileslist2.txt C:\dev\apan C:\web\apan

Source: http://www.tech-recipes.com/rx/2682/xcopy_command_using_the_exclude_flag/

What is ADT? (Abstract Data Type)

An abstract data type, sometimes abbreviated ADT, is a logical description of how we view the data and the operations that are allowed without regard to how they will be implemented. This means that we are concerned only with what the data is representing and not with how it will eventually be constructed.

https://runestone.academy/runestone/books/published/pythonds/Introduction/WhyStudyDataStructuresandAbstractDataTypes.html