Programs & Examples On #Ynchronizationontext

SSRS chart does not show all labels on Horizontal axis

It looks as though the horizontal axis (Category Group) labels have very long values - there may not be room to display them all. I suggest changing the labels to have shorter values.

You can set the sort order for the Category Groups in the Category Group Properties - Sorting section - this may have been previously set; if not, I suggest using this to sort as desired.

/usr/bin/codesign failed with exit code 1

I had the same problem. In the end it turned out that my private key did not allow codesign to access it. One can see this in the info dialog in keychain application.

How do I pipe or redirect the output of curl -v?

The answer above didn't work for me, what did eventually was this syntax:

curl https://${URL} &> /dev/stdout | tee -a ${LOG}

tee puts the output on the screen, but also appends it to my log.

How to declare a global variable in C++

You declare the variable as extern in a common header:

//globals.h
extern int x;

And define it in an implementation file.

//globals.cpp
int x = 1337;

You can then include the header everywhere you need access to it.

I suggest you also wrap the variable inside a namespace.

Public class is inaccessible due to its protection level

You could go into the designer of the web form and change the "webcontrols" to be "public" instead of "protected" but I'm not sure how safe that is. I prefer to make hidden inputs and have some jQuery set the values into those hidden inputs, then create public properties in the web form's class (code behind), and access the values that way.

Create a <ul> and fill it based on a passed array

What are disadvantages of the following solution? Seems to be faster and shorter.

var options = {
    set0: ['Option 1','Option 2'],
    set1: ['First Option','Second Option','Third Option']
};

var list = "<li>" + options.set0.join("</li><li>") + "</li>";
document.getElementById("list").innerHTML = list;

if, elif, else statement issues in Bash

Missing space between elif and [ rest your program is correct. you need to correct it an check it out. here is fixed program:

#!/bin/bash

if [ "$seconds" -eq 0 ]; then
   timezone_string="Z"
elif [ "$seconds" -gt 0 ]; then
   timezone_string=$(printf "%02d:%02d" $((seconds/3600)) $(((seconds / 60) % 60)))
else
   echo "Unknown parameter"
fi

useful link related to this bash if else statement

Assign output to variable in Bash

In shell, you don't put a $ in front of a variable you're assigning. You only use $IP when you're referring to the variable.

#!/bin/bash

IP=$(curl automation.whatismyip.com/n09230945.asp)

echo "$IP"

sed "s/IP/$IP/" nsupdate.txt | nsupdate

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

Look at your actual html code and check that the weird symbols are not originating there. This issue came up when I started coding in Notepad++ halfway after coding in Notepad. It seems to me that the older version of Notepad I was using may have used different encoding to Notepad's++ UTF-8 encoding. After I transferred my code from Notepad to Notepad++, the apostrophes got replaced with weird symbols, so I simply had to remove the symbols from my Notepad++ code.

Loading DLLs at runtime in C#

Members must be resolvable at compile time to be called directly from C#. Otherwise you must use reflection or dynamic objects.

Reflection

namespace ConsoleApplication1
{
    using System;
    using System.Reflection;

    class Program
    {
        static void Main(string[] args)
        {
            var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");

            foreach(Type type in DLL.GetExportedTypes())
            {
                var c = Activator.CreateInstance(type);
                type.InvokeMember("Output", BindingFlags.InvokeMethod, null, c, new object[] {@"Hello"});
            }

            Console.ReadLine();
        }
    }
}

Dynamic (.NET 4.0)

namespace ConsoleApplication1
{
    using System;
    using System.Reflection;

    class Program
    {
        static void Main(string[] args)
        {
            var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");

            foreach(Type type in DLL.GetExportedTypes())
            {
                dynamic c = Activator.CreateInstance(type);
                c.Output(@"Hello");
            }

            Console.ReadLine();
        }
    }
}

Creating a JavaScript cookie on a domain and reading it across sub domains

You can also use the Cookies API and do:

browser.cookies.set({
  url: 'example.com',
  name: 'HelloWorld',
  value: 'HelloWorld',
  expirationDate: myDate
}

MDN Set() Method Documentation

How to check if a character in a string is a digit or letter

import java.util.*;

public class String_char 
{

    public static void main(String arg[]){   

        Scanner in = new Scanner(System.in);
        System.out.println("Enter the value");
        String data;
        data = in.next();

        int len = data.length();
        for (int i = 0 ; i < len ; i++){
            char ch = data.charAt(i);

            if ((ch >= '0' && ch <= '9')){
                System.out.println("Number ");
            }
            else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
            System.out.println("Character");
            }
            else{
                System.out.println("Symbol");
             }
        }
    } 
}

JQuery .hasClass for multiple values in an if statement

For anyone wondering about some of the different performance aspects with all of these different options, I've created a jsperf case here: jsperf

In short, using element.hasClass('class') is the fastest.

Next best bet is using elem.hasClass('classA') || elem.hasClass('classB'). A note on this one: order matters! If the class 'classA' is more likely to be found, list it first! OR condition statements return as soon as one of them is met.

The worst performance by far was using element.is('.class').

Also listed in the jsperf is CyberMonk's function, and Kolja's solution.

How to clear jQuery validation error messages?

If you want to reset numberOfInvalids() as well then add following line in resetForm function in jquery.validate.js file line number: 415.

this.invalid = {};

Django DoesNotExist

I have found the solution to this issue using ObjectDoesNotExist on this way

from django.core.exceptions import ObjectDoesNotExist
......

try:
  # try something
except ObjectDoesNotExist:
  # do something

After this, my code works as I need

Thanks any way, your post help me to solve my issue

how to delete the content of text file without deleting itself

You want the setLength() method in the class RandomAccessFile.

SyntaxError: multiple statements found while compiling a single statement

A (partial) practical work-around is to put things into a throw-away function.

Pasting

x = 1
x += 1
print(x)

results in

>>> x = 1
x += 1
print(x)
  File "<stdin>", line 1
    x += 1
print(x)

    ^
SyntaxError: multiple statements found while compiling a single statement
>>>

However, pasting

def abc():
  x = 1
  x += 1
  print(x)

works:

>>> def abc():
  x = 1
  x += 1
  print(x)
>>> abc()
2
>>>

Of course, this is OK for a quick one-off, won't work for everything you might want to do, etc. But then, going to ipython / jupyter qtconsole is probably the next simplest option.

VB.NET: how to prevent user input in a ComboBox

Even if the question is marked answered, I would like to add some points to it.

Set the DropDownStyle property of the combobox to DropDownList works for sure.

BUT what if the drop down list is longer, the user will have to scroll it to the desired item as he has no access to keyboard.

 Private Sub cbostate_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles cbostate.Validating
    If cbostate.SelectedValue Is Nothing AndAlso cbostate.Text <> String.Empty Then
        e.Cancel = True
        MsgBox("Invalid State")
    End If
End Sub

I did it like this. I wanted to restrict the user entering 'random values' instead of 'state' but keeping he should be able to type and search states.

This validating event occurs when the control loses focus. So if user enters wrong value in combobox, It will not allow user to do anything on the form, perhaps it will not even allow to change the focus from the combobox

Delete files older than 15 days using PowerShell

$limit = (Get-Date).AddDays(-15)
$path = "C:\Some\Path"

# Delete files older than the $limit.
Get-ChildItem -Path $path -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force -Recurse

This will delete old folders and it content.

Removing the password from a VBA project

This has a simple method using SendKeys to unprotect the VBA project. This would get you into the project, so you'd have to continue on using SendKeys to figure out a way to remove the password protection: http://www.pcreview.co.uk/forums/thread-989191.php

And here's one that uses a more advanced, somewhat more reliable method for unprotecting. Again, it will only unlock the VB project for you. http://www.ozgrid.com/forum/showthread.php?t=13006&page=2

I haven't tried either method, but this may save you some time if it's what you need to do...

Parsing XML with namespace in Python via 'ElementTree'

ElementTree is not too smart about namespaces. You need to give the .find(), findall() and iterfind() methods an explicit namespace dictionary. This is not documented very well:

namespaces = {'owl': 'http://www.w3.org/2002/07/owl#'} # add more as needed

root.findall('owl:Class', namespaces)

Prefixes are only looked up in the namespaces parameter you pass in. This means you can use any namespace prefix you like; the API splits off the owl: part, looks up the corresponding namespace URL in the namespaces dictionary, then changes the search to look for the XPath expression {http://www.w3.org/2002/07/owl}Class instead. You can use the same syntax yourself too of course:

root.findall('{http://www.w3.org/2002/07/owl#}Class')

If you can switch to the lxml library things are better; that library supports the same ElementTree API, but collects namespaces for you in a .nsmap attribute on elements.

PHP - Move a file into a different folder on the server

use copy() and unlink() function

$moveFile="path/filename";
if (copy($csvFile,$moveFile)) 
{
  unlink($csvFile);
}

How do you send an HTTP Get Web Request in Python?

You can use urllib2

import urllib2
content = urllib2.urlopen(some_url).read()
print content

Also you can use httplib

import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK

or the requests library

import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200

Call external javascript functions from java code

try {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        System.out.println("okay1");
        FileInputStream fileInputStream = new FileInputStream("C:/Users/Kushan/eclipse-workspace/sureson.lk/src/main/webapp/js/back_end_response.js");
        System.out.println("okay2");
        if (fileInputStream != null){
         BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
         engine.eval(reader);
         System.out.println("okay3");
        // Invocable javascriptEngine = null;
         System.out.println("okay4");
        Invocable invocableEngine = (Invocable)engine;
         System.out.println("okay5");
         int x=0;
         System.out.println("invocableEngine is : "+invocableEngine);
         Object object = invocableEngine.invokeFunction("backend_message",x);

         System.out.println("okay6");
        }
        }catch(Exception e) {
            System.out.println("erroe when calling js function"+ e);
        }

python convert list to dictionary

I'd go for recursions:

l = ['a', 'b', 'c', 'd', 'e', ' ']
d = dict([(k, v) for k,v in zip (l[::2], l[1::2])])

Fade Effect on Link Hover?

You can do this with JQueryUI:

$('a').mouseenter(function(){
  $(this).animate({
    color: '#ff0000'
  }, 1000);
}).mouseout(function(){
  $(this).animate({
    color: '#000000'
  }, 1000);
});

http://jsfiddle.net/dWCbk/

What exactly does an #if 0 ..... #endif block do?

It is a cheap way to comment out, but I suspect that it could have debugging potential. For example, let's suppose you have a build that output values to a file. You might not want that in a final version so you can use the #if 0... #endif.

Also, I suspect a better way of doing it for debug purpose would be to do:

#ifdef DEBUG
// output to file
#endif

You can do something like that and it might make more sense and all you have to do is define DEBUG to see the results.

Determining the current foreground application from a background task or service

Try the following code:

ActivityManager activityManager = (ActivityManager) newContext.getSystemService( Context.ACTIVITY_SERVICE );
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
for(RunningAppProcessInfo appProcess : appProcesses){
    if(appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
        Log.i("Foreground App", appProcess.processName);
    }
}

Process name is the package name of the app running in foreground. Compare it to the package name of your application. If it is the same then your application is running on foreground.

I hope this answers your question.

Returning unique_ptr from functions

unique_ptr doesn't have the traditional copy constructor. Instead it has a "move constructor" that uses rvalue references:

unique_ptr::unique_ptr(unique_ptr && src);

An rvalue reference (the double ampersand) will only bind to an rvalue. That's why you get an error when you try to pass an lvalue unique_ptr to a function. On the other hand, a value that is returned from a function is treated as an rvalue, so the move constructor is called automatically.

By the way, this will work correctly:

bar(unique_ptr<int>(new int(44));

The temporary unique_ptr here is an rvalue.

How to kill/stop a long SQL query immediately?

What could the reason be

A query cancel is immediate, provided that your attention can reach the server and be processed. A query must be in a cancelable state, which is almost always true except if you do certain operations like calling a web service from SQLCLR. If your attention cannot reach the server it's usually due to scheduler overload.

But if your query is part of a transaction that must rollback, then rollback cannot be interrupted. If it takes 10 minutes then it needs 10 minutes and there's nothing you can do about it. Even restarting the server will not help, it will only make startup longer since recovery must finish the rollback.

To answer which specific reason applies to your case, you'll need to investigate yourself.

How to analyze a JMeter summary report?

Sample: Number of requests sent.

The Throughput: is the number of requests per unit of time (seconds, minutes, hours) that are sent to your server during the test.

The Response time: is the elapsed time from the moment when a given request is sent to the server until the moment when the last bit of information has returned to the client.

The throughput is the real load processed by your server during a run but it does not tell you anything about the performance of your server during this same run. This is the reason why you need both measures in order to get a real idea about your server’s performance during a run. The response time tells you how fast your server is handling a given load.

Average: This is the Average (Arithmetic mean µ = 1/n * Si=1…n xi) Response time of your total samples.

Min and Max are the minimum and maximum response time.

An important thing to understand is that the mean value can be very misleading as it does not show you how close (or far) your values are from the average.For this purpose, we need the Deviation value since Average value can be the Same for different response time of the samples!!

Deviation: The standard deviation (s) measures the mean distance of the values to their average (µ).It gives you a good idea of the dispersion or variability of the measures to their mean value.

The following equation show how the standard deviation (s) is calculated:

s = 1/n * v Si=1…n (xi-µ)2

For Details, see here!!

So, if the deviation value is low compared to the mean value, it will indicate you that your measures are not dispersed (or mostly close to the mean value) and that the mean value is significant.

Kb/sec: The throughput measured in Kilobytes per second.

Error % : Percent of requests with errors.

An example is always better to understand!!! I think, this article will help you.

jQuery checkbox event handling

There are several useful answers, but none seem to cover all the latest options. To that end all my examples also cater for the presence of matching label elements and also allow you to dynamically add checkboxes and see the results in a side-panel (by redirecting console.log).

  • Listening for click events on checkboxes is not a good idea as that will not allow for keyboard toggling or for changes made where a matching label element was clicked. Always listen for the change event.

  • Use the jQuery :checkbox pseudo-selector, rather than input[type=checkbox]. :checkbox is shorter and more readable.

  • Use is() with the jQuery :checked pseudo-selector to test for whether a checkbox is checked. This is guaranteed to work across all browsers.

Basic event handler attached to existing elements:

$('#myform :checkbox').change(function () {
    if ($(this).is(':checked')) {
        console.log($(this).val() + ' is now checked');
    } else {
        console.log($(this).val() + ' is now unchecked');
    }
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/2/

Notes:

  • Uses the :checkbox selector, which is preferable to using input[type=checkbox]
  • This connects only to matching elements that exist at the time the event was registered.

Delegated event handler attached to ancestor element:

Delegated event handlers are designed for situations where the elements may not yet exist (dynamically loaded or created) and is very useful. They delegate responsibility to an ancestor element (hence the term).

$('#myform').on('change', ':checkbox', function () {
    if ($(this).is(':checked')) {
        console.log($(this).val() + ' is now checked');
    } else {
        console.log($(this).val() + ' is now unchecked');
    }
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/4/

Notes:

  • This works by listening for events (in this case change) to bubble up to a non-changing ancestor element (in this case #myform).
  • It then applies the jQuery selector (':checkbox' in this case) to only the elements in the bubble chain.
  • It then applies the event handler function to only those matching elements that caused the event.
  • Use document as the default to connect the delegated event handler, if nothing else is closer/convenient.
  • Do not use body to attach delegated events as it has a bug (to do with styling) that can stop it getting mouse events.

The upshot of delegated handlers is that the matching elements only need to exist at event time and not when the event handler was registered. This allows for dynamically added content to generate the events.

Q: Is it slower?

A: So long as the events are at user-interaction speeds, you do not need to worry about the negligible difference in speed between a delegated event handler and a directly connected handler. The benefits of delegation far outweigh any minor downside. Delegated event handlers are actually faster to register as they typically connect to a single matching element.


Why doesn't prop('checked', true) fire the change event?

This is actually by design. If it did fire the event you would easily get into a situation of endless updates. Instead, after changing the checked property, send a change event to the same element using trigger (not triggerHandler):

e.g. without trigger no event occurs

$cb.prop('checked', !$cb.prop('checked'));

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/5/

e.g. with trigger the normal change event is caught

$cb.prop('checked', !$cb.prop('checked')).trigger('change');

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/6/

Notes:

  • Do not use triggerHandler as was suggested by one user, as it will not bubble events to a delegated event handler.

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/8/

although it will work for an event handler directly connected to the element:

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/9/

Events triggered with .triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.

Reference: http://api.jquery.com/triggerhandler/

If anyone has additional features they feel are not covered by this, please do suggest additions.

What are C++ functors and their uses?

Like others have mentioned, a functor is an object that acts like a function, i.e. it overloads the function call operator.

Functors are commonly used in STL algorithms. They are useful because they can hold state before and between function calls, like a closure in functional languages. For example, you could define a MultiplyBy functor that multiplies its argument by a specified amount:

class MultiplyBy {
private:
    int factor;

public:
    MultiplyBy(int x) : factor(x) {
    }

    int operator () (int other) const {
        return factor * other;
    }
};

Then you could pass a MultiplyBy object to an algorithm like std::transform:

int array[5] = {1, 2, 3, 4, 5};
std::transform(array, array + 5, array, MultiplyBy(3));
// Now, array is {3, 6, 9, 12, 15}

Another advantage of a functor over a pointer to a function is that the call can be inlined in more cases. If you passed a function pointer to transform, unless that call got inlined and the compiler knows that you always pass the same function to it, it can't inline the call through the pointer.

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

Upgrading to latest gradle plugin solve my problem :

classpath 'com.android.tools.build:gradle:0.13.+'

Sql Server string to date conversion

dateadd(day,0,'10/15/2008 10:06:32 PM')

Convert Year/Month/Day to Day of Year in Python

You could use strftime with a %j format string:

>>> import datetime
>>> today = datetime.datetime.now()
>>> today.strftime('%j')
'065'

but if you wish to do comparisons or calculations with this number, you would have to convert it to int() because strftime() returns a string. If that is the case, you are better off using DzinX's answer.

How to pass an array into a SQL Server stored procedure

Based on my experience, by creating a delimited expression from the employeeIDs, there is a tricky and nice solution for this problem. You should only create an string expression like ';123;434;365;' in-which 123, 434 and 365 are some employeeIDs. By calling the below procedure and passing this expression to it, you can fetch your desired records. Easily you can join the "another table" into this query. This solution is suitable in all versions of SQL server. Also, in comparison with using table variable or temp table, it is very faster and optimized solution.

CREATE PROCEDURE dbo.DoSomethingOnSomeEmployees  @List AS varchar(max)
AS
BEGIN
  SELECT EmployeeID 
  FROM EmployeesTable
  -- inner join AnotherTable on ...
  where @List like '%;'+cast(employeeID as varchar(20))+';%'
END
GO

How to compare two double values in Java?

Instead of using doubles for decimal arithemetic, please use java.math.BigDecimal. It would produce the expected results.

For reference take a look at this stackoverflow question

Can I change the scroll speed using css or jQuery?

Just use this js file. (I mentioned 2 examples with different js files. hope the second one is what you need) You can simply change the scroll amount, speed etc by changing the parameters.

https://github.com/nathco/jQuery.scrollSpeed

Here's a Demo

You can also try this. Here's a demo

how to implement regions/code collapse in javascript

On VS 2012 and VS 2015 install WebEssentials plugin and you will able to do so.

http://vswebessentials.com/features/javascript

Multiple github accounts on the same computer?

If you have created or cloned another repository and you were not able to pull from origin or upstream adding the ssh key at that directory using the following command worked.

This is the error I was getting here:

Warning: Permanently added the RSA host key for IP address '61:fd9b::8c52:7203' to the list of known hosts.
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I used the following command, this works:

ssh-add ~/.ssh/id_rsa_YOUR_COMPANY_NAME

Python Pandas : group by in group by and average?

I would simply do this, which literally follows what your desired logic was:

df.groupby(['org']).mean().groupby(['cluster']).mean()

How do I handle newlines in JSON?

You could just escape your string on the server when writing the value of the JSON field and unescape it when retrieving the value in the client browser, for instance.

The JavaScript implementation of all major browsers have the unescape command.

Example:

On the server:

response.write "{""field1"":""" & escape(RS_Temp("textField")) & """}"

In the browser:

document.getElementById("text1").value = unescape(jsonObject.field1)

How to get anchor text/href on click using jQuery?

Updated code

$('a','div.res').click(function(){
  var currentAnchor = $(this);
  alert(currentAnchor.text());
  alert(currentAnchor.attr('href'));
});

When should iteritems() be used instead of items()?

As the dictionary documentation for python 2 and python 3 would tell you, in python 2 items returns a list, while iteritems returns a iterator.

In python 3, items returns a view, which is pretty much the same as an iterator.

If you are using python 2, you may want to user iteritems if you are dealing with large dictionaries and all you want to do is iterate over the items (not necessarily copy them to a list)

When to catch java.lang.Error?

It might be appropriate to catch error within unit tests that check an assertion is made. If someone disables assertions or otherwise deletes the assertion you would want to know

Github "Updates were rejected because the remote contains work that you do not have locally."

You may refer to: How to deal with "refusing to merge unrelated histories" error:

$ git pull --allow-unrelated-histories
$ git push -f origin master

How do I make an http request using cookies on Android?

I do not work with google android but I think you'll find it's not that hard to get this working. If you read the relevant bit of the java tutorial you'll see that a registered cookiehandler gets callbacks from the HTTP code.

So if there is no default (have you checked if CookieHandler.getDefault() really is null?) then you can simply extend CookieHandler, implement put/get and make it work pretty much automatically. Be sure to consider concurrent access and the like if you go that route.

edit: Obviously you'd have to set an instance of your custom implementation as the default handler through CookieHandler.setDefault() to receive the callbacks. Forgot to mention that.

Array to Hash Ruby

All answers assume the starting array is unique. OP did not specify how to handle arrays with duplicate entries, which result in duplicate keys.

Let's look at:

a = ["item 1", "item 2", "item 3", "item 4", "item 1", "item 5"]

You will lose the item 1 => item 2 pair as it is overridden bij item 1 => item 5:

Hash[*a]
=> {"item 1"=>"item 5", "item 3"=>"item 4"}

All of the methods, including the reduce(&:merge!) result in the same removal.

It could be that this is exactly what you expect, though. But in other cases, you probably want to get a result with an Array for value instead:

{"item 1"=>["item 2", "item 5"], "item 3"=>["item 4"]}

The naïve way would be to create a helper variable, a hash that has a default value, and then fill that in a loop:

result = Hash.new {|hash, k| hash[k] = [] } # Hash.new with block defines unique defaults.
a.each_slice(2) {|k,v| result[k] << v }
a
=> {"item 1"=>["item 2", "item 5"], "item 3"=>["item 4"]}

It might be possible to use assoc and reduce to do above in one line, but that becomes much harder to reason about and read.

Assigning default value while creating migration file

Yes, I couldn't see how to use 'default' in the migration generator command either but was able to specify a default value for a new string column as follows by amending the generated migration file before applying "rake db:migrate":

class AddColumnToWidgets < ActiveRecord::Migration
  def change
    add_column :widgets, :colour, :string, default: 'red'
  end
end

This adds a new column called 'colour' to my 'Widget' model and sets the default 'colour' of new widgets to 'red'.

Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?

This is more commonly known as a null-coalescing operator. Javascript does not have one.

Count the occurrences of DISTINCT values

SELECT name,COUNT(*) as count 
FROM tablename 
GROUP BY name 
ORDER BY count DESC;

How do I show the changes which have been staged?

For Staging Area vs Repository(last commit) comparison use

 $git diff --staged

The command compares your staged($ git add fileName) changes to your last commit. If you want to see what you’ve staged that will go into your next commit, you can use git diff --staged. This command compares your staged changes to your last commit.

For Working vs Staging comparison use

$ git diff 

The command compares what is in your working directory with what is in your staging area. It’s important to note that git diff by itself doesn’t show all changes made since your last commit — only changes that are still unstaged. If you’ve staged all of your changes($ git add fileName), git diff will give you no output.

Also, if you stage a file($ git add fileName) and then edit it, you can use git diff to see the changes in the file that are staged and the changes that are unstaged.

Error in strings.xml file in Android

You have to put \ before an apostrophe. Like this \' , Also check that you are editing strings.xml and not values.xml (android studio directs you to this file when shows the error). Because if you edit values.xml and try to compile again, the error persists. This was happening to me recently.

Importing json file in TypeScript

Often in Node.js applications a .json is needed. With TypeScript 2.9, --resolveJsonModule allows for importing, extracting types from and generating .json files.

Example #

_x000D_
_x000D_
// tsconfig.json_x000D_
_x000D_
{_x000D_
    "compilerOptions": {_x000D_
        "module": "commonjs",_x000D_
        "resolveJsonModule": true,_x000D_
        "esModuleInterop": true_x000D_
    }_x000D_
}_x000D_
_x000D_
// .ts_x000D_
_x000D_
import settings from "./settings.json";_x000D_
_x000D_
settings.debug === true;  // OK_x000D_
settings.dry === 2;  // Error: Operator '===' cannot be applied boolean and number_x000D_
_x000D_
_x000D_
// settings.json_x000D_
_x000D_
{_x000D_
    "repo": "TypeScript",_x000D_
    "dry": false,_x000D_
    "debug": false_x000D_
}
_x000D_
_x000D_
_x000D_ by: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html

R dplyr: Drop multiple columns

You can try

iris %>% select(-!!drop.cols)

What is char ** in C?

well, char * means a pointer point to char, it is different from char array.

char amessage[] = "this is an array";  /* define an array*/
char *pmessage = "this is a pointer"; /* define a pointer*/

And, char ** means a pointer point to a char pointer.

You can look some books about details about pointer and array.

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

As mentioned above the following would solve the problem: mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

However in my case the provider did this [0..1] or [0..*] serialization rather as a bug and I could not enforce fixing. On the other hand it did not want to impact my strict mapper for all other cases which needs to be validated strictly.

So I did a Jackson NASTY HACK (which should not be copied in general ;-) ), especially because my SingleOrListElement had only few properties to patch:

@JsonProperty(value = "SingleOrListElement", access = JsonProperty.Access.WRITE_ONLY)
private Object singleOrListElement; 

public List<SingleOrListElement> patch(Object singleOrListElement) {
  if (singleOrListElement instanceof List) {
    return (ArrayList<SingleOrListElement>) singleOrListElement;
  } else {
    LinkedHashMap map = (LinkedHashMap) singleOrListElement;
    return Collections.singletonList(SingletonList.builder()
                            .property1((String) map.get("p1"))
                            .property2((Integer) map.get("p2"))
                            .build());
  }

How do I negate a test with regular expressions in a bash script?

You can also put the exclamation mark inside the brackets:

if [[ ! $PATH =~ $temp ]]

but you should anchor your pattern to reduce false positives:

temp=/mnt/silo/bin
pattern="(^|:)${temp}(:|$)"
if [[ ! "${PATH}" =~ ${pattern} ]]

which looks for a match at the beginning or end with a colon before or after it (or both). I recommend using lowercase or mixed case variable names as a habit to reduce the chance of name collisions with shell variables.

Stored procedure or function expects parameter which is not supplied

Your stored procedure expects 5 parameters as input

@userID int, 
@userName varchar(50), 
@password nvarchar(50), 
@emailAddress nvarchar(50), 
@preferenceName varchar(20) 

So you should add all 5 parameters to this SP call:

    cmd.CommandText = "SHOWuser";
    cmd.Parameters.AddWithValue("@userID",userID);
    cmd.Parameters.AddWithValue("@userName", userName);
    cmd.Parameters.AddWithValue("@password", password);
    cmd.Parameters.AddWithValue("@emailAddress", emailAddress);
    cmd.Parameters.AddWithValue("@preferenceName", preferences);
    dbcon.Open();

PS: It's not clear what these parameter are for. You don't use these parameters in your SP body so your SP should looks like:

ALTER PROCEDURE [dbo].[SHOWuser] AS BEGIN ..... END

Is there a “not in” operator in JavaScript for checking object properties?

Two quick possibilities:

if(!('foo' in myObj)) { ... }

or

if(myObj['foo'] === undefined) { ... }

Django template how to look up a dictionary value with a variable

Environment: Django 2.2

  1. Example code:


    from django.template.defaulttags import register

    @register.filter(name='lookup')
    def lookup(value, arg):
        return value.get(arg)

I put this code in a file named template_filters.py in my project folder named portfoliomgr

  1. No matter where you put your filter code, make sure you have __init__.py in that folder

  2. Add that file to libraries section in templates section in your projectfolder/settings.py file. For me, it is portfoliomgr/settings.py



    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
                'libraries':{
                    'template_filters': 'portfoliomgr.template_filters',
                }
            },
        },
    ]

  1. In your html code load the library

    
    {% load template_filters %}
    

The breakpoint will not currently be hit. No symbols have been loaded for this document in a Silverlight application

Whenever I've had this particular error come up, it's turned out that the folder that Visual Studio is loading assemblies from is different from the folder the web-application is running from.

That is, the application server is running the application from

C:\dev\MyApplication\bin 

but Visual studio is debugging from

C:\dev\MyOtherApplication\bin (or something along those lines, anyway).

Note - for various reasons, I do my debugging with IIS as the application host instead of the dinky standalone gizmo that most people use. This could influence the usefulness of my answer!

Update:

For IIS the application server directory (i.e. C:\dev\MyApplication above) is the physical directory configured for the web application - this can be controlled by changing basic settings for the app.

For Visual studio the debugging directory (i.e. C:\dev\MyOtherApplication above) is the directory in which your svc files are found, usually the same directory as your csproj project file.

Why doesn't logcat show anything in my Android?

If you are using a device, the simplest check is to restart eclipse.

** you don't have to shutdown eclipse **

use File > Restart

in a quick second or two you should see your LogCat return

FIND_IN_SET() vs IN()

because the second query is looking for rows with the id's 1 OR 2 OR 3, the first query is looking for a one of the comma delimited values to exist in companyID,

and another problem here is you aren't joining the tables on a common key in your where so you are going to get a mutation of rows that = count(table1) * count(table2);

Your problem really exists with part 2 of my answer. (with your second query)

How to create a folder with name as current date in batch (.bat) files

Use this batch script made by me:

@echo off
title Folder Creator
color b
setlocal enabledelayedexpansion
echo Enter the folder name, you can use these codes:
echo /t - Time (eg. 16:29)
echo /d - Date (eg. 17-02-19)
echo /a - Day (eg. 17)
echo /m - Month (eg. 02)
echo /y - Year (eg. 19)
echo /f - Full Year (eg. 2019)
echo.
set /p foldername=Folder Name:
set foldername=%foldername:/t=!time:~0,5!%
set foldername=%foldername:/d=!date:~0,2!-!date:~3,2!-!date:~8,2!%
set foldername=%foldername:/a=!date:~0,2!%
set foldername=%foldername:/m=!date:~3,2!%
set foldername=%foldername:/y=!date:~8,2!%
set foldername=%foldername:/f=!date:~6,4!%
md %foldername%

For example if you wanted to make a folder named the date in the DD-MM-YY format you would type "/d" but if you wanted to do that in the DD-MM-YYYY format you would type "/a-/m-/f".

How do I set ANDROID_SDK_HOME environment variable?

Copy your SDK path and assign it to the environment variable ANDROID_SDK_ROOT

Refer pic below:

enter image description here

Propagation Delay vs Transmission delay

Transmission Delay : Amount of time required to pump all bits/packets into the electric wire/optic fibre.

Propagation delay : It's the amount of time needed for a packet to reach the destination.

If propagation delay is very high than transmission delay the chance of losing the packet is high.

Add inline style using Javascript

You can try with this

nFilter.style.cssText = 'width:330px;float:left;';

That should do it for you.

How can I wait In Node.js (JavaScript)? l need to pause for a period of time

Update Jan 2021: You can even do it in the Node REPL interactive using --experimental-repl-await flag

$ node --experimental-repl-await
> const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
> await delay(1000) /// waiting 1 second.

A new answer to an old question. Today ( Jan 2017 June 2019) it is much easier. You can use the new async/await syntax. For example:

async function init() {
  console.log(1);
  await sleep(1000);
  console.log(2);
}

function sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}   

For using async/await out of the box without installing and plugins, you have to use node-v7 or node-v8, using the --harmony flag.

Update June 2019: By using the latest versions of NodeJS you can use it out of the box. No need to provide command line arguments. Even Google Chrome support it today.

Update May 2020: Soon you will be able to use the await syntax outside of an async function. In the top level like in this example

await sleep(1000)
function sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
} 

The proposal is in stage 3. You can use it today by using webpack 5 (alpha),

More info:

deleted object would be re-saved by cascade (remove deleted object from associations)

Some how all the above solutions did not worked in hibernate 5.2.10.Final.

But setting the map to null as below worked for me:

playlist.setPlaylistadMaps(null);

Callback after all asynchronous forEach callbacks are completed

var i=0;
const waitFor = (ms) => 
{ 
  new Promise((r) => 
  {
   setTimeout(function () {
   console.log('timeout completed: ',ms,' : ',i); 
     i++;
     if(i==data.length){
      console.log('Done')  
    }
  }, ms); 
 })
}
var data=[1000, 200, 500];
data.forEach((num) => {
  waitFor(num)
})

What are the rules for casting pointers in C?

I suspect you need a more general answer:

There are no rules on casting pointers in C! The language lets you cast any pointer to any other pointer without comment.

But the thing is: There is no data conversion or whatever done! Its solely your own responsibilty that the system does not misinterpret the data after the cast - which would generally be the case, leading to runtime error.

So when casting its totally up to you to take care that if data is used from a casted pointer the data is compatible!

C is optimized for performance, so it lacks runtime reflexivity of pointers/references. But that has a price - you as a programmer have to take better care of what you are doing. You have to know on your self if what you want to do is "legal"

Calling a JavaScript function named in a variable

This is kinda ugly, but its the first thing that popped in my head. This also should allow you to pass in arguments:

eval('var myfunc = ' + variable);  myfunc(args, ...);

If you don't need to pass in arguments this might be simpler.

eval(variable + '();');

Standard dry-code warning applies.

How do I export html table data as .csv file?

Here is a really quick CoffeeScript/jQuery example

csv = []
for row in $('#sometable tr')
  csv.push ("\"#{col.innerText}\"" for col in $(row).find('td,th')).join(',')
output = csv.join("\n")

How to put labels over geom_bar for each bar in R with ggplot2

Try this:

ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
     geom_bar(position = 'dodge', stat='identity') +
     geom_text(aes(label=Number), position=position_dodge(width=0.9), vjust=-0.25)

ggplot output

Reading JSON from a file?

You can use pandas library to read the JSON file.

import pandas as pd
df = pd.read_json('strings.json',lines=True)
print(df)

Installing a local module using npm?

Neither of these approaches (npm link or package.json file dependency) work if the local module has peer dependencies that you only want to install in your project's scope.

For example:

/local/mymodule/package.json:
  "name": "mymodule",
  "peerDependencies":
  {
    "foo": "^2.5"
  }

/dev/myproject/package.json:
  "dependencies":
  {
    "mymodule": "file:/local/mymodule",
    "foo": "^2.5"
  }

In this scenario, npm sets up myproject's node_modules/ like this:

/dev/myproject/node_modules/
  foo/
  mymodule -> /local/mymodule

When node loads mymodule and it does require('foo'), node resolves the mymodule symlink, and then only looks in /local/mymodule/node_modules/ (and its ancestors) for foo, which it doen't find. Instead, we want node to look in /local/myproject/node_modules/, since that's where were running our project from, and where foo is installed.

So, we either need a way to tell node to not resolve this symlink when looking for foo, or we need a way to tell npm to install a copy of mymodule when the file dependency syntax is used in package.json. I haven't found a way to do either, unfortunately :(

CSS text-align: center; is not centering things

You can use flex-grow: 1. The default value is 0 and it will cause the text-align: center looks like left.

https://css-tricks.com/almanac/properties/f/flex-grow/

Label encoding across multiple columns in scikit-learn

It is possible to do this all in pandas directly and is well-suited for a unique ability of the replace method.

First, let's make a dictionary of dictionaries mapping the columns and their values to their new replacement values.

transform_dict = {}
for col in df.columns:
    cats = pd.Categorical(df[col]).categories
    d = {}
    for i, cat in enumerate(cats):
        d[cat] = i
    transform_dict[col] = d

transform_dict
{'location': {'New_York': 0, 'San_Diego': 1},
 'owner': {'Brick': 0, 'Champ': 1, 'Ron': 2, 'Veronica': 3},
 'pets': {'cat': 0, 'dog': 1, 'monkey': 2}}

Since this will always be a one to one mapping, we can invert the inner dictionary to get a mapping of the new values back to the original.

inverse_transform_dict = {}
for col, d in transform_dict.items():
    inverse_transform_dict[col] = {v:k for k, v in d.items()}

inverse_transform_dict
{'location': {0: 'New_York', 1: 'San_Diego'},
 'owner': {0: 'Brick', 1: 'Champ', 2: 'Ron', 3: 'Veronica'},
 'pets': {0: 'cat', 1: 'dog', 2: 'monkey'}}

Now, we can use the unique ability of the replace method to take a nested list of dictionaries and use the outer keys as the columns, and the inner keys as the values we would like to replace.

df.replace(transform_dict)
   location  owner  pets
0         1      1     0
1         0      2     1
2         0      0     0
3         1      1     2
4         1      3     1
5         0      2     1

We can easily go back to the original by again chaining the replace method

df.replace(transform_dict).replace(inverse_transform_dict)
    location     owner    pets
0  San_Diego     Champ     cat
1   New_York       Ron     dog
2   New_York     Brick     cat
3  San_Diego     Champ  monkey
4  San_Diego  Veronica     dog
5   New_York       Ron     dog

How to get a list of installed Jenkins plugins with name and version pair

I wanted a solution that could run on master without any auth requirements and didn't see it here. I made a quick bash script that will pull out all the versions from the plugins dir.

if [ -f $JENKINS_HOME/plugin_versions.txt ]; then
  rm $JENKINS_HOME/plugin_versions.txt
fi

for dir in $JENKINS_HOME/plugins/*/; do
  dir=${dir%*/}
  dir=${dir##*/}
  version=$(grep Plugin-Version $JENKINS_HOME/plugins/$dir/META-INF/MANIFEST.MF | awk -F': ' '{print $2}')
  echo $dir $version >> $JENKINS_HOME/plugin_versions.txt
done

Ways to save enums in database

All my experience tells me that safest way of persisting enums anywhere is to use additional code value or id (some kind of evolution of @jeebee answer). This could be a nice example of an idea:

enum Race {
    HUMAN ("human"),
    ELF ("elf"),
    DWARF ("dwarf");

    private final String code;

    private Race(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }
}

Now you can go with any persistence referencing your enum constants by it's code. Even if you'll decide to change some of constant names, you always can save code value (e.g. DWARF("dwarf") to GNOME("dwarf"))

Ok, dive some more deeper with this conception. Here is some utility method, that helps you find any enum value, but first lets extend our approach.

interface CodeValue {
    String getCode();
}

And let our enum implement it:

enum Race implement CodeValue {...}

This is the time for magic search method:

static <T extends Enum & CodeValue> T resolveByCode(Class<T> enumClass, String code) {
    T[] enumConstants = enumClass.getEnumConstants();
    for (T entry : enumConstants) {
        if (entry.getCode().equals(code)) return entry;
    }
    // In case we failed to find it, return null.
    // I'd recommend you make some log record here to get notified about wrong logic, perhaps.
    return null;
}

And use it like a charm: Race race = resolveByCode(Race.class, "elf")

Copying PostgreSQL database to another server

I struggled quite a lot and eventually the method that allowed me to make it work with Rails 4 was:

on your old server

sudo su - postgres
pg_dump -c --inserts old_db_name > dump.sql

I had to use the postgres linux user to create the dump. also i had to use -c to force the creation of the database on the new server. --inserts tells it to use the INSERT() syntax which otherwise would not work for me :(

then, on the new server, simpy:

sudo su - postgres
psql new_database_name < dump.sql

to transfer the dump.sql file between server I simply used the "cat" to print the content and than "nano" to recreate it copypasting the content.

Also, the ROLE i was using on the two database was different so i had to find-replace all the owner name in the dump.

What's the best way to generate a UML diagram from Python source code?

You may have heard of Pylint that helps statically checking Python code. Few people know that it comes with a tool named Pyreverse that draws UML diagrams from the python code it reads. Pyreverse uses graphviz as a backend.

It is used like this:

pyreverse -o png -p yourpackage .

where the . can also be a single file.

Adding Google Play services version to your app's manifest?

From here

You should be referencing a copy of the library that you copied to your development workspace—you should not reference the library directly from the Android SDK directory.

I faced this error because I referenced the original copy from SDK directory. Make sure that you first copy the library to android workspace and only reference it. In eclipse you can do it by checking "Copy projects into workspace" while importing the project.

What Vim command(s) can be used to quote/unquote words?

If you use the vim plugin https://github.com/tpope/vim-surround (or use VSCode Vim plugin, which comes with vim-surround pre-installed), its pretty convinient!

add

ysiw' // surround in word `'`

drop

ds' // drop surround `'`

change

cs'" // change surround from `'` to `"`

It even works for html tags!

cst<em> // change surround from current tag to `<em>`

check out the readme on github for better examples

How to get a resource id with a known resource name?

I would suggest you using my method to get a resource ID. It's Much more efficient, than using getIdentidier() method, which is slow.

Here's the code:

/**
 * @author Lonkly
 * @param variableName - name of drawable, e.g R.drawable.<b>image</b>
 * @param ? - class of resource, e.g R.drawable.class or R.raw.class
 * @return integer id of resource
 */
public static int getResId(String variableName, Class<?> ?) {

    Field field = null;
    int resId = 0;
    try {
        field = ?.getField(variableName);
        try {
            resId = field.getInt(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return resId;

}

Changing variable names with Python for loops

You probably want a dict instead of separate variables. For example

d = {}
for i in range(3):
    d["group" + str(i)] = self.getGroup(selected, header+i)

If you insist on actually modifying local variables, you could use the locals function:

for i in range(3):
    locals()["group"+str(i)] = self.getGroup(selected, header+i)

On the other hand, if what you actually want is to modify instance variables of the class you're in, then you can use the setattr function

for i in group(3):
    setattr(self, "group"+str(i), self.getGroup(selected, header+i)

And of course, I'm assuming with all of these examples that you don't just want a list:

groups = [self.getGroup(i,header+i) for i in range(3)]

java.util.zip.ZipException: error in opening zip file

In my case SL4j-api.jar with multiple versions are conflicting in the maven repo. Than I deleted the entire SL4j-api folder in m2 maven repo and updated maven project, build maven project than ran the project in JBOSS server. issue got resolved.

Difference between two dates in years, months, days in JavaScript

Some math is in order.

You can subtract one Date object from another in Javascript, and you'll get the difference between them in milisseconds. From this result you can extract the other parts you want (days, months etc.)

For example:

var a = new Date(2010, 10, 1);
var b = new Date(2010, 9, 1);

var c = a - b; // c equals 2674800000,
               // the amount of milisseconds between September 1, 2010
               // and August 1, 2010.

Now you can get any part you want. For example, how many days have elapsed between the two dates:

var days = (a - b) / (60 * 60 * 24 * 1000);
// 60 * 60 * 24 * 1000 is the amount of milisseconds in a day.
// the variable days now equals 30.958333333333332.

That's almost 31 days. You can then round down for 30 days, and use whatever remained to get the amounts of hours, minutes etc.

Angular2 handling http response

Update alpha 47

As of alpha 47 the below answer (for alpha46 and below) is not longer required. Now the Http module handles automatically the errores returned. So now is as easy as follows

http
  .get('Some Url')
  .map(res => res.json())
  .subscribe(
    (data) => this.data = data,
    (err) => this.error = err); // Reach here if fails

Alpha 46 and below

You can handle the response in the map(...), before the subscribe.

http
  .get('Some Url')
  .map(res => {
    // If request fails, throw an Error that will be caught
    if(res.status < 200 || res.status >= 300) {
      throw new Error('This request has failed ' + res.status);
    } 
    // If everything went fine, return the response
    else {
      return res.json();
    }
  })
  .subscribe(
    (data) => this.data = data, // Reach here if res.status >= 200 && <= 299
    (err) => this.error = err); // Reach here if fails

Here's a plnkr with a simple example.

Note that in the next release this won't be necessary because all status codes below 200 and above 299 will throw an error automatically, so you won't have to check them by yourself. Check this commit for more info.

Error: Java: invalid target release: 11 - IntelliJ IDEA

I added these two lines to build.gradle file

compileJava.options.fork = true
                                              
compileJava.options.forkOptions.executable = 'C:\\Program Files\\Java\\jdk-11.0.8'

and it works

I am using windows and my project based on gradle

my jdk path -> 'C:\Program Files\Java\jdk-11.0.8'

please provide your jdk path

What's the best way to get the last element of an array without deleting it?

As of PHP version 7.3 the functions array_key_first and array_key_last has been introduced.

Since arrays in PHP are not strict array types, i.e. fixed sized collections of fixed sized fields starting at index 0, but dynamically extended associative array, the handling of positions with unknown keys is hard and workarounds do not perform very well. In contrast real arrays would be internally addressed via pointer arithmethics very rapidly and the last index is already known at compile-time by declaration.

At least the problem with the first and last position is solved by builtin functions now since version 7.3. This even works without any warnings on array literals out of the box:

$first = array_key_first( [1, 2, 'A'=>65, 'B'=>66, 3, 4 ] );
$last  = array_key_last ( [1, 2, 'A'=>65, 'B'=>66, 3, 4 ] );

Obviously the last value is:

$array[array_key_last($array)];

Does C# have extension properties?

Because I recently needed this, I looked at the source of the answer in:

c# extend class by adding properties

and created a more dynamic version:

public static class ObjectExtenders
{
    static readonly ConditionalWeakTable<object, List<stringObject>> Flags = new ConditionalWeakTable<object, List<stringObject>>();

    public static string GetFlags(this object objectItem, string key)
    {
        return Flags.GetOrCreateValue(objectItem).Single(x => x.Key == key).Value;
    }

    public static void SetFlags(this object objectItem, string key, string value)
    {
        if (Flags.GetOrCreateValue(objectItem).Any(x => x.Key == key))
        {
            Flags.GetOrCreateValue(objectItem).Single(x => x.Key == key).Value = value;
        }
        else
        {
            Flags.GetOrCreateValue(objectItem).Add(new stringObject()
            {
                Key = key,
                Value = value
            });
        }
    }

    class stringObject
    {
        public string Key;
        public string Value;
    }
}

It can probably be improved a lot (naming, dynamic instead of string), I currently use this in CF 3.5 together with a hacky ConditionalWeakTable (https://gist.github.com/Jan-WillemdeBruyn/db79dd6fdef7b9845e217958db98c4d4)

How to write an async method with out parameter?

Alex made a great point on readability. Equivalently, a function is also interface enough to define the type(s) being returned and you also get meaningful variable names.

delegate void OpDelegate(int op);
Task<bool> GetDataTaskAsync(OpDelegate callback)
{
    bool canGetData = true;
    if (canGetData) callback(5);
    return Task.FromResult(canGetData);
}

Callers provide a lambda (or a named function) and intellisense helps by copying the variable name(s) from the delegate.

int myOp;
bool result = await GetDataTaskAsync(op => myOp = op);

This particular approach is like a "Try" method where myOp is set if the method result is true. Otherwise, you don't care about myOp.

apply drop shadow to border-top only?

Multiple box shadows did it for me.

box-shadow:
        inset 0 -8px 4px 4px rgb(255,255,255),
        inset 0 2px 4px 0px rgba(50, 50, 50, 0.75);

http://jsfiddle.net/kk66f/

$on and $broadcast in angular

If you want to $broadcast use the $rootScope:

$scope.startScanner = function() {

    $rootScope.$broadcast('scanner-started');
}

And then to receive, use the $scope of your controller:

$scope.$on('scanner-started', function(event, args) {

    // do what you want to do
});

If you want you can pass arguments when you $broadcast:

$rootScope.$broadcast('scanner-started', { any: {} });

And then receive them:

$scope.$on('scanner-started', function(event, args) {

    var anyThing = args.any;
    // do what you want to do
});

Documentation for this inside the Scope docs.

Convert array of strings to List<string>

Just use this constructor of List<T>. It accepts any IEnumerable<T> as an argument.

string[] arr = ...
List<string> list = new List<string>(arr);

How can I format a nullable DateTime with ToString()?

you can use simple line:

dt2.ToString("d MMM yyyy") ?? ""

Error: EPERM: operation not permitted, unlink 'D:\Sources\**\node_modules\fsevents\node_modules\abbrev\package.json'

I tried this solution found at a How to fix Node.js blog

just use

npm cache clean

in windows if it refuses use

npm cache clean --force

How to access the last value in a vector?

The xts package provides a last function:

library(xts)
a <- 1:100
last(a)
[1] 100

Is it a good practice to place C++ definitions in header files?

To add more fun you can add .ipp files which contain the template implementation (that is being included in .hpp), while .hpp contains the interface.

As apart from templatized code (depending on the project this can be majority or minority of files) there is normal code and here it is better to separate the declarations and definitions. Provide also forward-declarations where needed - this may have effect on the compilation time.

KeyListener, keyPressed versus keyTyped

keyPressed - when the key goes down
keyReleased - when the key comes up
keyTyped - when the unicode character represented by this key is sent by the keyboard to system input.

I personally would use keyReleased for this. It will fire only when they lift their finger up.

Note that keyTyped will only work for something that can be printed (I don't know if F5 can or not) and I believe will fire over and over again if the key is held down. This would be useful for something like... moving a character across the screen or something.

EC2 Instance Cloning

There is no explicit Clone button. Basically what you do is create an image, or snapshot of an existing EC2 instance, and then spin up a new instance using that snapshot.

First create an image from an existing EC2 instance.

enter image description here


Check your snapshots list to see if the process is completed. This usually takes around 20 minutes depending on how large your instance drive is.

enter image description here


Then, you need to create a new instance and use that image as the AMI.

enter image description here

enter image description here

How to detect input type=file "change" for the same file?

This work for me

<input type="file" onchange="function();this.value=null;return false;">

matplotlib error - no module named tkinter

For Windows users, there's no need to download the installer again. Just do the following:

  1. Go to start menu, type Apps & features,
  2. Search for "python" in the search box,
  3. Select the Python version (e.g. Python 3.8.3rc1(32-bit)) and click Modify,
  4. On the Modify Setup page click Modify,
  5. Tick td/tk and IDLE checkbox (which installs tkinter) and click next.

Wait for installation and you're done.

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

Parse String date in (yyyy-MM-dd) format

You may need to format the out put as follows.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date convertedCurrentDate = sdf.parse("2013-09-18");
String date=sdf.format(convertedCurrentDate );
System.out.println(date);

Use

String convertedCurrentDate =sdf.format(sdf.parse("2013-09-18"));

Output:

2013-09-18

how to show only even or odd rows in sql server 2008?

SELECT *
  FROM   
  ( 
     SELECT rownum rn, empno, ename
     FROM emp
  ) temp
  WHERE  MOD(temp.rn,2) = 1

Python | change text color in shell

curses will allow you to use colors properly for the type of terminal that is being used.

Cannot use string offset as an array in php

For PHP4

...this reproduced the error:

$foo    = 'bar';
$foo[0] = 'bar';

For PHP5

...this reproduced the error:

$foo = 'bar';

if (is_array($foo['bar']))
    echo 'bar-array';
if (is_array($foo['bar']['foo']))
    echo 'bar-foo-array';
if (is_array($foo['bar']['foo']['bar']))
    echo 'bar-foo-bar-array';

(From bugs.php.net actually)

Edit,

so why doesn't the error appear in the first if condition even though it is a string.

Because PHP is a very forgiving programming language, I'd guess. I'll illustrate with code of what I think is going on:

$foo = 'bar';
// $foo is now equal to "bar"

$foo['bar'] = 'foo';
// $foo['bar'] doesn't exists - use first index instead (0)
// $foo['bar'] is equal to using $foo[0]
// $foo['bar'] points to a character so the string "foo" won't fit
// $foo['bar'] will instead be set to the first index
// of the string/array "foo", i.e 'f'

echo $foo['bar'];
// output will be "f"

echo $foo;
// output will be "far"

echo $foo['bar']['bar'];
// $foo['bar'][0] is equal calling to $foo['bar']['bar']
// $foo['bar'] points to a character
// characters can not be represented as an array,
// so we cannot reach anything at position 0 of a character
// --> fatal error

gcc/g++: "No such file or directory"

this works for me, sudo apt-get install libx11-dev

What is the most effective way to get the index of an iterator of an std::vector?

Beside int float string etc., you can put extra data to .second when using diff. types like:

std::map<unsigned long long int, glm::ivec2> voxels_corners;
std::map<unsigned long long int, glm::ivec2>::iterator it_corners;

or

struct voxel_map {
    int x,i;
};

std::map<unsigned long long int, voxel_map> voxels_corners;
std::map<unsigned long long int, voxel_map>::iterator it_corners;

when

long long unsigned int index_first=some_key; // llu in this case...
int i=0;
voxels_corners.insert(std::make_pair(index_first,glm::ivec2(1,i++)));

or

long long unsigned int index_first=some_key;
int index_counter=0;
voxel_map one;
one.x=1;
one.i=index_counter++;

voxels_corners.insert(std::make_pair(index_first,one));

with right type || structure you can put anything in the .second including a index number that is incremented when doing an insert.

instead of

it_corners - _corners.begin()

or

std::distance(it_corners.begin(), it_corners)

after

it_corners = voxels_corners.find(index_first+bdif_x+x_z);

the index is simply:

int vertice_index = it_corners->second.y;

when using the glm::ivec2 type

or

int vertice_index = it_corners->second.i;

in case of the structure data type

Update all objects in a collection using LINQ

You can use Magiq, a batch operation framework for LINQ.

Remove an item from an IEnumerable<T> collection

The IEnumerable interface is just that, enumerable - it doesn't provide any methods to Add or Remove or modify the list at all.

The interface just provides a way to iterate over some items - most implementations that require enumeration will implement IEnumerable such as List<T>

Why don't you just use your code without the implicit cast to IEnumerable

// Treat this like a list, not an enumerable
List<User> modifiedUsers = new List<User>();

foreach(var u in users)
{
   if(u.userId != 1233)
   {
        // Use List<T>.Add
        modifiedUsers.Add(u);
   }
}

Build project into a JAR automatically in Eclipse

Create an Ant file and tell Eclipse to build it. There are only two steps and each is easy with the step-by-step instructions below.


Step 1 Create a build.xml file and add to package explorer:

<?xml version="1.0" ?>
<!-- Configuration of the Ant build system to generate a Jar file --> 
<project name="TestMain" default="CreateJar">
  <target name="CreateJar" description="Create Jar file">
        <jar jarfile="Test.jar" basedir="." includes="*.class" />
  </target>
</project>

Eclipse should looks something like the screenshot below. Note the Ant icon on build.xml. Build.xml in Eclipse Project

Step 2 Right-click on the root node in the project. - Select Properties - Select Builders - Select New - Select Ant Build - In the Main tab, complete the path to the build.xml file in the bin folder.

Ant builder configuration Build step - Targets Tab

Check the Output

The Eclipse output window (named Console) should show the following after a build:

Buildfile: /home/<user>/src/Test/build.xml

CreateJar:
         [jar] Building jar: /home/<user>/src/Test/Test.jar
BUILD SUCCESSFUL
Total time: 152 milliseconds

EDIT: Some helpful comments by @yeoman and @betlista

@yeoman I think the correct include would be /.class, not *.class, as most people use packages and thus recursive search for class files makes more sense than flat inclusion

@betlista I would recomment to not to have build.xml in src folder

iOS - UIImageView - how to handle UIImage image orientation

Swift 3.1

func fixImageOrientation(_ image: UIImage)->UIImage {
    UIGraphicsBeginImageContext(image.size)
    image.draw(at: .zero)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage ?? image
}

AppendChild() is not a function javascript

In this

var div = '<div>top div</div>';

"div" is not a DOM object,is just a string,and string has no string.appendChild.

Here are some references that may help you on appendChild method:

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);

var element = document.getElementById("div1");
element.appendChild(para);
</script>

How to make a movie out of images in python

I use the ffmpeg-python binding. You can find more information here.

import ffmpeg
(
    ffmpeg
    .input('/path/to/jpegs/*.jpg', pattern_type='glob', framerate=25)
    .output('movie.mp4')
    .run()
)

How to do fade-in and fade-out with JavaScript and CSS

I like Ibu's one but, I think I have a better solution using his idea.

//Fade In.
element.style.opacity = 0;
var Op1 = 0;
var Op2 = 1;
var foo1, foo2;
foo1 = setInterval(Timer1, 20);
function Timer1()
{
    element.style.opacity = Op1;
    Op1 = Op1 + .01;
    console.log(Op1); //Option, but I recommend it for testing purposes.
    if (Op1 > 1)
    {
        clearInterval(foo1);
        foo2 = setInterval(Timer3, 20);
    }
}

This solution uses a additional equation unlike Ibu's solution, which used a multiplicative equation. The way it works is it takes a time increment (t), an opacity increment (o), and a opacity limit (l) in the equation, which is: (T = time of fade in miliseconds) [T = (l/o)*t]. the "20" represents the time increments or intervals (t), the ".01" represents the opacity increments (o), and the 1 represents the opacity limit (l). When you plug the numbers in the equation you get 2000 milliseconds (or 2 seconds). Here is the console log:

0.01
0.02
0.03
0.04
0.05
0.060000000000000005
0.07
0.08
0.09
0.09999999999999999
0.10999999999999999
0.11999999999999998
0.12999999999999998
0.13999999999999999
0.15
0.16
0.17
0.18000000000000002
0.19000000000000003
0.20000000000000004
0.21000000000000005
0.22000000000000006
0.23000000000000007
0.24000000000000007
0.25000000000000006
0.26000000000000006
0.2700000000000001
0.2800000000000001
0.2900000000000001
0.3000000000000001
0.3100000000000001
0.3200000000000001
0.3300000000000001
0.34000000000000014
0.35000000000000014
0.36000000000000015
0.37000000000000016
0.38000000000000017
0.3900000000000002
0.4000000000000002
0.4100000000000002
0.4200000000000002
0.4300000000000002
0.4400000000000002
0.45000000000000023
0.46000000000000024
0.47000000000000025
0.48000000000000026
0.49000000000000027
0.5000000000000002
0.5100000000000002
0.5200000000000002
0.5300000000000002
0.5400000000000003
0.5500000000000003
0.5600000000000003
0.5700000000000003
0.5800000000000003
0.5900000000000003
0.6000000000000003
0.6100000000000003
0.6200000000000003
0.6300000000000003
0.6400000000000003
0.6500000000000004
0.6600000000000004
0.6700000000000004
0.6800000000000004
0.6900000000000004
0.7000000000000004
0.7100000000000004
0.7200000000000004
0.7300000000000004
0.7400000000000004
0.7500000000000004
0.7600000000000005
0.7700000000000005
0.7800000000000005
0.7900000000000005
0.8000000000000005
0.8100000000000005
0.8200000000000005
0.8300000000000005
0.8400000000000005
0.8500000000000005
0.8600000000000005
0.8700000000000006
0.8800000000000006
0.8900000000000006
0.9000000000000006
0.9100000000000006
0.9200000000000006
0.9300000000000006
0.9400000000000006
0.9500000000000006
0.9600000000000006
0.9700000000000006
0.9800000000000006
0.9900000000000007
1.0000000000000007
1.0100000000000007

Notice how the opacity follows the opacity increment amount of .01 just like in the code. If you use the code Ibu made,

//I made slight edits but keeped the ESSENTIAL stuff in it.
var op = 0.01;  // initial opacity
var timer = setInterval(function () {
    if (op >= 1){
        clearInterval(timer);
    }
    element.style.opacity = op;
    op += op * 0.1;
}, 20);

you will get these numbers (or something similar) in you console log. Here is what I got.

0.0101
0.010201
0.01030301
0.0104060401
0.010510100501
0.010615201506009999
0.0107213535210701
0.0108285670562808
0.010936852726843608
0.011046221254112044
0.011156683466653165
0.011268250301319695
0.011380932804332892
0.01149474213237622
0.011609689553699983
0.011725786449236983
0.011843044313729352
0.011961474756866645
0.012081089504435313
0.012201900399479666
0.012323919403474463
0.012447158597509207
0.0125716301834843
0.012697346485319142
0.012824319950172334
0.012952563149674056
0.013082088781170797
0.013212909668982505
0.01334503876567233
0.013478489153329052
0.013613274044862343
0.013749406785310966
0.013886900853164076
0.014025769861695717
0.014166027560312674
0.014307687835915801
0.01445076471427496
0.01459527236141771
0.014741225085031886
0.014888637335882205
0.015037523709241028
0.015187898946333437
0.01533977793579677
0.015493175715154739
0.015648107472306286
0.01580458854702935
0.015962634432499644
0.01612226077682464
0.016283483384592887
0.016446318218438817
0.016610781400623206
0.01677688921462944
0.016944658106775732
0.01711410468784349
0.017285245734721923
0.017458098192069144
0.017632679173989835
0.01780900596572973
0.01798709602538703
0.018166966985640902
0.01834863665549731
0.018532123022052285
0.018717444252272807
0.018904618694795535
0.01909366488174349
0.019284601530560927
0.019477447545866538
0.0196722220213252
0.019868944241538455
0.02006763368395384
0.02026831002079338
0.020470993121001313
0.020675703052211326
0.02088246008273344
0.021091284683560776
0.021302197530396385
0.02151521950570035
0.021730371700757353
0.021947675417764927
0.022167152171942577
0.022388823693662
0.022612711930598623
0.022838839049904608
0.023067227440403654
0.02329789971480769
0.023530878711955767
0.023766187499075324
0.024003849374066077
0.02424388786780674
0.024486326746484807
0.024731190013949654
0.024978501914089152
0.025228286933230044
0.025480569802562344
0.025735375500587968
0.025992729255593847
0.026252656548149785
0.026515183113631283
0.026780334944767597
0.027048138294215273
0.027318619677157426
0.027591805873929
0.02786772393266829
0.028146401171994972
0.028427865183714922
0.02871214383555207
0.02899926527390759
0.029289257926646668
0.029582150505913136
0.029877972010972267
0.030176751731081992
0.030478519248392812
0.03078330444087674
0.031091137485285508
0.031402048860138365
0.03171606934873975
0.03203323004222715
0.03235356234264942
0.03267709796607591
0.03300386894573667
0.03333390763519403
0.03366724671154597
0.03400391917866143
0.03434395837044805
0.03468739795415253
0.03503427193369406
0.035384614653031
0.035738460799561306
0.03609584540755692
0.03645680386163249
0.03682137190024882
0.03718958561925131
0.03756148147544382
0.03793709629019826
0.03831646725310024
0.038699631925631243
0.03908662824488755
0.039477494527336426
0.03987226947260979
0.040270992167335894
0.04067370208900925
0.04108043910989934
0.04149124350099834
0.04190615593600832
0.042325217495368404
0.04274846967032209
0.04317595436702531
0.04360771391069556
0.044043791049802515
0.04448422896030054
0.04492907124990354
0.04537836196240258
0.045832145582026605
0.04629046703784687
0.04675337170822534
0.047220905425307595
0.04769311447956067
0.04817004562435628
0.04865174608059984
0.04913826354140584
0.0496296461768199
0.0501259426385881
0.05062720206497398
0.05113347408562372
0.05164480882647996
0.05216125691474476
0.05268286948389221
0.053209698178731134
0.05374179516051845
0.05427921311212363
0.05482200524324487
0.05537022529567732
0.05592392754863409
0.056483166824120426
0.05704799849236163
0.05761847847728525
0.0581946632620581
0.05877660989467868
0.059364375993625464
0.05995801975356172
0.060557599951097336
0.06116317595060831
0.06177480771011439
0.06239255578721554
0.0630164813450877
0.06364664615853857
0.06428311262012396
0.0649259437463252
0.06557520318378844
0.06623095521562633
0.0668932647677826
0.06756219741546042
0.06823781938961503
0.06892019758351117
0.06960939955934628
0.07030549355493974
0.07100854849048914
0.07171863397539403
0.07243582031514798
0.07316017851829945
0.07389178030348245
0.07463069810651728
0.07537700508758245
0.07613077513845827
0.07689208288984285
0.07766100371874128
0.0784376137559287
0.07922198989348798
0.08001420979242287
0.0808143518903471
0.08162249540925057
0.08243872036334307
0.0832631075669765
0.08409573864264626
0.08493669602907272
0.08578606298936345
0.08664392361925709
0.08751036285544966
0.08838546648400417
0.08926932114884421
0.09016201436033265
0.09106363450393598
0.09197427084897535
0.0928940135574651
0.09382295369303975
0.09476118322997015
0.09570879506226986
0.09666588301289256
0.09763254184302148
0.0986088672614517
0.09959495593406621
0.10059090549340688
0.10159681454834095
0.10261278269382436
0.1036389105207626
0.10467529962597022
0.10572205262222992
0.10677927314845222
0.10784706587993674
0.10892553653873611
0.11001479190412347
0.1111149398231647
0.11222608922139635
0.11334835011361032
0.11448183361474643
0.11562665195089389
0.11678291847040283
0.11795074765510685
0.11913025513165793
0.1203215576829745
0.12152477325980425
0.12274002099240229
0.12396742120232632
0.12520709541434957
0.12645916636849308
0.127723758032178
0.12900099561249978
0.13029100556862477
0.13159391562431103
0.13290985478055414
0.1342389533283597
0.13558134286164328
0.1369371562902597
0.1383065278531623
0.13968959313169393
0.14108648906301088
0.142497353953641
0.1439223274931774
0.14536155076810917
0.14681516627579025
0.14828331793854815
0.14976615111793362
0.15126381262911295
0.15277645075540408
0.15430421526295812
0.1558472574155877
0.15740572998974356
0.158979787289641
0.1605695851625374
0.16217528101416276
0.16379703382430438
0.16543500416254742
0.1670893542041729
0.16876024774621462
0.17044785022367676
0.17215232872591352
0.17387385201317265
0.17561259053330439
0.17736871643863744
0.1791424036030238
0.18093382763905405
0.1827431659154446
0.18457059757459904
0.18641630355034502
0.1882804665858485
0.19016327125170698
0.19206490396422404
0.19398555300386627
0.19592540853390494
0.197884662619244
0.19986350924543644
0.20186214433789082
0.20388076578126973
0.20591957343908243
0.20797876917347324
0.21005855686520797
0.21215914243386005
0.21428073385819865
0.21642354119678064
0.21858777660874845
0.22077365437483593
0.2229813909185843
0.22521120482777013
0.22746331687604782
0.2297379500448083
0.23203532954525638
0.23435568284070896
0.23669923966911605
0.2390662320658072
0.24145689438646528
0.24387146333032994
0.24631017796363325
0.24877327974326957
0.25126101254070227
0.2537736226661093
0.2563113588927704
0.2588744724816981
0.26146321720651505
0.2640778493785802
0.266718627872366
0.26938581415108964
0.27207967229260055
0.27480046901552657
0.27754847370568186
0.28032395844273866
0.28312719802716607
0.28595847000743774
0.2888180547075121
0.2917062352545872
0.2946232976071331
0.2975695305832044
0.3005452258890364
0.3035506781479268
0.3065861849294061
0.3096520467787002
0.3127485672464872
0.31587605291895204
0.31903481344814155
0.322225161582623
0.3254474131984492
0.3287018873304337
0.33198890620373805
0.33530879526577545
0.3386618832184332
0.34204850205061754
0.3454689870711237
0.34892367694183496
0.35241291371125333
0.35593704284836586
0.3594964132768495
0.363091377409618
0.3667222911837142
0.3703895140955513
0.37409340923650686
0.37783434332887195
0.38161268676216065
0.38542881362978226
0.3892831017660801
0.3931759327837409
0.3971076921115783
0.40107876903269407
0.405089556723021
0.4091404522902512
0.4132318568131537
0.41736417538128523
0.4215378171350981
0.42575319530644906
0.43001072725951356
0.43431083453210867
0.43865394287742976
0.4430404823062041
0.44747088712926614
0.4519455960005588
0.45646505196056436
0.46102970248017
0.4656399995049717
0.47029639950002144
0.47499936349502164
0.47974935712997185
0.48454685070127157
0.4893923192082843
0.4942862424003671
0.4992291048243708
0.5042213958726145
0.5092636098313407
0.5143562459296541
0.5194998083889507
0.5246948064728402
0.5299417545375685
0.5352411720829442
0.5405935838037736
0.5459995196418114
0.5514595148382295
0.5569741099866118
0.5625438510864779
0.5681692895973427
0.5738509824933161
0.5795894923182493
0.5853853872414317
0.5912392411138461
0.5971516335249846
0.6031231498602344
0.6091543813588367
0.615245925172425
0.6213983844241493
0.6276123682683908
0.6338884919510748
0.6402273768705855
0.6466296506392913
0.6530959471456843
0.6596269066171412
0.6662231756833126
0.6728854074401457
0.6796142615145472
0.6864104041296927
0.6932745081709896
0.7002072532526995
0.7072093257852266
0.7142814190430788
0.7214242332335097
0.7286384755658448
0.7359248603215033
0.7432841089247183
0.7507169500139654
0.7582241195141051
0.7658063607092461
0.7734644243163386
0.7811990685595019
0.789011059245097
0.7969011698375479
0.8048701815359234
0.8129188833512826
0.8210480721847955
0.8292585529066434
0.8375511384357098
0.8459266498200669
0.8543859163182677
0.8629297754814503
0.8715590732362648
0.8802746639686274
0.8890774106083137
0.8979681847143969
0.9069478665615408
0.9160173452271562
0.9251775186794278
0.9344292938662221
0.9437735868048843
0.9532113226729332
0.9627434358996625
0.9723708702586591
0.9820945789612456
0.9919155247508581
1.0018346799983666
1.0118530267983503

Notice that there is no discernible pattern. If you ran Ibu's code, you would never know how long the fade was. You would have to grab a timer and guess and check 2 seconds. Nonetheless, Ibu's code did make a pretty nice fade in (it probably works for fade out. I don't know because I didn't use a fade out yet). My code will also work for a fade out. Let's just say you wanted 2 seconds for a fade out. You can do that with my code. Here is how it would look:

//Fade out. (Continued from the fade in.
function Timer2()
{
    element.style.opacity = Op2;
    Op2 = Op2 - .01;
    console.log(Op2); //Option, but I recommend it for testing purposes.
    if (Op2 < 0)
    { 
        clearInterval(foo2);
    }
}

All I did was change the opacity to 1 (or fully opaque). I changed the opacity increment to -.01 so it would start turning invisible. Lastly, I changed the opacity limit to 0. When it hits the opacity limit, the timer will stop. Same as the last one, except it used 1 instead of 0. When you run the code, here is what the console log should relatively look like.

.99
0.98
0.97
0.96
0.95
0.94
0.9299999999999999
0.9199999999999999
0.9099999999999999
0.8999999999999999
0.8899999999999999
0.8799999999999999
0.8699999999999999
0.8599999999999999
0.8499999999999999
0.8399999999999999
0.8299999999999998
0.8199999999999998
0.8099999999999998
0.7999999999999998
0.7899999999999998
0.7799999999999998
0.7699999999999998
0.7599999999999998
0.7499999999999998
0.7399999999999998
0.7299999999999998
0.7199999999999998
0.7099999999999997
0.6999999999999997
0.6899999999999997
0.6799999999999997
0.6699999999999997
0.6599999999999997
0.6499999999999997
0.6399999999999997
0.6299999999999997
0.6199999999999997
0.6099999999999997
0.5999999999999996
0.5899999999999996
0.5799999999999996
0.5699999999999996
0.5599999999999996
0.5499999999999996
0.5399999999999996
0.5299999999999996
0.5199999999999996
0.5099999999999996
0.49999999999999956
0.48999999999999955
0.47999999999999954
0.46999999999999953
0.4599999999999995
0.4499999999999995
0.4399999999999995
0.4299999999999995
0.4199999999999995
0.4099999999999995
0.39999999999999947
0.38999999999999946
0.37999999999999945
0.36999999999999944
0.35999999999999943
0.3499999999999994
0.3399999999999994
0.3299999999999994
0.3199999999999994
0.3099999999999994
0.2999999999999994
0.28999999999999937
0.27999999999999936
0.26999999999999935
0.25999999999999934
0.24999999999999933
0.23999999999999932
0.22999999999999932
0.2199999999999993
0.2099999999999993
0.1999999999999993
0.18999999999999928
0.17999999999999927
0.16999999999999926
0.15999999999999925
0.14999999999999925
0.13999999999999924
0.12999999999999923
0.11999999999999923
0.10999999999999924
0.09999999999999924
0.08999999999999925
0.07999999999999925
0.06999999999999926
0.059999999999999255
0.04999999999999925
0.03999999999999925
0.02999999999999925
0.019999999999999248
0.009999999999999247
-7.528699885739343e-16
-0.010000000000000753

As you can see, the .01 pattern still exists in the fade out. Both fades are smooth and precise. I hope these codes helped you or gave you insight on the topic. If you have any additions or suggestions let me know. Thank you for taking the time to view this!

Exact difference between CharSequence and String in java

General differences

There are several classes which implement the CharSequence interface besides String. Among these are

  • StringBuilder for variable-length character sequences which can be modified
  • CharBuffer for fixed-length low-level character sequences which can be modified

Any method which accepts a CharSequence can operate on all of these equally well. Any method which only accepts a String will require conversion. So using CharSequence as an argument type in all the places where you don't care about the internals is prudent. However you should use String as a return type if you actually return a String, because that avoids possible conversions of returned values if the calling method actually does require a String.

Also note that maps should use String as key type, not CharSequence, as map keys must not change. In other words, sometimes the immutable nature of String is essential.

Specific code snippet

As for the code you pasted: simply compile that, and have a look at the JVM bytecode using javap -v. There you will notice that both obj and str are references to the same constant object. As a String is immutable, this kind of sharing is all right.

The + operator of String is compiled as invocations of various StringBuilder.append calls. So it is equivalent to

System.out.println(
  (new StringBuilder())
  .append("output is : ")
  .append((Object)obj)
  .append(" ")
  .append(str)
  .toString()
)

I must confess I'm a bit surprised that my compiler javac 1.6.0_33 compiles the + obj using StringBuilder.append(Object) instead of StringBuilder.append(CharSequence). The former probably involves a call to the toString() method of the object, whereas the latter should be possible in a more efficient way. On the other hand, String.toString() simply returns the String itself, so there is little penalty there. So StringBuilder.append(String) might be more efficient by about one method invocation.

Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window

I've experimented the exact same error. My problem was that the SetUp method I had created was declared as static.

If using eclipse, one could get a good description by clicking above the error and then checking the Failure trace window, just below... That's how I found the real problem!

Can multiple different HTML elements have the same ID if they're different elements?

The official spec for HTML states that id tags must be unique AND the official spec also states that if the render can be completed, it must (i.e. there are no such thing as "errors" in HTML, only "invalid" HTML). So, the following is how id tags actually work in practice. They are all invalid, but still work:

This:

<div id="unique">One</div>
<div id="unique">Two</div>

Renders fine in all browsers. However, document.getElementById only returns an object, not an array; you will only ever be able to select the first div via an id tag. If you were to change the id of the first div using JavaScript, the second ID would then be accessible with document.getElementById (tested on Chrome, FireFox & IE11). You can still select the div using other selection methods, and it's id property will be returned correctly.

Please note this above issue opens a potential security vulnerability in sites that render SVG images, as SVGs are allowed to contain DOM elements, and also id tags on them (allows script DOM redirects via uploaded images). As long as the SVG is positioned in the DOM before the element it replaces, the image will receive all JavaScript events meant for the other element.

This issue is currently not on anyone's radar as far as I know, yet it's real.

This:

<div id="unique" id="unique-also">One</div>

Also renders fine in all browsers. However, only the first id you define this way is utilized, if you tried document.getElementById('unique-also'); in the above example, you would be returned null (tested on Chrome, FireFox & IE11).

This:

<div id="unique unique-two">Two</div>

Also renders fine in all browsers, however, unlike class tags that can be separated by a space, the id tag allows spaces, so the id of the above element is actually "unique unique-two", and asking the dom for "unique" or "unique-two" in isolation returns null unless otherwise defined elsewhere in the DOM (tested on Chrome, FireFox & IE11).

The ternary (conditional) operator in C

In C, the real utility of it is that it's an expression instead of a statement; that is, you can have it on the right-hand side (RHS) of a statement. So you can write certain things more concisely.

pandas: to_numeric for multiple columns

df.loc[:,'col':] = df.loc[:,'col':].apply(pd.to_numeric, errors = 'coerce')

Pass Javascript Variable to PHP POST

Your idea of an hidden form element is solid. Something like this

<form action="script.php" method="post">
<input type="hidden" name="total" id="total">
</form>

<script type="text/javascript">
var element = document.getElementById("total");
element.value = getTotalFromSomewhere;
element.form.submit();
</script>

Of course, this will change the location to script.php. If you want to do this invisibly to the user, you'll want to use AJAX. Here's a jQuery example (for brevity). No form or hidden inputs required

$.post("script.php", { total: getTotalFromSomewhere });

Bootstrap carousel multiple frames at once

This is a working twitter bootstrap 3.

Here is the javascript:

$('#myCarousel').carousel({
    interval: 10000
})

$('.carousel .item').each(function(){
    var next = $(this).next();

    if (!next.length) {
        next = $(this).siblings(':first');
    }

    next.children(':first-child').clone().appendTo($(this));

    if (next.next().length>0) {
        next.next().children(':first-child').clone().appendTo($(this));
    }
    else {
        $(this).siblings(':first').children(':first-child').clone().appendTo($(this));
    }
});

And the css:

.carousel-inner .active.left  { left: -33%;             }
.carousel-inner .active.right { left: 33%;              }
.carousel-inner .next         { left: 33%               }
.carousel-inner .prev         { left: -33%              }
.carousel-control.left        { background-image: none; }
.carousel-control.right       { background-image: none; }
.carousel-inner .item         { background: white;      }

You can see it in action at this Jsfiddle

The reason i added this answer because the other ones don't work entirely. I found 2 bugs inside them, one of them was that the left arrow generated a strange effect and the other was about the text getting bold in some situations witch can be resolved by setting the background color so the bottom item wont be visible while the transition effect.

How to use a class object in C++ as a function parameter

At its simplest:

#include <iostream>
using namespace std;

class A {
   public:
     A( int x ) : n( x ){}
     void print() { cout << n << endl; }
   private:
     int n;
};

void func( A p ) {
   p.print();
}

int main () {
   A a;
   func ( a );
}

Of course, you should probably be using references to pass the object, but I suspect you haven't got to them yet.

Html code as IFRAME source rather than a URL

iframe srcdoc: This attribute contains HTML content, which will override src attribute. If a browser does not support the srcdoc attribute, it will fall back to the URL in the src attribute.

Let's understand it with an example

<iframe 
    name="my_iframe" 
    srcdoc="<h1 style='text-align:center; color:#9600fa'>Welcome to iframes</h1>"
    src="https://www.birthdaycalculatorbydate.com/"
    width="500px"
    height="200px"
></iframe>

Original content is taken from iframes.

Difference between hamiltonian path and euler path

Eulerian path must visit each edge exactly once, while Hamiltonian path must visit each vertex exactly once.

How to remove leading and trailing zeros in a string? Python

You can simply do this with a bool:

if int(number) == float(number):

   number = int(number)

else:

   number = float(number)

Checkout old commit and make it a new commit

git rm -r .
git checkout HEAD~3 .
git commit

After the commit, files in the new HEAD will be the same as they were in the revision HEAD~3.

How do I check if a string is valid JSON in Python?

I would say parsing it is the only way you can really entirely tell. Exception will be raised by python's json.loads() function (almost certainly) if not the correct format. However, the the purposes of your example you can probably just check the first couple of non-whitespace characters...

I'm not familiar with the JSON that facebook sends back, but most JSON strings from web apps will start with a open square [ or curly { bracket. No images formats I know of start with those characters.

Conversely if you know what image formats might show up, you can check the start of the string for their signatures to identify images, and assume you have JSON if it's not an image.

Another simple hack to identify a graphic, rather than a text string, in the case you're looking for a graphic, is just to test for non-ASCII characters in the first couple of dozen characters of the string (assuming the JSON is ASCII).

Why is my toFixed() function not working?

document.getElementById("EDTVALOR").addEventListener("change", function() {
  this.value = this.value.replace(",", ".");
  this.value = parseFloat(this.value).toFixed(2);
  if (this.value < 0) {
    this.value = 0;
  }
  this.value = this.value.replace(".", ",");
  this.value = this.value.replace("NaN", "0");
});

How to run test methods in specific order in JUnit4?

If you get rid of your existing instance of Junit, and download JUnit 4.11 or greater in the build path, the following code will execute the test methods in the order of their names, sorted in ascending order:

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SampleTest {

    @Test
    public void testAcreate() {
        System.out.println("first");
    }
    @Test
    public void testBupdate() {
        System.out.println("second");
    }
    @Test
    public void testCdelete() {
        System.out.println("third");
    }
}

Font size of TextView in Android application changes on changing font size from native settings

simple way to prevent the whole app from getting effected by system font size is to updateConfiguration using a base activity.

//in base activity add this code.
public  void adjustFontScale( Configuration configuration) {

    configuration.fontScale = (float) 1.0;
    DisplayMetrics metrics = getResources().getDisplayMetrics();
    WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
    wm.getDefaultDisplay().getMetrics(metrics);
    metrics.scaledDensity = configuration.fontScale * metrics.density;
    getBaseContext().getResources().updateConfiguration(configuration, metrics);

}

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    adjustFontScale( getResources().getConfiguration());
}

Node.js - Maximum call stack size exceeded

Regarding increasing the max stack size, on 32 bit and 64 bit machines V8's memory allocation defaults are, respectively, 700 MB and 1400 MB. In newer versions of V8, memory limits on 64 bit systems are no longer set by V8, theoretically indicating no limit. However, the OS (Operating System) on which Node is running can always limit the amount of memory V8 can take, so the true limit of any given process cannot be generally stated.

Though V8 makes available the --max_old_space_size option, which allows control over the amount of memory available to a process, accepting a value in MB. Should you need to increase memory allocation, simply pass this option the desired value when spawning a Node process.

It is often an excellent strategy to reduce the available memory allocation for a given Node instance, especially when running many instances. As with stack limits, consider whether massive memory needs are better delegated to a dedicated storage layer, such as an in-memory database or similar.

Immediate exit of 'while' loop in C++

cin >> choice;
while(choice!=99) {
    cin>>gNum;
    cin >> choice
}

You don't need a break, in that case.

change type of input field with jQuery

Simply this:

this.type = 'password';

such as

$("#password").click(function(){
    this.type = 'password';
});

This is assuming that your input field was set to "text" before hand.

Defining private module functions in python

This is an ancient question, but both module private (one underscore) and class-private (two underscores) mangled variables are now covered in the standard documentation:

The Python Tutorial » Classes » Private Variables

Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file

I stumbled upon another possible reason of this error. If you use NTFS symbolic links in your project tree, and probably subst'ed drives, you may get this error even if they point to your local drive. If this is the case, try to avoid the situation when .resx files are reached via symlinks.

How to calculate number of days between two given dates?

everyone has answered excellently using the date, let me try to answer it using pandas

dt = pd.to_datetime('2008/08/18', format='%Y/%m/%d')
dt1 = pd.to_datetime('2008/09/26', format='%Y/%m/%d')

(dt1-dt).days

This will give the answer. In case one of the input is dataframe column. simply use dt.days in place of days

(dt1-dt).dt.days

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

With JavaScript:

if (/Trident/g.test(navigator.userAgent)) { // detect trident engine so IE
        document.getElementsByTagName('html')[0].className= 'no-js ie'; }

Work for all IE.

IE08 => 'Trident/4.0'

IE09 => 'Trident/5.0'

IE10 => 'Trident/6.0'

IE11 => 'Trident/7.0'

So change /Trident/g by /Trident/x.0/g where x = 4, 5, 6 or 7 (or maybe 8 for the future).

mat-form-field must contain a MatFormFieldControl

import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';

don't forget to add at first of <tabe></table>

 <mat-form-field>
        <mat-label>Filter</mat-label>
        <input matInput (keyup)="applyFilter($event)" placeholder="Ex. Helium" #input>
      </mat-form-field>

don't forget to add at last of <tabe></table>

<tr class="mat-row" *matNoDataRow>
<td class="mat-cell" colspan="4">
   No data matching the filter "{{input.value}}"
</td>
</tr>

Undefined symbols for architecture i386: _OBJC_CLASS_$_SKPSMTPMessage", referenced from: error

I also met this issue and I fixed it by checking if both compile source and link binary with library contained all the file/library/framework I required.

enter image description here

How do you properly determine the current script directory?

Note: this answer is now a package

$ pip install locate

>>> from locate import this_dir
>>> print(this_dir())
C:/Users/simon

For .py scripts as well as interactive usage:

I frequently use the directory of my scripts (for accessing files stored along side them), but I also frequently run these scripts in an interactive shell for debugging purposes. I define __dirpath__ as:

  • When running or importing a .py file, the file's base directory. This is always the correct path.
  • When running an .ipyn notebook, the current working directory. This is always the correct path, since Jupyter sets the working directory as the .ipynb base directory.
  • When running in a REPL, the current working directory. Hmm, what is the actual "correct path" when the code is detached from a file? Rather, make it your responsibility to change into the "correct path" before invoking the REPL.

Python 3.4 (and above):

from pathlib import Path
__dirpath__ = Path(globals().get("__file__", "./_")).absolute().parent

Python 2 (and above):

import os
__dirpath__ = os.path.dirname(os.path.abspath(globals().get("__file__", "./_")))

Explanation:

  • globals() returns all the global variables as a dictionary.
  • .get("__file__", "./_") returns the value from the key "__file__" if it exists in globals(), otherwise it returns the provided default value "./_".
  • The rest of the code just expands __file__ (or "./_") into an absolute filepath, and then returns the filepath's base directory.

How do I prompt a user for confirmation in bash script?

read -p "Are you sure? " -n 1 -r
echo    # (optional) move to a new line
if [[ $REPLY =~ ^[Yy]$ ]]
then
    # do dangerous stuff
fi

I incorporated levislevis85's suggestion (thanks!) and added the -n option to read to accept one character without the need to press Enter. You can use one or both of these.

Also, the negated form might look like this:

read -p "Are you sure? " -n 1 -r
echo    # (optional) move to a new line
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1 # handle exits from shell or function but don't exit interactive shell
fi

However, as pointed out by Erich, under some circumstances such as a syntax error caused by the script being run in the wrong shell, the negated form could allow the script to continue to the "dangerous stuff". The failure mode should favor the safest outcome so only the first, non-negated if should be used.

Explanation:

The read command outputs the prompt (-p "prompt") then accepts one character (-n 1) and accepts backslashes literally (-r) (otherwise read would see the backslash as an escape and wait for a second character). The default variable for read to store the result in is $REPLY if you don't supply a name like this: read -p "my prompt" -n 1 -r my_var

The if statement uses a regular expression to check if the character in $REPLY matches (=~) an upper or lower case "Y". The regular expression used here says "a string starting (^) and consisting solely of one of a list of characters in a bracket expression ([Yy]) and ending ($)". The anchors (^ and $) prevent matching longer strings. In this case they help reinforce the one-character limit set in the read command.

The negated form uses the logical "not" operator (!) to match (=~) any character that is not "Y" or "y". An alternative way to express this is less readable and doesn't as clearly express the intent in my opinion in this instance. However, this is what it would look like: if [[ $REPLY =~ ^[^Yy]$ ]]

Getting GET "?" variable in laravel

We have similar situation right now and as of this answer, I am using laravel 5.6 release.

I will not use your example in the question but mine, because it's related though.

I have route like this:

Route::name('your.name.here')->get('/your/uri', 'YourController@someMethod');

Then in your controller method, make sure you include

use Illuminate\Http\Request;

and this should be above your controller, most likely a default, if generated using php artisan, now to get variable from the url it should look like this:

  public function someMethod(Request $request)
  {
    $foo = $request->input("start");
    $bar = $request->input("limit");

    // some codes here
  }

Regardless of the HTTP verb, the input() method may be used to retrieve user input.

https://laravel.com/docs/5.6/requests#retrieving-input

Hope this help.

Giving height to table and row in Bootstrap

The simple solution that worked for me as below, wrap the table with a div and change the line-height, this line-height is taken as a ratio.

_x000D_
_x000D_
<div class="col-md-6" style="line-height: 0.5">_x000D_
                                <table class="table table-striped" >_x000D_
                                    <thead>_x000D_
                                    <tr>_x000D_
                                        <th>Parameter</th>_x000D_
                                        <th>Recorded Value</th>_x000D_
                                        <th>Individual Score</th>_x000D_
                                    </tr>_x000D_
                                    </thead>_x000D_
                                    <tbody>_x000D_
                                    <tr>_x000D_
                                        <td>Respiratory Rate</td>_x000D_
                                        <td>Doe</td>_x000D_
                                        <td>[email protected]</td>_x000D_
                                    </tr>_x000D_
                                    <tr>_x000D_
                                        <td>Respiratory Effort</td>_x000D_
                                        <td>Moe</td>_x000D_
                                        <td>[email protected]</td>_x000D_
                                    </tr>_x000D_
                                    <tr>_x000D_
                                        <td>Oxygon Saturation</td>_x000D_
                                        <td>Dooley</td>_x000D_
                                        <td>[email protected]</td>_x000D_
                                    </tr>_x000D_
                                    </tbody>_x000D_
                                </table>_x000D_
                            </div>
_x000D_
_x000D_
_x000D_

Try changing the value as it fits for you.

JPA 2.0, Criteria API, Subqueries, In Expressions

Below is the pseudo-code for using sub-query using Criteria API.

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();
Root<EMPLOYEE> from = criteriaQuery.from(EMPLOYEE.class);
Path<Object> path = from.get("compare_field"); // field to map with sub-query
from.fetch("name");
from.fetch("id");
CriteriaQuery<Object> select = criteriaQuery.select(from);

Subquery<PROJECT> subquery = criteriaQuery.subquery(PROJECT.class);
Root fromProject = subquery.from(PROJECT.class);
subquery.select(fromProject.get("requiredColumnName")); // field to map with main-query
subquery.where(criteriaBuilder.and(criteriaBuilder.equal("name",name_value),criteriaBuilder.equal("id",id_value)));

select.where(criteriaBuilder.in(path).value(subquery));

TypedQuery<Object> typedQuery = entityManager.createQuery(select);
List<Object> resultList = typedQuery.getResultList();

Also it definitely needs some modification as I have tried to map it according to your query. Here is a link http://www.ibm.com/developerworks/java/library/j-typesafejpa/ which explains concept nicely.

Connection string using Windows Authentication

For connecting to a sql server database via Windows authentication basically needs which server you want to connect , what is your database name , Integrated Security info and provider name.

Basically this works:

<connectionStrings>      
<add name="MyConnectionString"
         connectionString="data source=ServerName;
   Initial Catalog=DatabaseName;Integrated Security=True;"
         providerName="System.Data.SqlClient" />
</connectionStrings> 

Setting Integrated Security field true means basically you want to reach database via Windows authentication, if you set this field false Windows authentication will not work.

It is also working different according which provider you are using.

  • SqlClient both Integrated Security=true; or IntegratedSecurity=SSPI; is working.

  • OleDb it is Integrated Security=SSPI;

  • Odbc it is Trusted_Connection=yes;
  • OracleClient it is Integrated Security=yes;

Integrated Security=true throws an exception when used with the OleDb provider.

Bootstrap 4 responsive tables won't take up 100% width

I found that using the recommended table-responsive class in a wrapper still causes responsive tables to (surprisingly) shrink horizontally:

<div class="table-responsive-lg">
    <table class="table">
        ...
    </table>
</div>

The solution for me was to create the following media breakpoints and classes to prevent it:

.table-xs {
    width:544px;
}

.table-sm {
    width: 576px;
}

.table-md {
    width: 768px;
}

.table-lg {
    width: 992px;
}

.table-xl {
    width: 1200px;
}

/* Small devices (landscape phones, 544px and up) */
@media (min-width: 576px) {  
    .table-sm {
        width: 100%;
    }
}

/* Medium devices (tablets, 768px and up) The navbar toggle appears at this breakpoint */
@media (min-width: 768px) {
    .table-sm {
        width: 100%;
    }

    .table-md {
        width: 100%;
    }
}

/* Large devices (desktops, 992px and up) */
@media (min-width: 992px) {
    .table-sm {
        width: 100%;
    }

    .table-md {
        width: 100%;
    }

    .table-lg {
        width: 100%;
    }
}

/* Extra large devices (large desktops, 1200px and up) */
@media (min-width: 1200px) {
    .table-sm {
        width: 100%;
    }

    .table-md {
        width: 100%;
    }

    .table-lg {
        width: 100%;
    }

    .table-xl {
        width: 100%;
    }
}

Then I can add the appropriate class to my table element. For example:

<div class="table-responsive-lg">
    <table class="table table-lg">
        ...
    </table>
</div>

Here the wrapper sets the width to 100% for large and greater per Bootstrap. With the table-lg class applied to the table element, the table width is set also set to 100% for large and greater, but set to 992px for medium and smaller. The classes table-xs, table-sm, table-md, and table-xl work the same way.

python multithreading wait till all threads finished

In Python3, since Python 3.2 there is a new approach to reach the same result, that I personally prefer to the traditional thread creation/start/join, package concurrent.futures: https://docs.python.org/3/library/concurrent.futures.html

Using a ThreadPoolExecutor the code would be:

from concurrent.futures.thread import ThreadPoolExecutor
import time

def call_script(ordinal, arg):
    print('Thread', ordinal, 'argument:', arg)
    time.sleep(2)
    print('Thread', ordinal, 'Finished')

args = ['argumentsA', 'argumentsB', 'argumentsC']

with ThreadPoolExecutor(max_workers=2) as executor:
    ordinal = 1
    for arg in args:
        executor.submit(call_script, ordinal, arg)
        ordinal += 1
print('All tasks has been finished')

The output of the previous code is something like:

Thread 1 argument: argumentsA
Thread 2 argument: argumentsB
Thread 1 Finished
Thread 2 Finished
Thread 3 argument: argumentsC
Thread 3 Finished
All tasks has been finished

One of the advantages is that you can control the throughput setting the max concurrent workers.

Move SQL Server 2008 database files to a new folder location

You can use Detach/Attach Option in SQL Server Management Studio.

Check this: Move a Database Using Detach and Attach

How to send an HTTP request using Telnet

To somewhat expand on earlier answers, there are a few complications.

telnet is not particularly scriptable; you might prefer to use nc (aka netcat) instead, which handles non-terminal input and signals better.

Also, unlike telnet, nc actually allows SSL (and so https instead of http traffic -- you need port 443 instead of port 80 then).

There is a difference between HTTP 1.0 and 1.1. The recent version of the protocol requires the Host: header to be included in the request on a separate line after the POST or GET line, and to be followed by an empty line to mark the end of the request headers.

The HTTP protocol requires carriage return / line feed line endings. Many servers are lenient about this, but some are not. You might want to use

printf "%\r\n" \
    "GET /questions HTTP/1.1" \
    "Host: stackoverflow.com" \
    "" |
nc --ssl stackoverflow.com 443

If you fall back to HTTP/1.0 you don't always need the Host: header, but many modern servers require the header anyway; if multiple sites are hosted on the same IP address, the server doesn't know from GET /foo HTTP/1.0 whether you mean http://site1.example.com/foo or http://site2.example.net/foo if those two sites are both hosted on the same server (in the absence of a Host: header, a HTTP 1.0 server might just default to a different site than the one you want, so you don't get the contents you wanted).

The HTTPS protocol is identical to HTTP in these details; the only real difference is in how the session is set up initially.

Does SVG support embedding of bitmap images?

You could use a Data URI to supply the image data, for example:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

<image width="20" height="20" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="/>

</svg>

The image will go through all normal svg transformations.

But this technique has disadvantages, for example the image will not be cached by the browser

What are alternatives to document.write?

Here is code that should replace document.write in-place:

document.write=function(s){
    var scripts = document.getElementsByTagName('script');
    var lastScript = scripts[scripts.length-1];
    lastScript.insertAdjacentHTML("beforebegin", s);
}

How do I export a project in the Android studio?

From the menu:

Build|Generate Signed APK

or

Build|Build APK

(the latter if you don't need a signed one to publish to the Play Store)

"date(): It is not safe to rely on the system's timezone settings..."

<? date_default_timezone_set('Europe/Istanbul'); ?>

For php (or your location).

PHP: How to get current time in hour:minute:second?

You can combine both in the same date function call

date("d-m-Y H:i:s");  

MVC 3 file upload and model binding

If you won't always have images posting to your action, you can do something like this:

[HttpPost]
public ActionResult Uploadfile(Container container, HttpPostedFileBase file) 
{
    //do container stuff

    if (Request.Files != null)
    {
        foreach (string requestFile in Request.Files)
        {
            HttpPostedFileBase file = Request.Files[requestFile]; 
            if (file.ContentLength > 0)
            {
                string fileName = Path.GetFileName(file.FileName);
                string directory = Server.MapPath("~/App_Data/uploads/");
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                string path = Path.Combine(directory, fileName);
                file.SaveAs(path);
            }
        }
    }

} 

Stretch image to fit full container width bootstrap

In bootstrap 4.1, the w-100 class is required along with img-fluid for images smaller than the page to be stretched:

<div class="container">
  <div class="row">
    <img class='img-fluid w-100' src="#" alt="" />
  </div>
</div>

see closed issue: https://github.com/twbs/bootstrap/issues/20830

(As of 2018-04-20, the documentation is wrong: https://getbootstrap.com/docs/4.1/content/images/ says that img-fluid applies max-width: 100%; height: auto;" but img-fluid does not resolve the issue, and neither does manually adding those style attributes with or without bootstrap classes on the img tag.)

Running PowerShell as another user, and launching a script

Here's also nice way to achieve this via UI.

0) Right click on PowerShell icon when on task bar

1) Shift + right click on Windows PowerShell

2) "Run as different user"

Pic

Writing binary number system in C code

Use BOOST_BINARY (Yes, you can use it in C).

#include <boost/utility/binary.hpp>
...
int bin = BOOST_BINARY(110101);

This macro is expanded to an octal literal during preprocessing.

How to check if an environment variable exists and get its value?

All the answers worked. However, I had to add the variables that I needed to get to the sudoers files as follows:

sudo visudo
Defaults env_keep += "<var1>, <var2>, ..., <varn>"

How to remove an app with active device admin enabled on Android?

For Redmi users,

Settings -> Password & security -> Privacy -> Special app access -> Device admin apps

Click the deactivate the apps

Easy way to turn JavaScript array into comma-separated list?

Do you want to end it with an "and"?

For this situation, I created an npm module.

Try arrford:


Usage

const arrford = require('arrford');

arrford(['run', 'climb', 'jump!']);
//=> 'run, climb, and jump!'

arrford(['run', 'climb', 'jump!'], false);
//=> 'run, climb and jump!'

arrford(['run', 'climb!']);
//=> 'run and climb!'

arrford(['run!']);
//=> 'run!'


Install

npm install --save arrford


Read More

https://github.com/dawsonbotsford/arrford


Try it yourself

Tonic link

How to set a Javascript object values dynamically?

When you create an object myObj as you have, think of it more like a dictionary. In this case, it has two keys, name, and age.

You can access these dictionaries in two ways:

  • Like an array (e.g. myObj[name]); or
  • Like a property (e.g. myObj.name); do note that some properties are reserved, so the first method is preferred.

You should be able to access it as a property without any problems. However, to access it as an array, you'll need to treat the key like a string.

myObj["name"]

Otherwise, javascript will assume that name is a variable, and since you haven't created a variable called name, it won't be able to access the key you're expecting.

How to see indexes for a database or table in MySQL?

To see the index for a specific table use SHOW INDEX:

SHOW INDEX FROM yourtable;

To see indexes for all tables within a specific schema you can use the STATISTICS table from INFORMATION_SCHEMA:

SELECT DISTINCT
    TABLE_NAME,
    INDEX_NAME
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = 'your_schema';

Removing the where clause will show you all indexes in all schemas.

How do I download the Android SDK without downloading Android Studio?

To download the SDK over command line, the link has changed slightly than previously mentioned:

wget --quiet --output-document=/tmp/sdk-tools-linux.zip https://dl.google.com/android/repository/commandlinetools-linux-${ANDROID_SDK_TOOLS}.zip

Latest version listed on the downloads page.

How to do error logging in CodeIgniter (PHP)

CodeIgniter has some error logging functions built in.

  • Make your /application/logs folder writable
  • In /application/config/config.php set
    $config['log_threshold'] = 1;
    or use a higher number, depending on how much detail you want in your logs
  • Use log_message('error', 'Some variable did not contain a value.');
  • To send an email you need to extend the core CI_Exceptions class method log_exceptions(). You can do this yourself or use this. More info on extending the core here

See http://www.codeigniter.com/user_guide/general/errors.html

Convert from ASCII string encoded in Hex to plain ASCII?

b''.fromhex('7061756c')

use it without delimiter

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

How to get my activity context?

If you need the context of A in B, you need to pass it to B, and you can do that by passing the Activity A as parameter as others suggested. I do not see much the problem of having the many instances of A having their own pointers to B, not sure if that would even be that much of an overhead.

But if that is the problem, a possibility is to keep the pointer to A as a sort of global, avariable of the Application class, as @hasanghaforian suggested. In fact, depending on what do you need the context for, you could even use the context of the Application instead.

I'd suggest reading this article about context to better figure it out what context you need.

How can I clone a JavaScript object except for one key?

You also can use spread operator to do this

const source = { a: 1, b: 2, c: 3, z: 26 }
const copy = { ...source, ...{ b: undefined } } // { a: 1, c: 3, z: 26 }

Difference in Months between two dates in JavaScript

Consider each date in terms of months, then subtract to find the difference.

var past_date = new Date('11/1/2014');
var current_date = new Date();

var difference = (current_date.getFullYear()*12 + current_date.getMonth()) - (past_date.getFullYear()*12 + past_date.getMonth());

This will get you the difference of months between the two dates, ignoring the days.

To get total number of columns in a table in sql

In my situation, I was comparing table schema column count for 2 identical tables in 2 databases; one is the main database and the other is the archival database. I did this (SQL 2012+):

DECLARE @colCount1 INT;
DECLARE @colCount2 INT;

SELECT @colCount1 = COUNT(COLUMN_NAME) FROM MainDB.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'SomeTable';
SELECT @colCount2 = COUNT(COLUMN_NAME) FROM ArchiveDB.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'SomeTable';

IF (@colCount1 != @colCount2) THROW 5000, 'Number of columns in both tables are not equal. The archive schema may need to be updated.', 16;

The important thing to notice here is qualifying the database name before INFORMATION_SCHEMA (which is a schema, like dbo). This will allow the code to break, in case columns were added to the main database and not to the archival database, in which if the procedure were allowed to run, data loss would almost certainly occur.

How can I run code on a background thread on Android?

An Alternative to AsyncTask is robospice. https://github.com/octo-online/robospice.

Some of the features of robospice.

1.executes asynchronously (in a background AndroidService) network requests (ex: REST requests using Spring Android).notify you app, on the UI thread, when result is ready.

2.is strongly typed ! You make your requests using POJOs and you get POJOs as request results.

3.enforce no constraints neither on POJOs used for requests nor on Activity classes you use in your projects.

4.caches results (in Json with both Jackson and Gson, or Xml, or flat text files, or binary files, even using ORM Lite).

5.notifies your activities (or any other context) of the result of the network request if and only if they are still alive

6.no memory leak at all, like Android Loaders, unlike Android AsyncTasks notifies your activities on their UI Thread.

7.uses a simple but robust exception handling model.

Samples to start with. https://github.com/octo-online/RoboSpice-samples.

A sample of robospice at https://play.google.com/store/apps/details?id=com.octo.android.robospice.motivations&feature=search_result.

How to hide a status bar in iOS?

You need to add this code in your AppDelegate file, not in your Root View Controller

Or add the property Status bar is initially hidden in your plist file

enter image description here

Folks, in iOS 7+

please add this to your info.plist file, It will make the difference :)

UIStatusBarHidden UIViewControllerBasedStatusBarAppearance

enter image description here

For iOS 11.4+ and Xcode 9.4 +

Use this code either in one or all your view controllers

override var prefersStatusBarHidden: Bool { return true }

Team Build Error: The Path ... is already mapped to workspace

I received this error, which was caused by having two build definitions that pointed to the same source. The issue was that I used a static build directory in the Build Agent.

This forum post describes my issue and resolution exactly: http://social.msdn.microsoft.com/Forums/en-US/tfsbuild/thread/60a4138a-9b28-4c46-bdf4-f9775ce43c3e/

CSS media queries: max-width OR max-height

yes, using and, like:

@media screen and (max-width: 800px), 
       screen and (max-height: 600px) {
  ...
}

PHP array delete by value (not key)

To delete multiple values try this one:

while (($key = array_search($del_val, $messages)) !== false) 
{
    unset($messages[$key]);
}

How to add reference to a method parameter in javadoc?

I guess you could write your own doclet or taglet to support this behaviour.

Taglet Overview

Doclet Overview

Eclipse error ... cannot be resolved to a type

Easy Solution:
Go to

Project property -> java builder path -> maven -> find c3p0-0.9.5.2.jar

and see the location where the file is stored in the local repository and go to this location and delete the repository manually.

G

How do I verify that a string only contains letters, numbers, underscores and dashes?

A regular expression will do the trick with very little code:

import re

...

if re.match("^[A-Za-z0-9_-]*$", my_little_string):
    # do something here

How to get UTF-8 working in Java webapps?

I want also to add from here this part solved my utf problem:

runtime.encoding=<encoding>

HTTP get with headers using RestTemplate

The RestTemplate getForObject() method does not support setting headers. The solution is to use the exchange() method.

So instead of restTemplate.getForObject(url, String.class, param) (which has no headers), use

HttpHeaders headers = new HttpHeaders();
headers.set("Header", "value");
headers.set("Other-Header", "othervalue");
...

HttpEntity entity = new HttpEntity(headers);

ResponseEntity<String> response = restTemplate.exchange(
    url, HttpMethod.GET, entity, String.class, param);

Finally, use response.getBody() to get your result.

This question is similar to this question.

How to get 'System.Web.Http, Version=5.2.3.0?

In Package Manager Console

Install-Package Microsoft.AspNet.WebApi.Core -version 5.2.3

Get value from text area

Vanilla JS

document.getElementById("textareaID").value

jQuery

$("#textareaID").val()

Cannot do the other way round (it's always good to know what you're doing)

document.getElementById("textareaID").value() // --> TypeError: Property 'value' of object #<HTMLTextAreaElement> is not a function

jQuery:

$("#textareaID").value // --> undefined

No mapping found for HTTP request with URI [/WEB-INF/pages/apiForm.jsp]

Unfortunately, this is a rather broad class error message. Yet another thing which could be going wrong is if you are missing some classes/jars. For example, if you are missing the spring-expression jar file, the dispatch-servlet is not going to be able to locate your controller no matter how hard you try and how correct everything else is configured.

Setting table column width

style="column-width:300px;white-space: normal;"

Difference between `constexpr` and `const`

Both const and constexpr can be applied to variables and functions. Even though they are similar to each other, in fact they are very different concepts.

Both const and constexpr mean that their values can't be changed after their initialization. So for example:

const int x1=10;
constexpr int x2=10;

x1=20; // ERROR. Variable 'x1' can't be changed.
x2=20; // ERROR. Variable 'x2' can't be changed.

The principal difference between const and constexpr is the time when their initialization values are known (evaluated). While the values of const variables can be evaluated at both compile time and runtime, constexpr are always evaluated at compile time. For example:

int temp=rand(); // temp is generated by the the random generator at runtime.

const int x1=10; // OK - known at compile time.
const int x2=temp; // OK - known only at runtime.
constexpr int x3=10; // OK - known at compile time.
constexpr int x4=temp; // ERROR. Compiler can't figure out the value of 'temp' variable at compile time so `constexpr` can't be applied here.

The key advantage to know if the value is known at compile time or runtime is the fact that compile time constants can be used whenever compile time constants are needed. For instance, C++ doesn't allow you to specify C-arrays with the variable lengths.

int temp=rand(); // temp is generated by the the random generator at runtime.

int array1[10]; // OK.
int array2[temp]; // ERROR.

So it means that:

const int size1=10; // OK - value known at compile time.
const int size2=temp; // OK - value known only at runtime.
constexpr int size3=10; // OK - value known at compile time.


int array3[size1]; // OK - size is known at compile time.
int array4[size2]; // ERROR - size is known only at runtime time.
int array5[size3]; // OK - size is known at compile time.

So const variables can define both compile time constants like size1 that can be used to specify array sizes and runtime constants like size2 that are known only at runtime and can't be used to define array sizes. On the other hand constexpr always define compile time constants that can specify array sizes.

Both const and constexpr can be applied to functions too. A const function must be a member function (method, operator) where application of const keyword means that the method can't change the values of their member (non-static) fields. For example.

class test
{
   int x;

   void function1()
   {
      x=100; // OK.
   }

   void function2() const
   {
      x=100; // ERROR. The const methods can't change the values of object fields.
   }
};

A constexpr is a different concept. It marks a function (member or non-member) as the function that can be evaluated at compile time if compile time constants are passed as their arguments. For example you can write this.

constexpr int func_constexpr(int X, int Y)
{
    return(X*Y);
}

int func(int X, int Y)
{
    return(X*Y);
}

int array1[func_constexpr(10,20)]; // OK - func_constexpr() can be evaluated at compile time.
int array2[func(10,20)]; // ERROR - func() is not a constexpr function.

int array3[func_constexpr(10,rand())]; // ERROR - even though func_constexpr() is the 'constexpr' function, the expression 'constexpr(10,rand())' can't be evaluated at compile time.

By the way the constexpr functions are the regular C++ functions that can be called even if non-constant arguments are passed. But in that case you are getting the non-constexpr values.

int value1=func_constexpr(10,rand()); // OK. value1 is non-constexpr value that is evaluated in runtime.
constexpr int value2=func_constexpr(10,rand()); // ERROR. value2 is constexpr and the expression func_constexpr(10,rand()) can't be evaluated at compile time.

The constexpr can be also applied to the member functions (methods), operators and even constructors. For instance.

class test2
{
    static constexpr int function(int value)
    {
        return(value+1);
    }

    void f()
    {
        int x[function(10)];


    }
};

A more 'crazy' sample.

class test3
{
    public:

    int value;

    // constexpr const method - can't chanage the values of object fields and can be evaluated at compile time.
    constexpr int getvalue() const
    {
        return(value);
    }

    constexpr test3(int Value)
        : value(Value)
    {
    }
};


constexpr test3 x(100); // OK. Constructor is constexpr.

int array[x.getvalue()]; // OK. x.getvalue() is constexpr and can be evaluated at compile time.

Print new output on same line

print("single",end=" ")
print("line")

this will give output

single line

for the question asked use

i = 0 
while i <10:
     i += 1 
     print (i,end="")

Disable a Button

Let's say in Swift 4 you have a button set up for a segue as an IBAction like this @IBAction func nextLevel(_ sender: UIButton) {} and you have other actions occurring within your app (i.e. a timer, gamePlay, etc.). Rather than disabling the segue button, you might want to give your user the option to use that segue while the other actions are still occurring and WITHOUT CRASHING THE APP. Here's how:

var appMode = 0

@IBAction func mySegue(_ sender: UIButton) {

    if appMode == 1 {  // avoid crash if button pressed during other app actions and/or conditions
        let conflictingAction = sender as UIButton
        conflictingAction.isEnabled = false
    }
}

Please note that you will likely have other conditions within if appMode == 0 and/or if appMode == 1 that will still occur and NOT conflict with the mySegue button. Thus, AVOIDING A CRASH.

converting multiple columns from character to numeric format in r

You can use index of columns: data_set[,1:9] <- sapply(dataset[,1:9],as.character)

Add placeholder text inside UITextView in Swift?

Use This Extension this is the best way to set placeholder in UITextView. But make sure you have attached delegates to the TextView. You can set Place holder like this:-

yourTextView.placeholder = "Placeholder" 

extension UITextView :UITextViewDelegate
{

    /// Resize the placeholder when the UITextView bounds change
    override open var bounds: CGRect {
        didSet {
            self.resizePlaceholder()
        }
    }

    /// The UITextView placeholder text
    public var placeholder: String? {
        get {
            var placeholderText: String?

            if let placeholderLabel = self.viewWithTag(100) as? UILabel {
                placeholderText = placeholderLabel.text
            }

            return placeholderText
        }
        set {
            if let placeholderLabel = self.viewWithTag(100) as! UILabel? {
                placeholderLabel.text = newValue
                placeholderLabel.sizeToFit()
            } else {
                self.addPlaceholder(newValue!)
            }
        }
    }

    /// When the UITextView did change, show or hide the label based on if the UITextView is empty or not
    ///
    /// - Parameter textView: The UITextView that got updated
    public func textViewDidChange(_ textView: UITextView) {
        if let placeholderLabel = self.viewWithTag(100) as? UILabel {
            placeholderLabel.isHidden = self.text.characters.count > 0
        }
    }

    /// Resize the placeholder UILabel to make sure it's in the same position as the UITextView text
    private func resizePlaceholder() {
        if let placeholderLabel = self.viewWithTag(100) as! UILabel? {
            let labelX = self.textContainer.lineFragmentPadding
            let labelY = self.textContainerInset.top - 2
            let labelWidth = self.frame.width - (labelX * 2)
            let labelHeight = placeholderLabel.frame.height

            placeholderLabel.frame = CGRect(x: labelX, y: labelY, width: labelWidth, height: labelHeight)
        }
    }

    /// Adds a placeholder UILabel to this UITextView
    private func addPlaceholder(_ placeholderText: String) {
        let placeholderLabel = UILabel()

        placeholderLabel.text = placeholderText
        placeholderLabel.sizeToFit()

        placeholderLabel.font = self.font
        placeholderLabel.textColor = UIColor.lightGray
        placeholderLabel.tag = 100

        placeholderLabel.isHidden = self.text.characters.count > 0

        self.addSubview(placeholderLabel)
        self.resizePlaceholder()
        self.delegate = self
    }
}