Programs & Examples On #Server hardware

How many socket connections possible?

10,000? 70,000? is that all :)

FreeBSD is probably the server you want, Here's a little blog post about tuning it to handle 100,000 connections, its has had some interesting features like zero-copy sockets for some time now, along with kqueue to act as a completion port mechanism.

Solaris can handle 100,000 connections back in the last century!. They say linux would be better

The best description I've come across is this presentation/paper on writing a scalable webserver. He's not afraid to say it like it is :)

Same for software: the cretins on the application layer forced great innovations on the OS layer. Because Lotus Notes keeps one TCP connection per client open, IBM contributed major optimizations for the ”one process, 100.000 open connections” case to Linux

And the O(1) scheduler was originally created to score well on some irrelevant Java benchmark. The bottom line is that this bloat bene?ts all of us.

asp.net Button OnClick event not firing

i had the same problem did all changed the button and all above mentioned methods then I did a simple thing I was using two forms on a single page and form with in the form so I removed one and it worked :)

Best way to get whole number part of a Decimal number

By the way guys, (int)Decimal.MaxValue will overflow. You can't get the "int" part of a decimal because the decimal is too friggen big to put in the int box. Just checked... its even too big for a long (Int64).

If you want the bit of a Decimal value to the LEFT of the dot, you need to do this:

Math.Truncate(number)

and return the value as... A DECIMAL or a DOUBLE.

edit: Truncate is definitely the correct function!

PHP foreach loop through multidimensional array

<?php
$first = reset($arr_nav); // Get the first element
$last  = end($arr_nav);   // Get the last element
// Ensure that we have a first element and that it's an array
if(is_array($first)) { 
   $first['class'] = 'first';
}
// Ensure we have a last element and that it differs from the first
if(is_array($last) && $last !== $first) {
   $last['class'] = 'last';
}

Now you could just echo the class inside you html-generator. Would probably need some kind of check to ensure that the class is set, or provide a default empty class to the array.

Retrieving values from nested JSON Object

Try this, you can parse nested JSON

public static String getJsonValue(String jsonReq, String key) {
        JSONObject json = new JSONObject(jsonReq);
        boolean exists = json.has(key);
        Iterator<?> keys;
        String nextKeys;
        String val = "";
        if (!exists) {
            keys = json.keys();
            while (keys.hasNext()) {
                nextKeys = (String) keys.next();
                try {
                    if (json.get(nextKeys) instanceof JSONObject) {
                        return getJsonValue(json.getJSONObject(nextKeys).toString(), key);
                    } else if (json.get(nextKeys) instanceof JSONArray) {
                        JSONArray jsonArray = json.getJSONArray(nextKeys);
                        int i = 0;
                        if (i < jsonArray.length()) do {
                            String jsonArrayString = jsonArray.get(i).toString();
                            JSONObject innerJson = new JSONObject(jsonArrayString);
                            return getJsonValue(innerJson.toString(),key);
                        } while (i < jsonArray.length());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            val = json.get(key).toString();
        }
        return val;
    }

How to make google spreadsheet refresh itself every 1 minute?

If you're on the New Google Sheets, this is all you need to do, according to the docs:

change your recalculation setting to "On change and every minute" in your spreadsheet at File > Spreadsheet settings.

This will make the entire sheet update itself every minute, on the server side, regardless of whether you have the spreadsheet up in your browser or not.

If you're on the old Google Sheets, you'll want to add a cell with this formula to achieve the same functionality:

=GoogleClock()

EDIT to include old and new Google Sheets and change to =GoogleClock().

Store boolean value in SQLite

In SQLite the best you can do is use the integers 0 and 1 to represent false and true. You could declare the column type like this:

CREATE TABLE foo(mycolumn BOOLEAN NOT NULL CHECK (mycolumn IN (0,1)));

Omit the NOT NULL if you want to allow NULL in addition to 0 and 1.

The use of the type name BOOLEAN here is for readability, to SQLite it's just a type with NUMERIC affinity.

Note that CHECK constraints have been supported since SQLite 3.3.0 (2006).

Here are some example INSERTs that will work: (note how strings and floating point numbers are parsed as integers)

sqlite> INSERT INTO foo VALUES(0);
sqlite> INSERT INTO foo VALUES(1);
sqlite> INSERT INTO foo VALUES(0.0);
sqlite> INSERT INTO foo VALUES(1.0);
sqlite> INSERT INTO foo VALUES("0.0");
sqlite> INSERT INTO foo VALUES("1.0");
sqlite> select mycolumn, typeof(mycolumn) from foo;
0|integer
1|integer
0|integer
1|integer
0|integer
1|integer

and some that will fail:

sqlite> INSERT INTO foo VALUES("-1");
Error: constraint failed
sqlite> INSERT INTO foo VALUES(0.24);
Error: constraint failed
sqlite> INSERT INTO foo VALUES(100);
Error: constraint failed
sqlite> INSERT INTO foo VALUES(NULL);
Error: foo.mycolumn may not be NULL
sqlite> INSERT INTO foo VALUES("true");
Error: constraint failed
sqlite> INSERT INTO foo VALUES("false");
Error: constraint failed

JavaScript/jQuery - "$ is not defined- $function()" error

You must not have made jQuery available to your script.

Add this to the top of your file:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>

This issue is related to the jQuery/JavaScript file not added to the PHP/JSP/ASP file properly. This goes out and gets the jQuery code from the source. You could download that and reference it locally on the server which would be faster.

Or either one can directly link it to jQuery or GoogleCDN or MicrosoftCDN.

How do add jQuery to your webpage

Are PHP short tags acceptable to use?

One has to ask what the point of using short tags is.

Quicker to type

MDCore said:

<?= is far more convenient than typing <?php echo

Yes, it is. You save having to type 7 characters * X times throughout your scripts.

However, when a script takes an hour, or 10 hours, or more, to design, develop, and write, how relevant is the few seconds of time not typing those 7 chars here and there for the duration of the script?

Compared to the potential for some core, or all, of you scripts not working if short tags are not turned on, or are on but an update or someone changing the ini file/server config stops them working, other potentials.

The small benefit you gain doesn't comes close to outweighing the severity of the potential problems, that is your site not working, or worse, only parts of it not working and thus a headache to resolve.

Easier to read

This depends on familiarity.
I've always seen and used <?php echo. So while <?= is not hard to read, it's not familiar to me and thus not easier to read.

And with front end/back end developer split (as with most companies) would a front end developer working on those templates be more familiar knowing <?= is equal to "PHP open tag and echo"?
I would say most would be more comfortable with the more logical one. That is, a clear PHP open tag and then what is happening "echo" - <?php echo.

Risk assessment
Issue = entire site or core scripts fail to work;

The potential of issue is very low + severity of outcome is very high = high risk

Conclusion

You save a few seconds here and there not having to type a few chars, but risk a lot for it, and also likely lose readability as a result.

Front or back end coders familiar with <?= are more likely to understand <?php echo, as they're standard PHP things - standard <?php open tag and very well known "echo".
(Even front end coders should know "echo" or they simply wont be working on any code served by a framework).

Whereas the reverse is not as likely, someone is not likely to logically deduce that the equals sign on a PHP short tag is "echo".

How to get the mobile number of current sim card in real device?

You can use the TelephonyManager to do this:

TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); 
String number = tm.getLine1Number();

The documentation for getLine1Number() says this method will return null if the number is "unavailable", but it does not say when the number might be unavailable.

You'll need to give your application permission to make this query by adding the following to your Manifest:

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

(You shouldn't use TelephonyManager.getDefault() to get the TelephonyManager as that is a private undocumented API call and may change in future.)

How to Bootstrap navbar static to fixed on scroll?

Or you can change position of specific div using class name

$(document).scroll(function(e){
    var scrollTop = $(document).scrollTop();
    if(scrollTop > 0){
        //console.log(scrollTop);
        $('.header').css("position","fixed");
    } else {
         $('.header').css("position","relative");
    }
});

How to get HQ youtube thumbnails?

Depending on the resolution you need, you can use a different URL:

Default Thumbnail

http://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg

High Quality Thumbnail

http://img.youtube.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg

Medium Quality

http://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg

Standard Definition

http://img.youtube.com/vi/<insert-youtube-video-id-here>/sddefault.jpg

Maximum Resolution

http://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg

Note: it's a work-around if you don't want to use the YouTube Data API. Furthermore not all videos have the thumbnail images set, so the above method doesn’t work.

Github: Can I see the number of downloads for a repo?

11 years later...
Here's a small python3 snippet to retrieve the download count of the last 100 release assets:

import requests

owner = "twbs"
repo = "bootstrap"
h = {"Accept": "application/vnd.github.v3+json"}
u = f"https://api.github.com/repos/{owner}/{repo}/releases?per_page=100"
r = requests.get(u, headers=h).json()
r.reverse() # older tags first
for rel in r:
  if rel['assets']:
    tag = rel['tag_name']
    dls = rel['assets'][0]['download_count']
    pub = rel['published_at']
    print(f"Pub: {pub} | Tag: {tag} | Dls: {dls} ")

Pub: 2013-07-18T00:03:17Z | Tag: v1.2.0 | Dls: 1193 
Pub: 2013-08-19T21:20:59Z | Tag: v3.0.0 | Dls: 387786 
Pub: 2013-10-30T17:07:16Z | Tag: v3.0.1 | Dls: 102278 
Pub: 2013-11-06T21:58:55Z | Tag: v3.0.2 | Dls: 381136 
...
Pub: 2020-12-07T16:24:37Z | Tag: v5.0.0-beta1 | Dls: 93943 

Demo

How to get different colored lines for different plots in a single figure?

TL;DR No, it can't be done automatically. Yes, it is possible.

import matplotlib.pyplot as plt
my_colors = plt.rcParams['axes.prop_cycle']() # <<< note that we CALL the prop_cycle
fig, axes = plt.subplots(2,3)
for ax in axes.flatten(): ax.plot((0,1), (0,1), **next(my_colors))

enter image description here Each plot (axes) in a figure (figure) has its own cycle of colors — if you don't force a different color for each plot, all the plots share the same order of colors but, if we stretch a bit what "automatically" means, it can be done.


The OP wrote

[...] I have to identify each plot with a different color which should be automatically generated by [Matplotlib].

But... Matplotlib automatically generates different colors for each different curve

In [10]: import numpy as np
    ...: import matplotlib.pyplot as plt

In [11]: plt.plot((0,1), (0,1), (1,2), (1,0));
Out[11]:

enter image description here

So why the OP request? If we continue to read, we have

Can you please give me a method to put different colors for different plots in the same figure?

and it make sense, because each plot (each axes in Matplotlib's parlance) has its own color_cycle (or rather, in 2018, its prop_cycle) and each plot (axes) reuses the same colors in the same order.

In [12]: fig, axes = plt.subplots(2,3)

In [13]: for ax in axes.flatten():
    ...:     ax.plot((0,1), (0,1))

enter image description here

If this is the meaning of the original question, one possibility is to explicitly name a different color for each plot.

If the plots (as it often happens) are generated in a loop we must have an additional loop variable to override the color automatically chosen by Matplotlib.

In [14]: fig, axes = plt.subplots(2,3)

In [15]: for ax, short_color_name in zip(axes.flatten(), 'brgkyc'):
    ...:     ax.plot((0,1), (0,1), short_color_name)

enter image description here

Another possibility is to instantiate a cycler object

from cycler import cycler
my_cycler = cycler('color', ['k', 'r']) * cycler('linewidth', [1., 1.5, 2.])
actual_cycler = my_cycler()

fig, axes = plt.subplots(2,3)
for ax in axes.flat:
    ax.plot((0,1), (0,1), **next(actual_cycler))

enter image description here

Note that type(my_cycler) is cycler.Cycler but type(actual_cycler) is itertools.cycle.

How to resolve "Could not find schema information for the element/attribute <xxx>"?

Have you tried copying the schema file to the XML Schema Caching folder for VS? You can find the location of that folder by looking at VS Tools/Options/Test Editor/XML/Miscellaneous. Unfortunately, i don't know where's the schema file for the MS Enterprise Library 4.0.

Update: After installing MS Enterprise Library, it seems there's no .xsd file. However, there's a tool for editing the configuration - EntLibConfig.exe, which you can use to edit the configuration files. Also, if you add the proper config sections to your config file, VS should be able to parse the config file properly. (EntLibConfig will add these for you, or you can add them yourself). Here's an example for the loggingConfiguration section:

<configSections>
    <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</configSections>

You also need to add a reference to the appropriate assembly in your project.

Converting array to list in Java

Even shorter:

List<Integer> list = Arrays.asList(1, 2, 3, 4);

What is the benefit of zerofill in MySQL?

ZEROFILL

This essentially means that if the integer value 23 is inserted into an INT column with the width of 8 then the rest of the available position will be automatically padded with zeros.

Hence

23

becomes:

00000023

String Resource new line /n not possible?

I just faced this issue. didn't work on TextView with constraint parameters. Adding android:lines="2" seems to fix this.

Is calling destructor manually always a sign of bad design?

I have another situation where I think it is perfectly reasonable to call the destructor.

When writing a "Reset" type of method to restore an object to its initial state, it is perfectly reasonable to call the Destructor to delete the old data that is being reset.

class Widget
{
private: 
    char* pDataText { NULL  }; 
    int   idNumber  { 0     };

public:
    void Setup() { pDataText = new char[100]; }
    ~Widget()    { delete pDataText;          }

    void Reset()
    {
        Widget blankWidget;
        this->~Widget();     // Manually delete the current object using the dtor
        *this = blankObject; // Copy a blank object to the this-object.
    }
};

Edit and replay XHR chrome/firefox etc?

My two suggestions:

  1. Chrome's Postman plugin + the Postman Interceptor Plugin. More Info: Postman Capturing Requests Docs

  2. If you're on Windows then Telerik's Fiddler is an option. It has a composer option to replay http requests, and it's free.

How do I close a single buffer (out of many) in Vim?

Those using a buffer or tree navigation plugin, like Buffergator or NERDTree, will need to toggle these splits before destroying the current buffer - else you'll send your splits into wonkyville

I use:

"" Buffer Navigation                                                                                                                                                                                        
" Toggle left sidebar: NERDTree and BufferGator                                                                                                                                                             
fu! UiToggle()                                                                                                                                                                                              
  let b = bufnr("%")                                                                                                                                                                                        
  execute "NERDTreeToggle | BuffergatorToggle"                                                                                                                                                              
  execute ( bufwinnr(b) . "wincmd w" )                                                                                                                                                                      
  execute ":set number!"                                                                                                                                                                                    
endf                                                                                                                                                                                                        
map  <silent> <Leader>w  <esc>:call UiToggle()<cr>   

Where "NERDTreeToggle" in that list is the same as typing :NERDTreeToggle. You can modify this function to integrate with your own configuration.

CSS3's border-radius property and border-collapse:collapse don't mix. How can I use border-radius to create a collapsed table with rounded corners?

I tried a workaround using the pseudo elements :before and :after on the thead th:first-child and thead th:last-child

In combination with wrapping the table with a <div class="radius borderCCC">

table thead th:first-child:before{ 
    content:" ";
    position:absolute;
    top:-1px;
    left:-1px;
    width:15px;
    height:15px;
    border-left:1px solid #ccc;
    border-top:1px solid #ccc; 
    -webkit-border-radius:5px 0px 0px;
}
table thead th:last-child:after{ 
    content:" "; 
    position:absolute; 
    top:-1px;
    right:-1px; 
    width:15px;
    height:15px;
    border-right:1px solid #ccc;
    border-top:1px solid #ccc;
    -webkit-border-radius:0px 5px 0px 0px;
}

see jsFiddle

Works for me in chrome (13.0.782.215) Let me know if this works for you in other browsers.

What is base 64 encoding used for?

“Base64 encoding schemes are commonly used when there is a need to encode binary data that needs be stored and transferred over media that are designed to deal with textual data. This is to ensure that the data remains intact without modification during transport”(Wiki, 2017)

Example could be the following: you have a web service that accept only ASCII chars. You want to save and then transfer user’s data to some other location (API) but recipient want receive untouched data. Base64 is for that. . . The only downside is that base64 encoding will require around 33% more space than regular strings.

Another Example:: uenc = url encoded = aHR0cDovL2xvYy5tYWdlbnRvLmNvbS9hc2ljcy1tZW4tcy1nZWwta2F5YW5vLXhpaS5odG1s = http://loc.querytip.com/asics-men-s-gel-kayano-xii.html.

As you can see we can’t put char “/” in URL if we want to send last visited URL as parameter because we would break attribute/value rule for “MOD rewrite” – GET parameter.

A full example would be: “http://loc.querytip.com/checkout/cart/add/uenc/http://loc.magento.com/asics-men-s-gel-kayano-xii.html/product/93/

How to prevent Right Click option using jquery

I think this should help. Trick is to bind the contextmenu event.

<script type="text/javascript" language="javascript">
        $(function() {
            $(this).bind("contextmenu", function(e) {
                e.preventDefault();
            });
        }); 
</script>

Asynchronously load images with jQuery

$(function () {

    if ($('#hdnFromGLMS')[0].value == 'MB9262') {
        $('.clr').append('<img src="~/Images/CDAB_london.jpg">');
    }
    else
    {
        $('.clr').css("display", "none");
        $('#imgIreland').css("display", "block");
        $('.clrIrland').append('<img src="~/Images/Ireland-v1.jpg">');
    }
});

How to decode a QR-code image in (preferably pure) Python?

There is a library called BoofCV which claims to better than ZBar and other libraries.
Here are the steps to use that (any OS).

Pre-requisites:

  • Ensure JDK 14+ is installed and set in $PATH
  • pip install pyboof

Class to decode:

import os
import numpy as np
import pyboof as pb

pb.init_memmap() #Optional

class QR_Extractor:
    # Src: github.com/lessthanoptimal/PyBoof/blob/master/examples/qrcode_detect.py
    def __init__(self):
        self.detector = pb.FactoryFiducial(np.uint8).qrcode()
    
    def extract(self, img_path):
        if not os.path.isfile(img_path):
            print('File not found:', img_path)
            return None
        image = pb.load_single_band(img_path, np.uint8)
        self.detector.detect(image)
        qr_codes = []
        for qr in self.detector.detections:
            qr_codes.append({
                'text': qr.message,
                'points': qr.bounds.convert_tuple()
            })
        return qr_codes

Usage:

qr_scanner = QR_Extractor()
output = qr_scanner.extract('Your-Image.jpg')
print(output)

Tested and works on Python 3.8 (Windows & Ubuntu)

Excel CSV. file with more than 1,048,576 rows of data

You can use PowerPivot to work with files of up to 2GB, which will be enough for your needs.

How to copy and paste code without rich text formatting?

From websites, using Firefox, I use the CopyPlainText extension.

What is class="mb-0" in Bootstrap 4?

Bootstrap 4

It is used to create a bottom margin of 0 (margin-bottom:0). You can see more of the new spacing utility classes here: https://getbootstrap.com/docs/4.0/utilities/spacing/

Related: How do I use the Spacing Utility Classes on Bootstrap 4

Global variables in c#.net

You can create a base class in your application that inherits from System.Web.UI.Page. Let all your pages inherit from the newly created base class. Add a property or a variable to your base class with propected access modifier, so that it will be accessed from all your pages in the application.

How to use Python to login to a webpage and retrieve cookies for later usage?

import urllib, urllib2, cookielib

username = 'myuser'
password = 'mypassword'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()

resp.read() is the straight html of the page you want to open, and you can use opener to view any page using your session cookie.

Best Way to View Generated Source of Webpage?

Only thing i found is the BetterSource extension for Safari this will show you the manipulated source of the document only downside is nothing remotely like it for Firefox

What does SQL clause "GROUP BY 1" mean?

It means to group by the first column regardless of what it's called. You can do the same with ORDER BY.

Vue.js img src concatenate variable and text

just try

_x000D_
_x000D_
<img :src="require(`${imgPreUrl}img/logo.png`)">
_x000D_
_x000D_
_x000D_

How should I copy Strings in Java?

Since strings are immutable, both versions are safe. The latter, however, is less efficient (it creates an extra object and in some cases copies the character data).

With this in mind, the first version should be preferred.

How can I refresh or reload the JFrame?

You should use this code

this.setVisible(false); //this will close frame i.e. NewJFrame

new NewJFrame().setVisible(true); // Now this will open NewJFrame for you again and will also get refreshed 

How to install PyQt5 on Windows?

If you have python installed completely, it can save you the hassle. All you need to do is enter the following command in your respective shell:

pip install pyqt5

And contrary to popular belief, AS LONG AS YOU HAVE PIP INSTALLED, you can do this on virtually any OS... Hope this helped!

Using LIMIT within GROUP BY to get N results per group?

No, you can't LIMIT subqueries arbitrarily (you can do it to a limited extent in newer MySQLs, but not for 5 results per group).

This is a groupwise-maximum type query, which is not trivial to do in SQL. There are various ways to tackle that which can be more efficient for some cases, but for top-n in general you'll want to look at Bill's answer to a similar previous question.

As with most solutions to this problem, it can return more than five rows if there are multiple rows with the same rate value, so you may still need a quantity of post-processing to check for that.

C# "must declare a body because it is not marked abstract, extern, or partial"

You cannot provide your own implementation for the setter when using automatic properties. In other words, you should either do:

public int Hour { get;set;} // Automatic property, no implementation

or provide your own implementation for both the getter and setter, which is what you want judging from your example:

public int Hour  
{ 
    get { return hour; } 
    set 
    {
        if (value < MIN_HOUR)
        {
            hour = 0;
            MessageBox.Show("Hour value " + value.ToString() + " cannot be negative. Reset to " + MIN_HOUR.ToString(),
                    "Invalid Hour", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        else
        {
                //take the modulus to ensure always less than 24 hours
                //works even if the value is already within range, or value equal to 24
                hour = value % MAX_HOUR;
        }
     }
}

VBA setting the formula for a cell

If Cells(1, 1).Formula gives a 1004 error, like in my case, changes it to:

Cells(1, 1).FormulaLocal

Uncaught ReferenceError: jQuery is not defined

In my case, the error occurred because I was using the wrong version of jquery.

<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

I changed it to:

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

How to get overall CPU usage (e.g. 57%) on Linux

Take a look at cat /proc/stat

grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}'

EDIT please read comments before copy-paste this or using this for any serious work. This was not tested nor used, it's an idea for people who do not want to install a utility or for something that works in any distribution. Some people think you can "apt-get install" anything.

NOTE: this is not the current CPU usage, but the overall CPU usage in all the cores since the system bootup. This could be very different from the current CPU usage. To get the current value top (or similar tool) must be used.

Current CPU usage can be potentially calculated with:

awk '{u=$2+$4; t=$2+$4+$5; if (NR==1){u1=u; t1=t;} else print ($2+$4-u1) * 100 / (t-t1) "%"; }' \
<(grep 'cpu ' /proc/stat) <(sleep 1;grep 'cpu ' /proc/stat)

Convert output of MySQL query to utf8

You can use CAST and CONVERT to switch between different types of encodings. See: http://dev.mysql.com/doc/refman/5.0/en/charset-convert.html

SELECT column1, CONVERT(column2 USING utf8)
FROM my_table 
WHERE my_condition;

Make sure that the controller has a parameterless public constructor error

What's happening is that you're bitten by this problem. Basically, what happened is that you didn't register your controllers explicitly in your container. Unity tries to resolve unregistered concrete types for you, but because it can't resolve it (caused by an error in your configuration), it return null. It is forced to return null, because Web API forces it to do so due to the IDependencyResolver contract. Since Unity returns null, Web API will try to create the controller itself, but since it doesn't have a default constructor it will throw the "Make sure that the controller has a parameterless public constructor" exception. This exception message is misleading and doesn't explain the real cause.

You would have seen a much clearer exception message if you registered your controllers explicitly, and that's why you should always register all root types explicitly.

But of course, the configuration error comes from you adding the second constructor to your DbContext. Unity always tries to pick the constructor with the most arguments, but it has no idea how to resolve this particular constructor.

So the real cause is that you are trying to use Unity's auto-wiring capabilities to create the DbContext. DbContext is a special type that shouldn't be auto-wired. It is a framework type and you should therefore fallback to registering it using a factory delegate:

container.Register<DashboardDbContext>(
    new InjectionFactory(c => new DashboardDbContext())); 

Docker: adding a file from a parent directory

Unfortunately, (for practical and security reasons I guess), if you want to add/copy local content, it must be located under the same root path than the Dockerfile.

From the documentation:

The <src> path must be inside the context of the build; you cannot ADD ../something/something, because the first step of a docker build is to send the context directory (and subdirectories) to the docker daemon.

EDIT: There's now an option (-f) to set the path of your Dockerfile ; it can be used to achieve what you want, see @Boedy 's response.

Proper way to exit command line program?

if you do ctrl-z and then type exit it will close background applications.

Ctrl+Q is another good way to kill the application.

Capturing a single image from my webcam in Java or Python

Some time ago I wrote simple Webcam Capture API which can be used for that. The project is available on Github.

Example code:

Webcam webcam = Webcam.getDefault();
webcam.open();
try {
  ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));
} catch (IOException e) {
  e.printStackTrace();
} finally {
  webcam.close();
}

Turning a Comma Separated string into individual rows

DECLARE @id_list VARCHAR(MAX) = '1234,23,56,576,1231,567,122,87876,57553,1216'
DECLARE @table TABLE ( id VARCHAR(50) )
DECLARE @x INT = 0
DECLARE @firstcomma INT = 0
DECLARE @nextcomma INT = 0

SET @x = LEN(@id_list) - LEN(REPLACE(@id_list, ',', '')) + 1 -- number of ids in id_list

WHILE @x > 0
    BEGIN
        SET @nextcomma = CASE WHEN CHARINDEX(',', @id_list, @firstcomma + 1) = 0
                              THEN LEN(@id_list) + 1
                              ELSE CHARINDEX(',', @id_list, @firstcomma + 1)
                         END
        INSERT  INTO @table
        VALUES  ( SUBSTRING(@id_list, @firstcomma + 1, (@nextcomma - @firstcomma) - 1) )
        SET @firstcomma = CHARINDEX(',', @id_list, @firstcomma + 1)
        SET @x = @x - 1
    END

SELECT  *
FROM    @table

How to update-alternatives to Python 3 without breaking apt?

As I didn't want to break anything, I did this to be able to use newer versions of Python3 than Python v3.4 :

$ sudo update-alternatives --install /usr/local/bin/python3 python3 /usr/bin/python3.6 1
update-alternatives: using /usr/bin/python3.6 to provide /usr/local/bin/python3 (python3) in auto mode
$ sudo update-alternatives --install /usr/local/bin/python3 python3 /usr/bin/python3.7 2
update-alternatives: using /usr/bin/python3.7 to provide /usr/local/bin/python3 (python3) in auto mode
$ update-alternatives --list python3
/usr/bin/python3.6
/usr/bin/python3.7
$ sudo update-alternatives --config python3
There are 2 choices for the alternative python3 (providing /usr/local/bin/python3).

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /usr/bin/python3.7   2         auto mode
  1            /usr/bin/python3.6   1         manual mode
  2            /usr/bin/python3.7   2         manual mode

Press enter to keep the current choice[*], or type selection number: 1
update-alternatives: using /usr/bin/python3.6 to provide /usr/local/bin/python3 (python3) in manual mode
$ ls -l /usr/local/bin/python3 /etc/alternatives/python3 
lrwxrwxrwx 1 root root 18 2019-05-03 02:59:03 /etc/alternatives/python3 -> /usr/bin/python3.6*
lrwxrwxrwx 1 root root 25 2019-05-03 02:58:53 /usr/local/bin/python3 -> /etc/alternatives/python3*

Convert a number range to another range, maintaining ratio

There is a condition, when all of the values that you are checking are the same, where @jerryjvl's code would return NaN.

if (OldMin != OldMax && NewMin != NewMax):
    return (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin
else:
    return (NewMax + NewMin) / 2

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

Similar situation. It was working. Then, I started to include pytables. At first view, no reason to errors. I decided to use another function, that has a domain constraint (elipse) and received the following error:

TypeError: 'numpy.float64' object cannot be interpreted as an integer

or

TypeError: 'numpy.float64' object is not iterable

The crazy thing: the previous function I was using, no code changed, started to return the same error. My intermediary function, already used was:

def MinMax(x, mini=0, maxi=1)
    return max(min(x,mini), maxi)

The solution was avoid numpy or math:

def MinMax(x, mini=0, maxi=1)
    x = [x_aux if x_aux > mini else mini for x_aux in x]
    x = [x_aux if x_aux < maxi else maxi for x_aux in x]
    return max(min(x,mini), maxi)

Then, everything calm again. It was like one library possessed max and min!

Disable cross domain web security in Firefox

From this answer I've known a CORS Everywhere Firefox extension and it works for me. It creates MITM proxy intercepting headers to disable CORS. You can find the extension at addons.mozilla.org or here.

How to create a multi line body in C# System.Net.Mail.MailMessage

In case you dont need the message body in html, turn it off:

message.IsBodyHtml = false;

then use e.g:

message.Body = "First line" + Environment.NewLine + 
               "Second line";

but if you need to have it in html for some reason, use the html-tag:

message.Body = "First line <br /> Second line";

How can I store HashMap<String, ArrayList<String>> inside a list?

class Student{
    //instance variable or data members.

    Map<Integer, List<Object>> mapp = new HashMap<Integer, List<Object>>();
    Scanner s1 = new Scanner(System.in);
    String name = s1.nextLine();
    int regno ;
    int mark1;
    int mark2;
    int total;
    List<Object> list = new ArrayList<Object>();
    mapp.put(regno,list); //what wrong in this part?
    list.add(mark1);
    list.add(mark2);**
    //String mark2=mapp.get(regno)[2];
}

Why am I getting an OPTIONS request instead of a GET request?

I don't believe jQuery will just naturally do a JSONP request when given a URL like that. It will, however, do a JSONP request when you tell it what argument to use for a callback:

$.get("http://metaward.com/import/http://metaward.com/u/ptarjan?jsoncallback=?", function(data) {
     alert(data);
});

It's entirely up to the receiving script to make use of that argument (which doesn't have to be called "jsoncallback"), so in this case the function will never be called. But, since you stated you just want the script at metaward.com to execute, that would make it.

Adding elements to an xml file in C#

<Snippet name="abc"> 

name is an attribute, not an element. That's why it's failing. Look into using SetAttribute on the <Snippet> element.

root.SetAttribute("name", "name goes here");

is the code you need with what you have.

Regular expression to match any character being repeated more than 10 times

={10,}

matches = that is repeated 10 or more times.

How to get first 5 characters from string

You can use the substr function like this:

echo substr($myStr, 0, 5);

The second argument to substr is from what position what you want to start and third arguments is for how many characters you want to return.

What is the HTML5 equivalent to the align attribute in table cells?

you can use this code as replacement for table align

table 
{
    margin:auto;
}

Entity Framework Queryable async

Long story short,
IQueryable is designed to postpone RUN process and firstly build the expression in conjunction with other IQueryable expressions, and then interprets and runs the expression as a whole.
But ToList() method (or a few sort of methods like that), are ment to run the expression instantly "as is".
Your first method (GetAllUrlsAsync), will run imediately, because it is IQueryable followed by ToListAsync() method. hence it runs instantly (asynchronous), and returns a bunch of IEnumerables.
Meanwhile your second method (GetAllUrls), won't get run. Instead, it returns an expression and CALLER of this method is responsible to run the expression.

How to submit a form when the return key is pressed?

I think you should actually have a submit button or a submit image... Do you have a specific reason for using a "submit div"? If you just want custom styles I recommend <input type="image".... http://webdesign.about.com/cs/forms/a/aaformsubmit_2.htm

How do I extract the contents of an rpm?

Copy the .rpm file in a separate folder then run the following command $ yourfile.rpm | cpio -idmv

Javascript Cookie with no expiration date

YOU JUST CAN'T. There's no exact code to use for setting a forever cookie but an old trick will do, like current time + 10 years.

Just a note that any dates beyond January 2038 will doomed you for the cookies (32-bit int) will be deleted instantly. Wish for a miracle that that will be fixed in the near future. For 64-bit int, years around 2110 will be safe. As time goes by, software and hardware will change and may never adapt to older ones (the things we have now) so prepare the now for the future.

See Year 2038 problem

OracleCommand SQL Parameters Binding

string strConn = "Data Source=ORCL134; User ID=user; Password=psd;";

System.Data.OracleClient.OracleConnection con = newSystem.Data.OracleClient.OracleConnection(strConn);
    con.Open();

    System.Data.OracleClient.OracleCommand Cmd = 
        new System.Data.OracleClient.OracleCommand(
            "SELECT * FROM TBLE_Name WHERE ColumnName_year= :year", con);

//for oracle..it is :object_name and for sql it s @object_name
    Cmd.Parameters.Add(new System.Data.OracleClient.OracleParameter("year", (txtFinYear.Text).ToString()));

    System.Data.OracleClient.OracleDataAdapter da = new System.Data.OracleClient.OracleDataAdapter(Cmd);
    DataSet myDS = new DataSet();
    da.Fill(myDS);
    try
    {
        lblBatch.Text = "Batch Number is : " + Convert.ToString(myDS.Tables[0].Rows[0][19]);
        lblBatch.ForeColor = System.Drawing.Color.Green;
        lblBatch.Visible = true;
    }
    catch 
    {
        lblBatch.Text = "No Data Found for the Year : " + txtFinYear.Text;
        lblBatch.ForeColor = System.Drawing.Color.Red;
        lblBatch.Visible = true;   
    }
    da.Dispose();
    con.Close();

Blur effect on a div element

Try using this library: https://github.com/jakiestfu/Blur.js-II

That should do it for ya.

Java FileWriter how to write to next Line

out.write(c.toString());
out.newLine();

here is a simple solution, I hope it works

EDIT: I was using "\n" which was obviously not recommended approach, modified answer.

Custom ImageView with drop shadow

Here the Implementation of Paul Burkes answer:

public class ShadowImageView extends ImageView {

    public ShadowImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public ShadowImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ShadowImageView(Context context) {
        super(context);
    }

    private Paint createShadow() {
        Paint mShadow = new Paint();

        float radius = 10.0f;
        float xOffset = 0.0f;
        float yOffset = 2.0f;

        // color=black
        int color = 0xFF000000;
        mShadow.setShadowLayer(radius, xOffset, yOffset, color);


        return mShadow;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Paint mShadow = createShadow();
        Drawable d = getDrawable();
        if (d != null){
            setLayerType(LAYER_TYPE_SOFTWARE, mShadow);
            Bitmap bitmap = ((BitmapDrawable) getDrawable()).getBitmap();
            canvas.drawBitmap(bitmap, 0.0f, 0.0f, mShadow);
        } else {
            super.onDraw(canvas);
        }

    };

}

TODO: execute setLayerType(LAYER_TYPE_SOFTWARE, mShadow); only if API Level is > 10

how to insert datetime into the SQL Database table?

DateTime values should be inserted as if they are strings surrounded by single quotes:

'20100301'

SQL Server allows for many accepted date formats and it should be the case that most development libraries provide a series of classes or functions to insert datetime values properly. However, if you are doing it manually, it is important to distinguish the date format using DateFormat and to use generalized format:

Set DateFormat MDY --indicates the general format is Month Day Year

Insert Table( DateTImeCol )
Values( '2011-03-12' )

By setting the dateformat, SQL Server now assumes that my format is YYYY-MM-DD instead of YYYY-DD-MM.

SET DATEFORMAT

SQL Server also recognizes a generic format that is always interpreted the same way: YYYYMMDD e.g. 20110312.

If you are asking how to insert the current date and time using T-SQL, then I would recommend using the keyword CURRENT_TIMESTAMP. For example:

Insert Table( DateTimeCol )
Values( CURRENT_TIMESTAMP )

Send mail via CMD console

From Linux you can use 'swaks' which is available as an official packages on many distros including Debian/Ubuntu and Redhat/CentOS on EPEL:

swaks -f [email protected] -t [email protected] \
    --server mail.example.com

Convert Map to JSON using Jackson

You should prefer Object Mapper instead. Here is the link for the same : Object Mapper - Spring MVC way of Obect to JSON

How to install pip with Python 3?

Assuming you are in a highly restricted computer env (such as myself) without root access or ability to install packages...

I had never setup a fresh/standalone/raw/non-root instance of Python+virtualenv before this post. I had do quite a bit of Googling to make this work.

  1. Decide if you are using python (python2) or python3 and set your PATH correctly. (I am strictly a python3 user.) All commands below can substitute python3 for python if you are python2 user.
  2. wget https://pypi.python.org/packages/source/v/virtualenv/virtualenv-x.y.z.tar.gz
  3. tar -xzvf virtualenv-x.y.z.tar.gz
  4. python3 virtualenv-x.y.z/virtualenv.py --python $(which python3) /path/to/new/virtualenv
  5. source /path/to/new/virtualenv/bin/activate
    • Assumes you are using a Bourne-compatible shell, e.g., bash
    • Brilliantly, this virtualenv package includes a standalone version of pip and setuptools that are auto-magically installed into each new virtualenv. This solves the chicken and egg problem.
    • You may want to create an alias (or update your ~/.bashrc, etc.) for this final command to activate the python virtualenv during each login. It can be a pain to remember all these paths and commands.
  6. Check your version of python now: which python3 should give: /path/to/new/virtualenv/bin/python3
  7. Check pip is also available in the virtualenv via which pip... should give: /path/to/new/virtualenv/bin/pip

Then... pip, pip, pip!

Final tip to newbie Pythoneers: You don't think you need virtualenv when you start, but you will be happy to have it later. Helps with "what if" installation / upgrade scenarios for open source / shared packages.

Ref: https://virtualenv.pypa.io/en/latest/installation.html

PHP - Get array value with a numeric index

array_values() will do pretty much what you want:

$numeric_indexed_array = array_values($your_array);
// $numeric_indexed_array = array('bar', 'bin', 'ipsum');
print($numeric_indexed_array[0]); // bar

Is there a way to specify a default property value in Spring XML?

The default value can be followed with a : after the property key, e.g.

<property name="port" value="${my.server.port:8080}" />

Or in java code:

@Value("${my.server.port:8080}")
private String myServerPort;

See:

BTW, the Elvis Operator is only available within Spring Expression Language (SpEL),
e.g.: https://stackoverflow.com/a/37706167/537554

Start HTML5 video at a particular position when loading?

adjust video start and end time when using the video tag in html5;

http://www.yoursite.com/yourfolder/yourfile.mp4#t=5,15

where left of comma is start time in seconds, right of comma is end time in seconds. drop the comma and end time to effect the start time only.

Getting a list of values from a list of dicts

A very simple way to do it is:

list1=['']
j=0
for i in com_list:
    if j==0:
        list1[0]=(i['value'])
    else:
        list1.append(i['value'])
    j+=1

Output:

['apple', 'banana', 'cars']

Changing directory in Google colab (breaking out of the python interpreter)

If you want to use the cd or ls functions , you need proper identifiers before the function names ( % and ! respectively) use %cd and !ls to navigate

.

!ls    # to find the directory you're in ,
%cd ./samplefolder  #if you wanna go into a folder (say samplefolder)

or if you wanna go out of the current folder

%cd ../      

and then navigate to the required folder/file accordingly

Python: TypeError: cannot concatenate 'str' and 'int' objects

Apart from other answers, one could also use format()

print("a + b as integers: {}".format(c))

For example -

hours = 13
minutes = 32
print("Time elapsed - {} hours and {} minutes".format(hours, minutes))

will result in output - Time elapsed - 13 hours and 32 minutes

Check out docs for more information.

Is JavaScript a pass-by-reference or pass-by-value language?

Observation: If there isn't any way for an observer to examine the underlying memory of the engine, there is no way to determine whether an immutable value gets copied or a reference gets passed.

JavaScript is more or less agnostic to the underlying memory model. There is no such thing as a reference². JavaScript has values. Two variables can hold the same value (or more accurate: two environment records can bind the same value). The only type of values that can be mutated are objects through their abstract [[Get]] and [[Set]] operations. If you forget about computers and memory, this is all you need to describe JavaScript's behaviour, and it allows you to understand the specification.

 let a = { prop: 1 };
 let b = a; // a and b hold the same value
 a.prop = "test"; // The object gets mutated, can be observed through both a and b
 b = { prop: 2 }; // b holds now a different value

Now you might ask yourself how two variables can hold the same value on a computer. You might then look into the source code of a JavaScript engine and you'll most likely find something which a programmer of the language the engine was written in would call a reference.

So in fact you can say that JavaScript is "pass by value", whereas the value can be shared, and you can say that JavaScript is "pass by reference", which might be a useful logical abstraction for programmers from low level languages, or you might call the behaviour "call by sharing".

As there is no such thing as a reference in JavaScript, all of these are neither wrong nor on point. Therefore I don't think the answer is particularly useful to search for.

² The term Reference in the specification is not a reference in the traditional sense. It is a container for an object and the name of a property, and it is an intermediate value (e.g., a.b evaluates to Reference { value = a, name = "b" }). The term reference also sometimes appears in the specification in unrelated sections.

Jackson how to transform JsonNode to ArrayNode without casting?

I would assume at the end of the day you want to consume the data in the ArrayNode by iterating it. For that:

Iterator<JsonNode> iterator = datasets.withArray("datasets").elements();
while (iterator.hasNext()) 
        System.out.print(iterator.next().toString() + " "); 

or if you're into streams and lambda functions:

import com.google.common.collect.Streams;
Streams.stream(datasets.withArray("datasets").elements())
    .forEach( item -> System.out.print(item.toString()) )

How does C compute sin() and other math functions?

Use Taylor series and try to find relation between terms of the series so you don't calculate things again and again

Here is an example for cosinus:

double cosinus(double x, double prec)
{
    double t, s ;
    int p;
    p = 0;
    s = 1.0;
    t = 1.0;
    while(fabs(t/s) > prec)
    {
        p++;
        t = (-t * x * x) / ((2 * p - 1) * (2 * p));
        s += t;
    }
    return s;
}

using this we can get the new term of the sum using the already used one (we avoid the factorial and x2p)

explanation

Custom Python list sorting

It's documented here.

The sort() method takes optional arguments for controlling the comparisons.

cmp specifies a custom comparison function of two arguments (list items) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.

How do you get total amount of RAM the computer has?

If you happen to be using Mono, then you might be interested to know that Mono 2.8 (to be released later this year) will have a performance counter which reports the physical memory size on all the platforms Mono runs on (including Windows). You would retrieve the value of the counter using this code snippet:

using System;
using System.Diagnostics;

class app
{
   static void Main ()
   {
       var pc = new PerformanceCounter ("Mono Memory", "Total Physical Memory");
       Console.WriteLine ("Physical RAM (bytes): {0}", pc.RawValue);
   }
}

If you are interested in C code which provides the performance counter, it can be found here.

Sending credentials with cross-domain posts?

In jQuery 3 and perhaps earlier versions, the following simpler config also works for individual requests:

$.ajax(
        'https://foo.bar.com,
        {
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            success: successFunc
        }
    );

The full error I was getting in Firefox Dev Tools -> Network tab (in the Security tab for an individual request) was:

An error occurred during a connection to foo.bar.com.SSL peer was unable to negotiate an acceptable set of security parameters.Error code: SSL_ERROR_HANDSHAKE_FAILURE_ALERT

How to center cell contents of a LaTeX table whose columns have fixed widths?

You can use \centering with your parbox to do this.

More info here and here.

(Sorry for the Google cached link; the original one I had doesn't work anymore.)

How to clear variables in ipython?

In iPython you can remove a single variable like this:

del x

Execute a shell function with timeout

timeout is a command - so it is executing in a subprocess of your bash shell. Therefore it has no access to your functions defined in your current shell.

The command timeout is given is executed as a subprocess of timeout - a grand-child process of your shell.

You might be confused because echo is both a shell built-in and a separate command.

What you can do is put your function in it's own script file, chmod it to be executable, then execute it with timeout.

Alternatively fork, executing your function in a sub-shell - and in the original process, monitor the progress, killing the subprocess if it takes too long.

How to restart counting from 1 after erasing table in MS Access?

I am going to Necro this topic.

Starting around , you can execute Data Definition Queries (DDQ) through Macro's

Data Definition Query


ALTER TABLE <Table> ALTER COLUMN <ID_Field> COUNTER(1,1);

  1. Save the DDQ, with your values
  2. Create a Macro with the appropriate logic either before this or after.
  3. To execute this DDQ:
    • Add an Open Query action
    • Define the name of the DDQ in the Query Name field; View and Data Mode settings are not relevant and can leave the default values

WARNINGS!!!!

  1. This will reset the AutoNumber Counter to 1
  2. Any Referential Integrity will be summarily destroyed

Advice

  • Use this for Staging tables
    • these are tables that are never intended to persist the data they temporarily contain.
    • The data contained is only there until additional cleaning actions have been performed and stored in the appropriate table(s).
    • Once cleaning operations have been performed and the data is no longer needed, these tables are summarily purged of any data contained.
  • Import Tables
    • These are very similar to Staging Tables but tend to only have two columns: ID and RowValue
    • Since these are typically used to import RAW data from a general file format (TXT, RTF, CSV, XML, etc.), the data contained does not persist past the processing lifecycle

Build the full path filename in Python

If you are fortunate enough to be running Python 3.4+, you can use pathlib:

>>> from pathlib import Path
>>> dirname = '/home/reports'
>>> filename = 'daily'
>>> suffix = '.pdf'
>>> Path(dirname, filename).with_suffix(suffix)
PosixPath('/home/reports/daily.pdf')

Best way to replace multiple characters in a string?

>>> a = '&#'
>>> print a.replace('&', r'\&')
\&#
>>> print a.replace('#', r'\#')
&\#
>>> 

You want to use a 'raw' string (denoted by the 'r' prefixing the replacement string), since raw strings to not treat the backslash specially.

Eclipse error "ADB server didn't ACK, failed to start daemon"

ADB will often fail if there is a newline in adb_usb.ini. Remove it, restart it, and that will often solve the problem (at least for me anyway).

Convert array to string in NodeJS

You can also cast an array to a string like...

newStr = String(aa);

I also agree with Tor Valamo's answer, console.log should have no problem with arrays, no need to convert to a string unless you're debugging something or just curious.

CSS text-align not working

Change the rule on your <a> element from:

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
}?

to

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
    width:100%;
    text-align:center;
}?

Just add two new rules (width:100%; and text-align:center;). You need to make the anchor expand to take up the full width of the list item and then text-align center it.

jsFiddle example

Scp command syntax for copying a folder from local machine to a remote server

In stall PuTTY in our system and set the environment variable PATH Pointing to putty path. open the command prompt and move to putty folder. Using PSCP command

Please check this

Convert serial.read() into a useable string using Arduino?

Credit for this goes to magma. Great answer, but here it is using c++ style strings instead of c style strings. Some users may find that easier.

String string = "";
char ch; // Where to store the character read

void setup() {
    Serial.begin(9600);
    Serial.write("Power On");
}
    
boolean Comp(String par) {
    while (Serial.available() > 0) // Don't read unless
                                       // there you know there is data
    {
        ch = Serial.read(); // Read a character
        string += ch; // Add it
    }
    
    if (par == string) {
       string = "";
       return(true);
    }
    else {
       //dont reset string
       return(false);
    }
}
    
void loop()
{
    if (Comp("m1 on")) {
        Serial.write("Motor 1 -> Online\n");
    }
    if (Comp("m1 off")) {
        Serial.write("Motor 1 -> Offline\n");
    }
}

Remove all items from RecyclerView

ListView uses clear().

But, if you're just doing it for RecyclerView. First you have to clear your RecyclerView.Adapter with notifyItemRangeRemoved(0,size)

Then, only you recyclerView.removeAllViewsInLayout().

Getting the absolute path of the executable, using C#?

On my side, I used, with a form application:

String Directory = System.Windows.Forms.Application.StartupPath;

it takes the application startup path.

Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet."

My problem was that I tried to import a Django model before calling django.setup()

This worked for me:

import django
django.setup()

from myapp.models import MyModel

The above script is in the project root folder.

Symbol for any number of any characters in regex?

I would use .*. . matches any character, * signifies 0 or more occurrences. You might need a DOTALL switch to the regex to capture new lines with ..

how do I strip white space when grabbing text with jQuery?

Use the replace function in js:

var emailAdd = $(this).text().replace(/ /g,'');

That will remove all the spaces

If you want to remove the leading and trailing whitespace only, use the jQuery $.trim method :

var emailAdd = $.trim($(this).text());

MySql : Grant read only options?

A step by step guide I found here.

To create a read-only database user account for MySQL

At a UNIX prompt, run the MySQL command-line program, and log in as an administrator by typing the following command:

mysql -u root -p

Type the password for the root account. At the mysql prompt, do one of the following steps:

To give the user access to the database from any host, type the following command:

grant select on database_name.* to 'read-only_user_name'@'%' identified by 'password';

If the collector will be installed on the same host as the database, type the following command:

grant select on database_name.* to 'read-only_user_name' identified by 'password';

This command gives the user read-only access to the database from the local host only. If you know the host name or IP address of the host that the collector is will be installed on, type the following command:

grant select on database_name.* to 'read-only_user_name'@'host_name or IP_address' identified by 'password';

The host name must be resolvable by DNS or by the local hosts file. At the mysql prompt, type the following command:

flush privileges;

Type quit.

The following is a list of example commands and confirmation messages:

mysql> grant select on dbname.* to 'readonlyuser'@'%' identified 
by 'pogo$23';
Query OK, 0 rows affected (0.11 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
mysql> quit

How do I import other TypeScript files?

If you are looking to use modules and want it to compile to a single JavaScript file you can do the following:

tsc -out _compiled/main.js Main.ts

Main.ts

///<reference path='AnotherNamespace/ClassOne.ts'/>
///<reference path='AnotherNamespace/ClassTwo.ts'/>

module MyNamespace
{
    import ClassOne = AnotherNamespace.ClassOne;
    import ClassTwo = AnotherNamespace.ClassTwo;

    export class Main
    {
        private _classOne:ClassOne;
        private _classTwo:ClassTwo;

        constructor()
        {
            this._classOne = new ClassOne();
            this._classTwo = new ClassTwo();
        }
    }
}

ClassOne.ts

///<reference path='CommonComponent.ts'/>

module AnotherNamespace
{
    export class ClassOne
    {
        private _component:CommonComponent;

        constructor()
        {
            this._component = new CommonComponent();
        }
    }
}

CommonComponent.ts

module AnotherNamespace
{
    export class CommonComponent
    {
        constructor()
        {
        }
    }
}

You can read more here: http://www.codebelt.com/typescript/javascript-namespacing-with-typescript-internal-modules/

How to upload a file and JSON data in Postman?

If you need like Upload file in multipart using form data and send json data(Dto object) in same POST Request

Get yor JSON object as String in Controller and make it Deserialize by adding this line

ContactDto contactDto  = new ObjectMapper().readValue(yourJSONString, ContactDto.class);

Select All as default value for Multivalue parameter

Does not work if you have nulls.

You can get around this by modifying your select statement to plop something into nulls:

phonenumber = CASE
  WHEN (isnull(phonenumber, '')='') THEN '(blank)'
  ELSE phonenumber
END

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

You must add it to entryComponents, as specified in the docs.

@NgModule({
  imports: [
    // ...
  ],
  entryComponents: [
    DialogInvokingComponent, 
    DialogResultExampleDialog
  ],
  declarations: [
    DialogInvokingComponent,   
    DialogResultExampleDialog
  ],
  // ...
})

Here is a full example for an app module file with a dialog defined as entryComponents.

Two Decimal places using c#

Another way :

decimal.Round(decimalvalue, 2, MidpointRounding.AwayFromZero);

How to get input field value using PHP

Example of using PHP to get a value from a form:

Put this in foobar.php:

<html>
<body>
  <form action="foobar_submit.php" method="post">
    <input name="my_html_input_tag"  value="PILLS HERE"/>

    <input type="submit" name="my_form_submit_button" 
           value="Click here for penguins"/>

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

Read the above code so you understand what it is doing:

"foobar.php is an HTML document containing an HTML form. When the user presses the submit button inside the form, the form's action property is run: foobar_submit.php. The form will be submitted as a POST request. Inside the form is an input tag with the name "my_html_input_tag". It's default value is "PILLS HERE". That causes a text box to appear with text: 'PILLS HERE' on the browser. To the right is a submit button, when you click it, the browser url changes to foobar_submit.php and the below code is run.

Put this code in foobar_submit.php in the same directory as foobar.php:

<?php
  echo $_POST['my_html_input_tag'];
  echo "<br><br>";
  print_r($_POST); 
?>

Read the above code so you know what its doing:

The HTML form from above populated the $_POST superglobal with key/value pairs representing the html elements inside the form. The echo prints out the value by key: 'my_html_input_tag'. If the key is found, which it is, its value is returned: "PILLS HERE".

Then print_r prints out all the keys and values from $_POST so you can peek as to what else is in there.

The value of the input tag with name=my_html_input_tag was put into the $_POST and you retrieved it inside another PHP file.

HTML table with 100% width, with vertical scroll inside tbody

Adding a fixed width to td,th after making tbody & thead display block works perfectly and also we can use slimscroll plugin to make the scroll bar beautiful.

enter image description here

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
    <title> Scrollable table </title>_x000D_
    <style>_x000D_
        body {_x000D_
            font-family: sans-serif;_x000D_
            font-size: 0.9em;_x000D_
        }_x000D_
        table {_x000D_
            border-collapse: collapse;_x000D_
            border-bottom: 1px solid #ddd;_x000D_
        }_x000D_
        thead {_x000D_
            background-color: #333;_x000D_
            color: #fff;_x000D_
        }_x000D_
        thead,tbody {_x000D_
            display: block;_x000D_
        }_x000D_
        th,td {_x000D_
            padding: 8px 10px;_x000D_
            border: 1px solid #ddd;_x000D_
            width: 117px;_x000D_
            box-sizing: border-box;_x000D_
        }_x000D_
        tbody {_x000D_
            height: 160px;_x000D_
            overflow-y: scroll_x000D_
        }_x000D_
    </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
    <table class="example-table">_x000D_
        <thead>_x000D_
            <tr>_x000D_
                <th> Header 1 </th>_x000D_
                <th> Header 2 </th>_x000D_
                <th> Header 3 </th>_x000D_
                <th> Header 4 </th>_x000D_
            </tr>_x000D_
        </thead>_x000D_
        <tbody>_x000D_
            <tr>_x000D_
                <td> Row 1- Col 1 </td>_x000D_
                <td> Row 1- Col 2 </td>_x000D_
                <td> Row 1- Col 3 </td>_x000D_
                <td> Row 1- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 2- Col 1 </td>_x000D_
                <td> Row 2- Col 2 </td>_x000D_
                <td> Row 2- Col 3 </td>_x000D_
                <td> Row 2- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 3- Col 1 </td>_x000D_
                <td> Row 3- Col 2 </td>_x000D_
                <td> Row 3- Col 3 </td>_x000D_
                <td> Row 3- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 4- Col 1 </td>_x000D_
                <td> Row 4- Col 2 </td>_x000D_
                <td> Row 4- Col 3 </td>_x000D_
                <td> Row 4- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 5- Col 1 </td>_x000D_
                <td> Row 5- Col 2 </td>_x000D_
                <td> Row 5- Col 3 </td>_x000D_
                <td> Row 5- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 6- Col 1 </td>_x000D_
                <td> Row 6- Col 2 </td>_x000D_
                <td> Row 6- Col 3 </td>_x000D_
                <td> Row 6- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 7- Col 1 </td>_x000D_
                <td> Row 7- Col 2 </td>_x000D_
                <td> Row 7- Col 3 </td>_x000D_
                <td> Row 7- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 8- Col 1 </td>_x000D_
                <td> Row 8- Col 2 </td>_x000D_
                <td> Row 8- Col 3 </td>_x000D_
                <td> Row 8- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 9- Col 1 </td>_x000D_
                <td> Row 9- Col 2 </td>_x000D_
                <td> Row 9- Col 3 </td>_x000D_
                <td> Row 9- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 10- Col 1 </td>_x000D_
                <td> Row 10- Col 2 </td>_x000D_
                <td> Row 10- Col 3 </td>_x000D_
                <td> Row 10- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 11- Col 1 </td>_x000D_
                <td> Row 11- Col 2 </td>_x000D_
                <td> Row 11- Col 3 </td>_x000D_
                <td> Row 11- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 12- Col 1 </td>_x000D_
                <td> Row 12- Col 2 </td>_x000D_
                <td> Row 12- Col 3 </td>_x000D_
                <td> Row 12- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 13- Col 1 </td>_x000D_
                <td> Row 13- Col 2 </td>_x000D_
                <td> Row 13- Col 3 </td>_x000D_
                <td> Row 13- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 14- Col 1 </td>_x000D_
                <td> Row 14- Col 2 </td>_x000D_
                <td> Row 14- Col 3 </td>_x000D_
                <td> Row 14- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 15- Col 1 </td>_x000D_
                <td> Row 15- Col 2 </td>_x000D_
                <td> Row 15- Col 3 </td>_x000D_
                <td> Row 15- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 16- Col 1 </td>_x000D_
                <td> Row 16- Col 2 </td>_x000D_
                <td> Row 16- Col 3 </td>_x000D_
                <td> Row 16- Col 4 </td>_x000D_
            </tr>_x000D_
        </tbody>_x000D_
    </table>_x000D_
_x000D_
_x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jQuery-slimScroll/1.3.8/jquery.slimscroll.min.js"></script>_x000D_
    <script>_x000D_
        $('.example-table tbody').slimscroll({_x000D_
            height: '160px',_x000D_
            alwaysVisible: true,_x000D_
            color: '#333'_x000D_
        })_x000D_
    </script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Explanation of the UML arrows

If you are more of a MOOC person, one free course that I'd recommend that teaches you all the in and outs of most UML diagrams is this one from Udacity: https://www.udacity.com/course/software-architecture-design--ud821

Can Mockito stub a method without regard to the argument?

Another option is to rely on good old fashion equals method. As long as the argument in the when mock equals the argument in the code being tested, then Mockito will match the mock.

Here is an example.

public class MyPojo {

    public MyPojo( String someField ) {
        this.someField = someField;
    }

    private String someField;

    @Override
    public boolean equals( Object o ) {
        if ( this == o ) return true;
        if ( o == null || getClass() != o.getClass() ) return false;
        MyPojo myPojo = ( MyPojo ) o;
        return someField.equals( myPojo.someField );
    }

}

then, assuming you know what the value for someField will be, you can mock it like this.

when(fooDao.getBar(new MyPojo(expectedSomeField))).thenReturn(myFoo);

pros: This is more explicit then any matchers. As a reviewer of code, I keep an eye open for any in the code junior developers write, as it glances over their code's logic to generate the appropriate object being passed.

con: Sometimes the field being passed to the object is a random ID. For this case you cannot easily construct the expected argument object in your mock code.

Another possible approach is to use Mockito's Answer object that can be used with the when method. Answer lets you intercept the actual call and inspect the input argument and return a mock object. In the example below I am using any to catch any request to the method being mocked. But then in the Answer lambda, I can further inspect the Bazo argument... maybe to verify that a proper ID was passed to it. I prefer this over any by itself so that at least some inspection is done on the argument.

    Bar mockBar = //generate mock Bar.

    when(fooDao.getBar(any(Bazo.class))
    .thenAnswer(  ( InvocationOnMock invocationOnMock) -> {
        Bazo actualBazo = invocationOnMock.getArgument( 0 );

        //inspect the actualBazo here and thrw exception if it does not meet your testing requirements.
        return mockBar;
    } );

So to sum it all up, I like relying on equals (where the expected argument and actual argument should be equal to each other) and if equals is not possible (due to not being able to predict the actual argument's state), I'll resort to Answer to inspect the argument.

git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054

It's mentioned as SSL_ERROR_SYSCALL, errno 10054.

To resolve this SSL issue I went to .gitconfig file (which is located in c drive in my desktop) I changed sslverify to false and added my username and email id.

sslVerify = `false` //make sslVerify as false    
[user]
    name = `***<Enter your name>**`
    email = `**<Email Id>**`

Select multiple elements from a list

mylist[c(5,7,9)] should do it.

You want the sublists returned as sublists of the result list; you don't use [[]] (or rather, the function is [[) for that -- as Dason mentions in comments, [[ grabs the element.

How can I use custom fonts on a website?

Yes, there is a way. Its called custom fonts in CSS.Your CSS needs to be modified, and you need to upload those fonts to your website.

The CSS required for this is:

@font-face {
     font-family: Thonburi-Bold;
     src: url('pathway/Thonburi-Bold.otf'); 
}

How to initialize a list of strings (List<string>) with many string values

List<string> animals= new List<string>();
animals.Add("dog");
animals.Add("tiger");

Register DLL file on Windows Server 2008 R2

Error 0x80040154 is COM's REGDB_E_CLASSNOTREG, which means "Class not registered". Basically, a COM class is not declared in the installation registry.

If you get this error when trying to register a DLL, it may be possible that the registration code for this DLL is trying to instantiate another COM server (DLL or EXE) which is missing or not registered on this installation.

If you don't have access to the original DLL source, I would suggest to use SysInternal's Process Monitor tool to track COM registry lookups (there use to be a more simple RegMon tool but it may not work any more).

You should put a filter on the working process (here: Regsvr32.exe) to only capture what's interesting. Then you should look for queries on HKEY_CLASSES_ROOT\[a progid, a string] that fail (with the NAME_NOT_FOUND error for example), or queries on HKEY_CLASSES_ROOT\CLSID\[a guid] that fail.

PS: Unfortunately, there may be many thing that seem to fail on a perfectly working Windows system, so you'll have to study all errors carefully. Good luck :-)

How to create Custom Ratings bar in Android

For SVG RatingBar I used RatingBar custom Vector Drawables superimposing and the answer of erdomester here. This solution traverses all drawables inside SvgRatingBar view of your layout, so in RecyclerView it has an overhead.

SvgRatingBar.java:

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.VectorDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.graphics.drawable.shapes.Shape;
import android.os.Build;
import android.util.AttributeSet;
import android.view.Gravity;

import androidx.appcompat.graphics.drawable.DrawableWrapper;
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat;

import com.example.R; // Your R.java file for R.attr.ratingBarStyle.

public class SvgRatingBar extends androidx.appcompat.widget.AppCompatRatingBar {

    private Bitmap sampleTile;

    public SvgRatingBar(Context context) {
        this(context, null);
    }

    public SvgRatingBar(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.ratingBarStyle);
    }

    public SvgRatingBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        LayerDrawable drawable = (LayerDrawable) createTile(getProgressDrawable(), false);
        setProgressDrawable(drawable);
    }

    /**
     * Converts a drawable to a tiled version of itself. It will recursively
     * traverse layer and state list drawables.
     */
    @SuppressLint("RestrictedApi")
    private Drawable createTile(Drawable drawable, boolean clip) {
        if (drawable instanceof DrawableWrapper) {
            Drawable inner = ((DrawableWrapper) drawable).getWrappedDrawable();
            if (inner != null) {
                inner = createTile(inner, clip);
                ((DrawableWrapper) drawable).setWrappedDrawable(inner);
            }
        } else if (drawable instanceof LayerDrawable) {
            LayerDrawable background = (LayerDrawable) drawable;
            final int n = background.getNumberOfLayers();
            Drawable[] outDrawables = new Drawable[n];

            for (int i = 0; i < n; i++) {
                int id = background.getId(i);
                outDrawables[i] = createTile(background.getDrawable(i),
                        (id == android.R.id.progress || id == android.R.id.secondaryProgress));
            }
            LayerDrawable newBg = new LayerDrawable(outDrawables);

            for (int i = 0; i < n; i++) {
                newBg.setId(i, background.getId(i));
            }

            return newBg;

        } else if (drawable instanceof BitmapDrawable) {
            final BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            final Bitmap tileBitmap = bitmapDrawable.getBitmap();
            if (sampleTile == null) {
                sampleTile = tileBitmap;
            }

            final ShapeDrawable shapeDrawable = new ShapeDrawable(getDrawableShape());
            final BitmapShader bitmapShader = new BitmapShader(tileBitmap,
                    Shader.TileMode.REPEAT, Shader.TileMode.CLAMP);
            shapeDrawable.getPaint().setShader(bitmapShader);
            shapeDrawable.getPaint().setColorFilter(bitmapDrawable.getPaint().getColorFilter());
            return (clip) ? new ClipDrawable(shapeDrawable, Gravity.START,
                    ClipDrawable.HORIZONTAL) : shapeDrawable;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && drawable instanceof VectorDrawable) {
            return createTile(getBitmapDrawableFromVectorDrawable(drawable), clip);
        } else if (drawable instanceof VectorDrawableCompat) {
            // API 19 support.
            return createTile(getBitmapDrawableFromVectorDrawable(drawable), clip);
        }
        return drawable;
    }

    private BitmapDrawable getBitmapDrawableFromVectorDrawable(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
        return new BitmapDrawable(getResources(), bitmap);
    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (sampleTile != null) {
            final int width = sampleTile.getWidth() * getNumStars();
            setMeasuredDimension(resolveSizeAndState(width, widthMeasureSpec, 0),
                    getMeasuredHeight());
        }
    }

    private Shape getDrawableShape() {
        final float[] roundedCorners = new float[]{5, 5, 5, 5, 5, 5, 5, 5};
        return new RoundRectShape(roundedCorners, null, null);
    }
}

In your layout:

<com.example.common.control.SvgRatingBar
    android:id="@+id/rate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:minHeight="13dp"
    android:numStars="5"
    android:progressDrawable="@drawable/rating_bar"
    android:rating="3.5"
    android:stepSize="0.01"
    />

You also have to create rating_bar.xml with two SVG drawables:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@android:id/background"
        android:drawable="@drawable/ic_unfilled_star"
        />

    <item
        android:id="@android:id/secondaryProgress"
        android:drawable="@drawable/ic_unfilled_star"
        />

    <item
        android:id="@android:id/progress"
        android:drawable="@drawable/ic_filled_star"
        />

</layer-list>

enter image description here

If you see in Design/Split view only one star, refresh layout:

enter image description here

In Kotlin.

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapShader
import android.graphics.Canvas
import android.graphics.Shader
import android.graphics.drawable.*
import android.graphics.drawable.shapes.RoundRectShape
import android.os.Build
import android.util.AttributeSet
import android.view.Gravity
import androidx.appcompat.graphics.drawable.DrawableWrapper
import androidx.appcompat.widget.AppCompatRatingBar
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import com.example.R; // Your R.java file for R.attr.ratingBarStyle.

class SvgRatingBar @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null,
                                             defStyleAttr: Int = R.attr.ratingBarStyle) :
    AppCompatRatingBar(context, attrs, defStyleAttr) {

    private var sampleTile: Bitmap? = null
    private val roundedCorners = floatArrayOf(5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f)
    private val roundRectShape = RoundRectShape(roundedCorners, null, null)

    init {
        progressDrawable = createTile(progressDrawable, false) as LayerDrawable
    }

    /**
     * Converts a drawable to a tiled version of itself. It will recursively
     * traverse layer and state list drawables.
     */
    private fun createTile(drawable: Drawable, clip: Boolean): Drawable =
        when {
            drawable is DrawableWrapper -> {
                @SuppressLint("RestrictedApi")
                var inner = drawable.wrappedDrawable
                if (inner != null) {
                    inner = createTile(inner, clip)
                    @SuppressLint("RestrictedApi")
                    drawable.wrappedDrawable = inner
                }
                drawable
            }
            drawable is LayerDrawable -> {
                val n = drawable.numberOfLayers
                val outDrawables = arrayOfNulls<Drawable>(n)
                for (i in 0 until n) {
                    val id = drawable.getId(i)
                    outDrawables[i] = createTile(drawable.getDrawable(i),
                        id == android.R.id.progress || id == android.R.id.secondaryProgress)
                }
                val newBg = LayerDrawable(outDrawables)
                for (i in 0 until n) {
                    newBg.setId(i, drawable.getId(i))
                }
                newBg
            }
            drawable is BitmapDrawable -> {
                val tileBitmap = drawable.bitmap
                if (sampleTile == null) {
                    sampleTile = tileBitmap
                }
                val bitmapShader = BitmapShader(tileBitmap, Shader.TileMode.REPEAT,
                    Shader.TileMode.CLAMP)
                val shapeDrawable = ShapeDrawable(roundRectShape).apply {
                    paint.shader = bitmapShader
                    paint.colorFilter = drawable.paint.colorFilter
                }
                if (clip) ClipDrawable(shapeDrawable, Gravity.START, ClipDrawable.HORIZONTAL)
                else shapeDrawable
            }
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && drawable is VectorDrawable -> {
                createTile(getBitmapDrawableFromVectorDrawable(drawable), clip)
            }
            drawable is VectorDrawableCompat -> {
                // Pre-Lollipop support.
                createTile(getBitmapDrawableFromVectorDrawable(drawable), clip)
            }
            else -> drawable
        }

    private fun getBitmapDrawableFromVectorDrawable(drawable: Drawable): BitmapDrawable {
        val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight,
            Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        drawable.setBounds(0, 0, canvas.width, canvas.height)
        drawable.draw(canvas)
        return BitmapDrawable(resources, bitmap)
    }

    @Synchronized override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        if (sampleTile != null) {
            val width = sampleTile!!.width * numStars
            setMeasuredDimension(resolveSizeAndState(width, widthMeasureSpec, 0),
                measuredHeight)
        }
    }
}

How to present popover properly in iOS 8

Actually it is much simpler than that. In the storyboard you should make the viewcontroller you want to use as popover and make a viewcontroller class for it as usual. Make a segue as shown below from the object you want to open the popover, in this case the UIBarButton named "Config".

enter image description here

In the "mother viewcontroller" implement the UIPopoverPresentationControllerDelegate and the delegate method:

func popoverPresentationControllerDidDismissPopover(popoverPresentationController: UIPopoverPresentationController) {
    //do som stuff from the popover
}

Override the prepareForSeque method like this:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     //segue for the popover configuration window
    if segue.identifier == "yourSegueIdentifierForPopOver" {
        if let controller = segue.destinationViewController as? UIViewController {
            controller.popoverPresentationController!.delegate = self
            controller.preferredContentSize = CGSize(width: 320, height: 186)
        }
    }
}

And you're done. And you can now treat the popover view as any other view, ie. add fields and what not! And you get hold of the the content controller by using the popoverPresentationController.presentedViewController method in the UIPopoverPresentationController.

Also on an iPhone you would have to overwrite

func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {

        return UIModalPresentationStyle.none
    } 

formatFloat : convert float number to string

Try this

package main

import "fmt"
import "strconv"

func FloatToString(input_num float64) string {
    // to convert a float number to a string
    return strconv.FormatFloat(input_num, 'f', 6, 64)
}

func main() {
    fmt.Println(FloatToString(21312421.213123))
}

If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg

strconv.FormatFloat(input_num, 'f', -1, 64)

Personally I find fmt easier to use. (Playground link)

fmt.Printf("x = %.6f\n", 21312421.213123)

Or if you just want to convert the string

fmt.Sprintf("%.6f", 21312421.213123)

calling a java servlet from javascript

I really recommend you use jquery for the javascript calls and some implementation of JSR311 like jersey for the service layer, which would delegate to your controllers.

This will help you with all the underlying logic of handling the HTTP calls and your data serialization, which is a big help.

jQuery: checking if the value of a field is null (empty)

I would also trim the input field, cause a space could make it look like filled

if ($.trim($('#person_data[document_type]').val()) != '')
{

}

Implement Validation for WPF TextBoxes

You can additionally implement IDataErrorInfo as follows in the view model. If you implement IDataErrorInfo, you can do the validation in that instead of the setter of a particular property, then whenever there is a error, return an error message so that the text box which has the error gets a red box around it, indicating an error.

class ViewModel : INotifyPropertyChanged, IDataErrorInfo
{
    private string m_Name = "Type Here";
    public ViewModel()
    {
    }

    public string Name
    {
        get
        {
            return m_Name;
        }
        set
        {
            if (m_Name != value)
            {
                m_Name = value;
                OnPropertyChanged("Name");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public string Error
    {
        get { return "...."; }
    }

    /// <summary>
    /// Will be called for each and every property when ever its value is changed
    /// </summary>
    /// <param name="columnName">Name of the property whose value is changed</param>
    /// <returns></returns>
    public string this[string columnName]
    {
        get 
        {
            return Validate(columnName);
        }
    }

    private string Validate(string propertyName)
    {
        // Return error message if there is error on else return empty or null string
        string validationMessage = string.Empty;
        switch (propertyName)
        {
            case "Name": // property name
                // TODO: Check validiation condition
                validationMessage = "Error";
                break;
        }

        return validationMessage;
    }
}

And you have to set ValidatesOnDataErrors=True in the XAML in order to invoke the methods of IDataErrorInfo as follows:

<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />

Make install, but not to default directories?

If the package provides a Makefile.PL - one can use:

perl Makefile.PL PREFIX=/home/my/local/lib LIB=/home/my/local/lib
make
make test
make install

* further explanation: https://www.perlmonks.org/?node_id=564720

How to amend a commit without changing commit message (reusing the previous one)?

just to add some clarity, you need to stage changes with git add, then amend last commit:

git add /path/to/modified/files
git commit --amend --no-edit

This is especially useful for if you forgot to add some changes in last commit or when you want to add more changes without creating new commits by reusing the last commit.

How do I type a TAB character in PowerShell?

TAB has a specific meaning in PowerShell. It's for command completion. So if you enter "getch" and then type a TAB. It changes what you typed into "GetChildItem" (it corrects the case, even though that's unnecessary).

From your question, it looks like TAB completion and command completion would overload the TAB key. I'm pretty sure the PowerShell designers didn't want that.

Invalid syntax when using "print"?

They changed print in Python 3. In 2 it was a statement, now it is a function and requires parenthesis.

Here's the docs from Python 3.0.

Set initially selected item in Select list in Angular2

If you use

<select [ngModel]="object">
    <option *ngFor="let object of objects" [ngValue]="object">{{object.name}}</option>
</select>

You need to set the property object in you components class to the item from objects that you want to have pre-selected.

class MyComponent {
  object;
  objects = [{name: 'a'}, {name: 'b'}, {name: 'c'}];
  constructor() {
    this.object = this.objects[1];
  }
}

How to pass a type as a method parameter in Java

Oh, but that's ugly, non-object-oriented code. The moment you see "if/else" and "typeof", you should be thinking polymorphism. This is the wrong way to go. I think generics are your friend here.

How many types do you plan to deal with?

UPDATE:

If you're just talking about String and int, here's one way you might do it. Start with the interface XmlGenerator (enough with "foo"):

package generics;

public interface XmlGenerator<T>
{
   String getXml(T value);
}

And the concrete implementation XmlGeneratorImpl:

    package generics;

public class XmlGeneratorImpl<T> implements XmlGenerator<T>
{
    private Class<T> valueType;
    private static final int DEFAULT_CAPACITY = 1024;

    public static void main(String [] args)
    {
        Integer x = 42;
        String y = "foobar";

        XmlGenerator<Integer> intXmlGenerator = new XmlGeneratorImpl<Integer>(Integer.class);
        XmlGenerator<String> stringXmlGenerator = new XmlGeneratorImpl<String>(String.class);

        System.out.println("integer: " + intXmlGenerator.getXml(x));
        System.out.println("string : " + stringXmlGenerator.getXml(y));
    }

    public XmlGeneratorImpl(Class<T> clazz)
    {
        this.valueType = clazz;
    }

    public String getXml(T value)
    {
        StringBuilder builder = new StringBuilder(DEFAULT_CAPACITY);

        appendTag(builder);
        builder.append(value);
        appendTag(builder, false);

        return builder.toString();
    }

    private void appendTag(StringBuilder builder) { this.appendTag(builder, false); }

    private void appendTag(StringBuilder builder, boolean isClosing)
    {
        String valueTypeName = valueType.getName();
        builder.append("<").append(valueTypeName);
        if (isClosing)
        {
            builder.append("/");
        }
        builder.append(">");
    }
}

If I run this, I get the following result:

integer: <java.lang.Integer>42<java.lang.Integer>
string : <java.lang.String>foobar<java.lang.String>

I don't know if this is what you had in mind.

Fitting a histogram with python

Here is an example that uses scipy.optimize to fit a non-linear functions like a Gaussian, even when the data is in a histogram that isn't well ranged, so that a simple mean estimate would fail. An offset constant also would cause simple normal statistics to fail ( just remove p[3] and c[3] for plain gaussian data).

from pylab import *
from numpy import loadtxt
from scipy.optimize import leastsq

fitfunc  = lambda p, x: p[0]*exp(-0.5*((x-p[1])/p[2])**2)+p[3]
errfunc  = lambda p, x, y: (y - fitfunc(p, x))

filename = "gaussdata.csv"
data     = loadtxt(filename,skiprows=1,delimiter=',')
xdata    = data[:,0]
ydata    = data[:,1]

init  = [1.0, 0.5, 0.5, 0.5]

out   = leastsq( errfunc, init, args=(xdata, ydata))
c = out[0]

print "A exp[-0.5((x-mu)/sigma)^2] + k "
print "Parent Coefficients:"
print "1.000, 0.200, 0.300, 0.625"
print "Fit Coefficients:"
print c[0],c[1],abs(c[2]),c[3]

plot(xdata, fitfunc(c, xdata))
plot(xdata, ydata)

title(r'$A = %.3f\  \mu = %.3f\  \sigma = %.3f\ k = %.3f $' %(c[0],c[1],abs(c[2]),c[3]));

show()

Output:

A exp[-0.5((x-mu)/sigma)^2] + k 
Parent Coefficients:
1.000, 0.200, 0.300, 0.625
Fit Coefficients:
0.961231625289 0.197254597618 0.293989275502 0.65370344131

gaussian plot with fit

Can local storage ever be considered secure?

This is a really interesting article here. I'm considering implementing JS encryption for offering security when using local storage. It's absolutely clear that this will only offer protection if the device is stolen (and is implemented correctly). It won't offer protection against keyloggers etc. However this is not a JS issue as the keylogger threat is a problem of all applications, regardless of their execution platform (browser, native). As to the article "JavaScript Crypto Considered Harmful" referenced in the first answer, I have one criticism; it states "You could use SSL/TLS to solve this problem, but that's expensive and complicated". I think this is a very ambitious claim (and possibly rather biased). Yes, SSL has a cost, but if you look at the cost of developing native applications for multiple OS, rather than web-based due to this issue alone, the cost of SSL becomes insignificant.

My conclusion - There is a place for client-side encryption code, however as with all applications the developers must recognise it's limitations and implement if suitable for their needs, and ensuring there are ways of mitigating it's risks.

Peak-finding algorithm for Python/SciPy

For those not sure about which peak-finding algorithms to use in Python, here a rapid overview of the alternatives: https://github.com/MonsieurV/py-findpeaks

Wanting myself an equivalent to the MatLab findpeaks function, I've found that the detect_peaks function from Marcos Duarte is a good catch.

Pretty easy to use:

import numpy as np
from vector import vector, plot_peaks
from libs import detect_peaks
print('Detect peaks with minimum height and distance filters.')
indexes = detect_peaks.detect_peaks(vector, mph=7, mpd=2)
print('Peaks are: %s' % (indexes))

Which will give you:

detect_peaks results

How to run python script with elevated privilege on windows

Make sure you have python in path,if not,win key + r, type in "%appdata%"(without the qotes) open local directory, then go to Programs directory ,open python and then select your python version directory. Click on file tab and select copy path and close file explorer.

Then do win key + r again, type control and hit enter. search for environment variables. click on the result, you will get a window. In the bottom right corner click on environmental variables. In the system side find path, select it and click on edit. In the new window, click on new and paste the path in there. Click ok and then apply in the first window. Restart your PC. Then do win + r for the last time, type cmd and do ctrl + shift + enter. Grant the previliges and open file explorer, goto your script and copy its path. Go back into cmd , type in "python" and paste the path and hit enter. Done

Cannot authenticate into mongo, "auth fails"

This is kind of a specific case, but in case anyone gets here with my problem:

In MongoHQ, it'll show you a field called "password", but it's actually just the hash of the password. You'll have to add a new user and store the password elsewhere (because MongoHQ won't show it to you).

Pygame mouse clicking detection

The MOUSEBUTTONDOWN event occurs once when you click the mouse button and the MOUSEBUTTONUP event occurs once when the mouse button is released. The pygame.event.Event() object has two attributes that provide information about the mouse event. pos is a tuple that stores the position that was clicked. button stores the button that was clicked. Each mouse button is associated a value. For instance the value of the attributes is 1, 2, 3, 4, 5 for the left mouse button, middle mouse button, right mouse button, mouse wheel up respectively mouse wheel down. When multiple keys are pressed, multiple mouse button events occur. Further explanations can be found in the documentation of the module pygame.event.

Use the rect attribute of the pygame.sprite.Sprite object and the collidepoint method to see if the Sprite was clicked. Pass the list of events to the update method of the pygame.sprite.Group so that you can process the events in the Sprite class:

class SpriteObject(pygame.sprite.Sprite):
    # [...]

    def update(self, event_list):

        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if self.rect.collidepoint(event.pos):
                    # [...]

my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)

# [...]

run = True
while run:
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False 

    group.update(event_list)

    # [...]

Minimal example: repl.it/@Rabbid76/PyGame-MouseClick

import pygame

class SpriteObject(pygame.sprite.Sprite):
    def __init__(self, x, y, color):
        super().__init__() 
        self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.original_image, color, (25, 25), 25)
        self.click_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.click_image, color, (25, 25), 25)
        pygame.draw.circle(self.click_image, (255, 255, 255), (25, 25), 25, 4)
        self.image = self.original_image 
        self.rect = self.image.get_rect(center = (x, y))
        self.clicked = False

    def update(self, event_list):
        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if self.rect.collidepoint(event.pos):
                    self.clicked = not self.clicked

        self.image = self.click_image if self.clicked else self.original_image

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
    SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
    SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
    SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
    SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])

run = True
while run:
    clock.tick(60)
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False 

    group.update(event_list)

    window.fill(0)
    group.draw(window)
    pygame.display.flip()

pygame.quit()
exit()

See further Creating multiple sprites with different update()'s from the same sprite class in Pygame


The current position of the mouse can be determined via pygame.mouse.get_pos(). The return value is a tuple that represents the x and y coordinates of the mouse cursor. pygame.mouse.get_pressed() returns a list of Boolean values ??that represent the state (True or False) of all mouse buttons. The state of a button is True as long as a button is held down. When multiple buttons are pressed, multiple items in the list are True. The 1st, 2nd and 3rd elements in the list represent the left, middle and right mouse buttons.

Detect evaluate the mouse states in the Update method of the pygame.sprite.Sprite object:

class SpriteObject(pygame.sprite.Sprite):
    # [...]

    def update(self, event_list):

        mouse_pos = pygame.mouse.get_pos()
        mouse_buttons = pygame.mouse.get_pressed()

        if  self.rect.collidepoint(mouse_pos) and any(mouse_buttons):
            # [...]

my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)

# [...]

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    group.update(event_list)

    # [...]

Minimal example: repl.it/@Rabbid76/PyGame-MouseHover

import pygame

class SpriteObject(pygame.sprite.Sprite):
    def __init__(self, x, y, color):
        super().__init__() 
        self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.original_image, color, (25, 25), 25)
        self.hover_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.hover_image, color, (25, 25), 25)
        pygame.draw.circle(self.hover_image, (255, 255, 255), (25, 25), 25, 4)
        self.image = self.original_image 
        self.rect = self.image.get_rect(center = (x, y))
        self.hover = False

    def update(self):
        mouse_pos = pygame.mouse.get_pos()
        mouse_buttons = pygame.mouse.get_pressed()

        #self.hover = self.rect.collidepoint(mouse_pos)
        self.hover = self.rect.collidepoint(mouse_pos) and any(mouse_buttons)

        self.image = self.hover_image if self.hover else self.original_image

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
    SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
    SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
    SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
    SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 

    group.update()

    window.fill(0)
    group.draw(window)
    pygame.display.flip()

pygame.quit()
exit()

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

Technically, there is no difference between a class and a case class -- even if the compiler does optimize some stuff when using case classes. However, a case class is used to do away with boiler plate for a specific pattern, which is implementing algebraic data types.

A very simple example of such types are trees. A binary tree, for instance, can be implemented like this:

sealed abstract class Tree
case class Node(left: Tree, right: Tree) extends Tree
case class Leaf[A](value: A) extends Tree
case object EmptyLeaf extends Tree

That enable us to do the following:

// DSL-like assignment:
val treeA = Node(EmptyLeaf, Leaf(5))
val treeB = Node(Node(Leaf(2), Leaf(3)), Leaf(5))

// On Scala 2.8, modification through cloning:
val treeC = treeA.copy(left = treeB.left)

// Pretty printing:
println("Tree A: "+treeA)
println("Tree B: "+treeB)
println("Tree C: "+treeC)

// Comparison:
println("Tree A == Tree B: %s" format (treeA == treeB).toString)
println("Tree B == Tree C: %s" format (treeB == treeC).toString)

// Pattern matching:
treeA match {
  case Node(EmptyLeaf, right) => println("Can be reduced to "+right)
  case Node(left, EmptyLeaf) => println("Can be reduced to "+left)
  case _ => println(treeA+" cannot be reduced")
}

// Pattern matches can be safely done, because the compiler warns about
// non-exaustive matches:
def checkTree(t: Tree) = t match {
  case Node(EmptyLeaf, Node(left, right)) =>
  // case Node(EmptyLeaf, Leaf(el)) =>
  case Node(Node(left, right), EmptyLeaf) =>
  case Node(Leaf(el), EmptyLeaf) =>
  case Node(Node(l1, r1), Node(l2, r2)) =>
  case Node(Leaf(e1), Leaf(e2)) =>
  case Node(Node(left, right), Leaf(el)) =>
  case Node(Leaf(el), Node(left, right)) =>
  // case Node(EmptyLeaf, EmptyLeaf) =>
  case Leaf(el) =>
  case EmptyLeaf =>
}

Note that trees construct and deconstruct (through pattern match) with the same syntax, which is also exactly how they are printed (minus spaces).

And they can also be used with hash maps or sets, since they have a valid, stable hashCode.

SVN Error: Commit blocked by pre-commit hook (exit code 1) with output: Error: n/a (6)

SOLUTION for WORDPRESS PLUGINS:

I think, get_option() returns FALSE (instead of EMPTY). So, check your plugin. Instead of:

if (empty(get_option('smth')))

there should be:

if (!get_option('smth'))

Changing case in Vim

Visual select the text, then U for uppercase or u for lowercase. To swap all casing in a visual selection, press ~ (tilde).

Without using a visual selection, gU<motion> will make the characters in motion uppercase, or use gu<motion> for lowercase.

For more of these, see Section 3 in Vim's change.txt help file.

How can I interrupt a running code in R with a keyboard command?

Self Answer (pretty much summary of other's comments and answers):

  • In RStudio, Esc works, on windows, Mac, and ubuntu (and I would guess on other linux distributions as well).

  • If the process is ran in say ubuntu shell (and this is not R specific), for example using:

    Rscript my_file.R
    

    Ctrl + c kills the process

    Ctrl + z suspends the process

  • Within R shell, Ctrl + C kills helps you escape it

How to get the host name of the current machine as defined in the Ansible hosts file?

This is an alternative:

- name: Install this only for local dev machine
  pip: name=pyramid
  delegate_to: localhost

How do I get the project basepath in CodeIgniter

Obviously you mean the baseurl. If so:

base url: URL to your CodeIgniter root. Typically this will be your base URL, | WITH a trailing slash.

Root in codeigniter specifically means that the position where you can append your controller to your url.

For example, if the root is localhost/ci_installation/index.php/, then to access the mycont controller you should go to localhost/ci_installation/index.php/mycont.

So, instead of writing such a long link you can (after loading "url" helper) , replace the term localhost/ci_installation/index.php/ by base_url() and this function will return the same string url.

NOTE: if you hadn't appended index.php/ to your base_url in your config.php, then if you use base_url(), it will return something like that localhost/ci_installation/mycont. And that will not work, because you have to access your controllers from index.php, instead of that you can place a .htaccess file to your codeigniter installation position. Cope that the below code to it:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /imguplod/index.php/$1 [L]

And it should work :)

Return the most recent record from ElasticSearch index

the _timestamp didn't work out for me,

this query does work for me:

(as in mconlin's answer)

{
  "query": {
    "match_all": {}
  },
  "size": "1",
  "sort": [
    {
      "@timestamp": {
        "order": "desc"
      }
    }
  ]
}

Could be trivial but the _timestamp answer didn't gave an error but not a good result either...

Hope to help someone...

(kibana/elastic 5.0.4)

S.

"Untrusted App Developer" message when installing enterprise iOS Application

Today, I was testing this with iOS 9 Beta and found the solution.

To solve it, go to:

  1. Settings -> General -> Profiles [Device Management on iOS 10]
  2. Under ENTERPRISE APP, choose your current developer account name.
  3. Tap Trust "Your developer account name"
  4. Tap "Trust" in pop up.
  5. Done

C - determine if a number is prime

Using Sieve of Eratosthenes, computation is quite faster compare to "known-wide" prime numbers algorithm.

By using pseudocode from it's wiki (https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes), I be able to have the solution on C#.

public bool IsPrimeNumber(int val) {
    // Using Sieve of Eratosthenes.
    if (val < 2)
    {
        return false;
    }

    // Reserve place for val + 1 and set with true.
    var mark = new bool[val + 1];
    for(var i = 2; i <= val; i++)
    {
        mark[i] = true;
    }

    // Iterate from 2 ... sqrt(val).
    for (var i = 2; i <= Math.Sqrt(val); i++)
    {
        if (mark[i])
        {
            // Cross out every i-th number in the places after i (all the multiples of i).
            for (var j = (i * i); j <= val; j += i)
            {
                mark[j] = false;
            }
        }
    }

    return mark[val];
}

IsPrimeNumber(1000000000) takes 21s 758ms.

NOTE: Value might vary depend on hardware specifications.

GitHub README.md center image

It works for me on github

<p align="center"> 
<img src="...">
</p>

AngularJS $http, CORS and http authentication

No you don't have to put credentials, You have to put headers on client side eg:

 $http({
        url: 'url of service',
        method: "POST",
        data: {test :  name },
        withCredentials: true,
        headers: {
                    'Content-Type': 'application/json; charset=utf-8'
        }
    });

And and on server side you have to put headers to this is example for nodejs:

/**
 * On all requests add headers
 */
app.all('*', function(req, res,next) {


    /**
     * Response settings
     * @type {Object}
     */
    var responseSettings = {
        "AccessControlAllowOrigin": req.headers.origin,
        "AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name",
        "AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
        "AccessControlAllowCredentials": true
    };

    /**
     * Headers
     */
    res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
    res.header("Access-Control-Allow-Origin",  responseSettings.AccessControlAllowOrigin);
    res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
    res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);

    if ('OPTIONS' == req.method) {
        res.send(200);
    }
    else {
        next();
    }


});

How do I protect javascript files?

As I said in the comment I left on gion_13 answer before (please read), you really can't. Not with javascript.

If you don't want the code to be available client-side (= stealable without great efforts), my suggestion would be to make use of PHP (ASP,Python,Perl,Ruby,JSP + Java-Servlets) that is processed server-side and only the results of the computation/code execution are served to the user. Or, if you prefer, even Flash or a Java-Applet that let client-side computation/code execution but are compiled and thus harder to reverse-engine (not impossible thus).

Just my 2 cents.

How to view .img files?

OSFMount , MagicDisc , Gizmo Director/Gizmo Drive , The Takeaway .

All these work well on .img files

How to add and remove item from array in components in Vue 2

You can use Array.push() for appending elements to an array.

For deleting, it is best to use this.$delete(array, index) for reactive objects.

Vue.delete( target, key ): Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.

https://vuejs.org/v2/api/#Vue-delete

Getter and Setter?

Why use getters and setters?

  1. Scalability: It's easier refactor a getter than search all the var assignments in a project code.
  2. Debugging: You can put breakpoints at setters and getters.
  3. Cleaner: Magic functions are not good solution for writting less, your IDE will not suggest the code. Better use templates for fast-writting getters.

direct assignment and getters/setters

How to create user for a db in postgresql?

Create the user with a password :

http://www.postgresql.org/docs/current/static/sql-createuser.html

CREATE USER name [ [ WITH ] option [ ... ] ]

where option can be:

      SUPERUSER | NOSUPERUSER
    | CREATEDB | NOCREATEDB
    | CREATEROLE | NOCREATEROLE
    | CREATEUSER | NOCREATEUSER
    | INHERIT | NOINHERIT
    | LOGIN | NOLOGIN
    | REPLICATION | NOREPLICATION
    | CONNECTION LIMIT connlimit
    | [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password'
    | VALID UNTIL 'timestamp'
    | IN ROLE role_name [, ...]
    | IN GROUP role_name [, ...]
    | ROLE role_name [, ...]
    | ADMIN role_name [, ...]
    | USER role_name [, ...]
    | SYSID uid

Then grant the user rights on a specific database :

http://www.postgresql.org/docs/current/static/sql-grant.html

Example :

grant all privileges on database db_name to someuser;

Copy directory contents into a directory with python

from subprocess import call

def cp_dir(source, target):
    call(['cp', '-a', source, target]) # Linux

cp_dir('/a/b/c/', '/x/y/z/')

It works for me. Basically, it executes shell command cp.

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

You define var scatterSeries = [];, and then try to parse it as a json string at console.info(JSON.parse(scatterSeries)); which obviously fails. The variable is converted to an empty string, which causes an "unexpected end of input" error when trying to parse it.

In Python, how do I read the exif data for an image?

You can also use the ExifRead module:

import exifread
# Open image file for reading (binary mode)
f = open(path_name, 'rb')

# Return Exif tags
tags = exifread.process_file(f)

Get folder name of the file in Python

you can use pathlib

from pathlib import Path
Path(r"C:\folder1\folder2\filename.xml").parts[-2]

The output of the above was this:

'folder2'

How to Use UTF-8 Collation in SQL Server database?

Two UDF to deal with UTF-8 in T-SQL:

CREATE Function UcsToUtf8(@src nvarchar(MAX)) returns varchar(MAX) as
begin
    declare @res varchar(MAX)='', @pi char(8)='%[^'+char(0)+'-'+char(127)+']%', @i int, @j int
    select @i=patindex(@pi,@src collate Latin1_General_BIN)
    while @i>0
    begin
        select @j=unicode(substring(@src,@i,1))
        if @j<0x800     select @res=@res+left(@src,@i-1)+char((@j&1984)/64+192)+char((@j&63)+128)
        else            select @res=@res+left(@src,@i-1)+char((@j&61440)/4096+224)+char((@j&4032)/64+128)+char((@j&63)+128)
        select @src=substring(@src,@i+1,datalength(@src)-1), @i=patindex(@pi,@src collate Latin1_General_BIN)
    end
    select @res=@res+@src
    return @res
end

CREATE Function Utf8ToUcs(@src varchar(MAX)) returns nvarchar(MAX) as
begin
    declare @i int, @res nvarchar(MAX)=@src, @pi varchar(18)
    select @pi='%[à-ï][€-¿][€-¿]%',@i=patindex(@pi,@src collate Latin1_General_BIN)
    while @i>0 select @res=stuff(@res,@i,3,nchar(((ascii(substring(@src,@i,1))&31)*4096)+((ascii(substring(@src,@i+1,1))&63)*64)+(ascii(substring(@src,@i+2,1))&63))), @src=stuff(@src,@i,3,'.'), @i=patindex(@pi,@src collate Latin1_General_BIN)
    select @pi='%[Â-ß][€-¿]%',@i=patindex(@pi,@src collate Latin1_General_BIN)
    while @i>0 select @res=stuff(@res,@i,2,nchar(((ascii(substring(@src,@i,1))&31)*64)+(ascii(substring(@src,@i+1,1))&63))), @src=stuff(@src,@i,2,'.'),@i=patindex(@pi,@src collate Latin1_General_BIN)
    return @res
end

What is the difference between a static and const variable?

static means local for compilation unit (i.e. a single C++ source code file), or in other words it means it is not added to a global namespace. you can have multiple static variables in different c++ source code files with the same name and no name conflicts.

const is just constant, meaning can't be modified.

How do you reindex an array in PHP but with indexes starting from 1?

You can reindex an array so the new array starts with an index of 1 like this;

$arr = array(
  '2' => 'red',
  '1' => 'green',
  '0' => 'blue',
);

$arr1 = array_values($arr);   // Reindex the array starting from 0.
array_unshift($arr1, '');     // Prepend a dummy element to the start of the array.
unset($arr1[0]);              // Kill the dummy element.

print_r($arr);
print_r($arr1);

The output from the above is;

Array
(
    [2] => red
    [1] => green
    [0] => blue
)
Array
(
    [1] => red
    [2] => green
    [3] => blue
)

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

I installed webapi with it via the helppages nuget package. That package replaced most of the asp.net mvc 4 binaries with beta versions which didn't work well together with the rest of the project. Fix was to restore the original mvc 4 dll's and all was good.

How to run python script on terminal (ubuntu)?

Save your python file in a spot where you will be able to find it again. Then navigate to that spot using the command line (cd /home/[profile]/spot/you/saved/file) or go to that location with the file browser. If you use the latter, right click and select "Open In Terminal." When the terminal opens, type "sudo chmod +x Yourfilename." After entering your password, type "python ./Yourfilename" which will open your python file in the command line. Hope this helps!

Running Linux Mint

LINQ: Select where object does not contain items from list

In general, you're looking for the "Except" extension.

var rejectStatus = GenerateRejectStatuses();
var fullList = GenerateFullList();
var rejectList = fullList.Where(i => rejectStatus.Contains(i.Status));
var filteredList = fullList.Except(rejectList);

In this example, GenerateRegectStatuses() should be the list of statuses you wish to reject (or in more concrete terms based on your example, a List<int> of IDs)

Setting Remote Webdriver to run tests in a remote computer using Java

  • First you need to create HubNode(Server) and start the HubNode(Server) from command Line/prompt using Java: -jar selenium-server-standalone-2.44.0.jar -role hub
  • Then bind the node/Client to this Hub using Hub machines IPAddress or Name with any port number >1024. For Node Machine for example: Java -jar selenium-server-standalone-2.44.0.jar -role webdriver -hub http://HubmachineIPAddress:4444/grid/register -port 5566

One more thing is that whenever we use Internet Explore or Google Chrome we need to set: System.setProperty("webdriver.ie.driver",path);

Eclipse IDE for Java - Full Dark Theme

Eclipse uses native OS controls for most UI aspects (buttons, menus, lists, etc.). That's where colors for most of the IDE come from. The first step in making a "dark IDE" is to modify your OS color theme. Then you can add the color themes plugin to complete the look.

Cannot make a static reference to the non-static method fxn(int) from the type Two

You can't access the method fxn since it's not static. Static methods can only access other static methods directly. If you want to use fxn in your main method you need to:

...
Two two = new Two();
x = two.fxn(x)
...

That is, make a Two-Object and call the method on that object.

...or make the fxn method static.

MavenError: Failed to execute goal on project: Could not resolve dependencies In Maven Multimodule project

In my case I forgot it was packaging conflict jar vs pom. I forgot to write

<packaging>pom</packaging>

In every child pom.xml file

Passing multiple values for same variable in stored procedure

You will need to do a couple of things to get this going, since your parameter is getting multiple values you need to create a Table Type and make your store procedure accept a parameter of that type.

Split Function Works Great when you are getting One String containing multiple values but when you are passing Multiple values you need to do something like this....

TABLE TYPE

CREATE TYPE dbo.TYPENAME AS TABLE   (     arg int    )  GO 

Stored Procedure to Accept That Type Param

 CREATE PROCEDURE mainValues   @TableParam TYPENAME READONLY  AS     BEGIN     SET NOCOUNT ON;   --Temp table to store split values   declare @tmp_values table (   value nvarchar(255) not null);        --function splitting values     INSERT INTO @tmp_values (value)    SELECT arg FROM @TableParam      SELECT * FROM @tmp_values  --<-- For testing purpose END 

EXECUTE PROC

Declare a variable of that type and populate it with your values.

 DECLARE @Table TYPENAME     --<-- Variable of this TYPE   INSERT INTO @Table                --<-- Populating the variable   VALUES (331),(222),(876),(932)  EXECUTE mainValues @Table   --<-- Stored Procedure Executed  

Result

╔═══════╗ ║ value ║ ╠═══════╣ ║   331 ║ ║   222 ║ ║   876 ║ ║   932 ║ ╚═══════╝ 

Java Wait for thread to finish

Generally, when you want to wait for a thread to finish, you should call join() on it.

How to enable file sharing for my app?

In Xcode 8.3.3 add new row in .plist with true value

Application supports iTunes file sharing

"Cloning" row or column vectors

One clean solution is to use NumPy's outer-product function with a vector of ones:

np.outer(np.ones(n), x)

gives n repeating rows. Switch the argument order to get repeating columns. To get an equal number of rows and columns you might do

np.outer(np.ones_like(x), x)

How to read files and stdout from a running Docker container

You can view the filesystem of the container at

/var/lib/docker/devicemapper/mnt/$CONTAINER_ID/rootfs/

and you can just

tail -f mylogfile.log

CGContextDrawImage draws image upside down when passed UIImage.CGImage

We can solve this problem using the same function:

UIGraphicsBeginImageContext(image.size);

UIGraphicsPushContext(context);

[image drawInRect:CGRectMake(gestureEndPoint.x,gestureEndPoint.y,350,92)];

UIGraphicsPopContext();

UIGraphicsEndImageContext();

How do I kill background processes / jobs when my shell script exits?

The trap 'kill 0' SIGINT SIGTERM EXIT solution described in @tokland's answer is really nice, but latest Bash crashes with a segmentation fault when using it. That's because Bash, starting from v. 4.3, allows trap recursion, which becomes infinite in this case:

  1. shell process receives SIGINT or SIGTERM or EXIT;
  2. the signal gets trapped, executing kill 0, which sends SIGTERM to all processes in the group, including the shell itself;
  3. go to 1 :)

This can be worked around by manually de-registering the trap:

trap 'trap - SIGTERM && kill 0' SIGINT SIGTERM EXIT

The more fancy way that allows printing the received signal and avoids "Terminated:" messages:

#!/usr/bin/env bash

trap_with_arg() { # from https://stackoverflow.com/a/2183063/804678
  local func="$1"; shift
  for sig in "$@"; do
    trap "$func $sig" "$sig"
  done
}

stop() {
  trap - SIGINT EXIT
  printf '\n%s\n' "received $1, killing child processes"
  kill -s SIGINT 0
}

trap_with_arg 'stop' EXIT SIGINT SIGTERM SIGHUP

{ i=0; while (( ++i )); do sleep 0.5 && echo "a: $i"; done } &
{ i=0; while (( ++i )); do sleep 0.6 && echo "b: $i"; done } &

while true; do read; done

UPD: added a minimal example; improved stop function to avoid de-trapping unnecessary signals and to hide "Terminated:" messages from the output. Thanks Trevor Boyd Smith for the suggestions!

Calculate distance between 2 GPS coordinates

Here's a Kotlin variation:

import kotlin.math.*

class HaversineAlgorithm {

    companion object {
        private const val MEAN_EARTH_RADIUS = 6371.0
        private const val D2R = Math.PI / 180.0
    }

    private fun haversineInKm(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
        val lonDiff = (lon2 - lon1) * D2R
        val latDiff = (lat2 - lat1) * D2R
        val latSin = sin(latDiff / 2.0)
        val lonSin = sin(lonDiff / 2.0)
        val a = latSin * latSin + (cos(lat1 * D2R) * cos(lat2 * D2R) * lonSin * lonSin)
        val c = 2.0 * atan2(sqrt(a), sqrt(1.0 - a))
        return EQATORIAL_EARTH_RADIUS * c
    }
}

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

Turn on Password Authentication

By default, you need to use keys to ssh into your google compute engine machine, but you can turn on password authentication if you do not need that level of security.

Tip: Use the Open in browser window SSH option from your cloud console to gain access to the machine. Then switch to the root user with sudo su - root to make the configuration changes below.

enter image description here

  1. Edit the /etc/ssh/sshd_config file.
  2. Change PasswordAuthentication and ChallengeResponseAuthentication to yes.
  3. Restart ssh /etc/init.d/ssh restart.

Code line wrapping - how to handle long lines

In general, I break lines before operators, and indent the subsequent lines:

Map<long parameterization> longMap
    = new HashMap<ditto>();

String longString = "some long text"
                  + " some more long text";

To me, the leading operator clearly conveys that "this line was continued from something else, it doesn't stand on its own." Other people, of course, have different preferences.

How to cache data in a MVC application

Here's a nice and simple cache helper class/service I use:

using System.Runtime.Caching;  

public class InMemoryCache: ICacheService
{
    public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class
    {
        T item = MemoryCache.Default.Get(cacheKey) as T;
        if (item == null)
        {
            item = getItemCallback();
            MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(10));
        }
        return item;
    }
}

interface ICacheService
{
    T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class;
}

Usage:

cacheProvider.GetOrSet("cache key", (delegate method if cache is empty));

Cache provider will check if there's anything by the name of "cache id" in the cache, and if there's not, it will call a delegate method to fetch data and store it in cache.

Example:

var products=cacheService.GetOrSet("catalog.products", ()=>productRepository.GetAll())

High-precision clock in Python

Here is a python 3 solution for Windows building upon the answer posted above by CyberSnoopy (using GetSystemTimePreciseAsFileTime). We borrow some code from jfs

Python datetime.utcnow() returning incorrect datetime

and get a precise timestamp (Unix time) in microseconds

#! python3
import ctypes.wintypes

def utcnow_microseconds():
    system_time = ctypes.wintypes.FILETIME()
    #system call used by time.time()
    #ctypes.windll.kernel32.GetSystemTimeAsFileTime(ctypes.byref(system_time))
    #getting high precision:
    ctypes.windll.kernel32.GetSystemTimePreciseAsFileTime(ctypes.byref(system_time))
    large = (system_time.dwHighDateTime << 32) + system_time.dwLowDateTime
    return large // 10 - 11644473600000000

for ii in range(5):
    print(utcnow_microseconds()*1e-6)

References
https://docs.microsoft.com/en-us/windows/win32/sysinfo/time-functions
https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime
https://support.microsoft.com/en-us/help/167296/how-to-convert-a-unix-time-t-to-a-win32-filetime-or-systemtime

Does Java have a complete enum for HTTP response codes?

Everyone seems to be ignoring the "enum type" portion of your question.

While there is no canonical source for HTTP Status Codes there is an simple way to add any missing Status constants you need to those provided by javax.ws.rs.core.Response.Status without adding any additional dependencies to your project.

javax.ws.rs.core.Response.Status is just one implementation of the javax.ws.rs.core.Response.StatusType interface. You simply need to create your own implementation enum with definitions for the Status Codes that you want.

Core libraries like Javax, Jersey, etc. are written to the interface StatusType not the implementation Status (or they certainly should be). Since your new Status enum implements StatusType it can be used anyplace you would use a javax.ws.rs.core.Response.Status constant.

Just remember that your own code should also be written to the StatusType interface. This will enable you to use both your own Status Codes along side the "standard" ones.

Here's a gist with a simple implementation with constants defined for the "Informational 1xx" Status Codes: https://gist.github.com/avendasora/a5ed9acf6b1ee709a14a

.attr('checked','checked') does not work

 $('.checkbox').attr('checked',true);

will not work with from jQuery 1.6.

Instead use

$('.checkbox').prop('checked',true);
$('.checkbox').prop('checked',false);

Full explanation / examples and demo can be found in the jQuery API Documentation https://api.jquery.com/attr/

SQL SERVER, SELECT statement with auto generate row id

IDENTITY(int, 1, 1) should do it if you are doing a select into. In SQL 2000, I use to just put the results in a temp table and query that afterwords.

Sort a List of Object in VB.NET

try..

Dim sortedList = From entry In mylist Order By entry.name Ascending Select entry

mylist = sortedList.ToList

Counting the number of occurences of characters in a string

if this is a real program and not a study project, then look at using the Apache Commons StringUtils class - particularly the countMatches method.

If it is a study project then keep at it and learn from your exploring :)

CSS display:inline property with list-style-image: property on <li> tags

I had similar problem, i solve using css ":before".. the code looks likes this:

.widgets li:before{
    content:"• ";
}

Bootstrap change div order with pull-right, pull-left on 3 columns

Try this...

<div class="row">
    <div class="col-xs-3">
        Menu
    </div>
    <div class="col-xs-9">
        <div class="row">
          <div class="col-sm-4 col-sm-push-8">
          Right content
          </div>
          <div class="col-sm-8 col-sm-pull-4">
          Content
          </div>
       </div>
    </div>
</div>

Bootply

How can I shuffle an array?

You could use the Fisher-Yates Shuffle (code adapted from this site):

function shuffle(array) {
    let counter = array.length;

    // While there are elements in the array
    while (counter > 0) {
        // Pick a random index
        let index = Math.floor(Math.random() * counter);

        // Decrease counter by 1
        counter--;

        // And swap the last element with it
        let temp = array[counter];
        array[counter] = array[index];
        array[index] = temp;
    }

    return array;
}

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

(Note: root, base, apex domains are all the same thing. Using interchangeably for google-foo.)

Traditionally, to point your apex domain you'd use an A record pointing to your server's IP. This solution doesn't scale and isn't viable for a cloud platform like Heroku, where multiple and frequently changing backends are responsible for responding to requests.

For subdomains (like www.example.com) you can use CNAME records pointing to your-app-name.herokuapp.com. From there on, Heroku manages the dynamic A records behind your-app-name.herokuapp.com so that they're always up-to-date. Unfortunately, the DNS specification does not allow CNAME records on the zone apex (the base domain). (For example, MX records would break as the CNAME would be followed to its target first.)

Back to root domains, the simple and generic solution is to not use them at all. As a fallback measure, some DNS providers offer to setup an HTTP redirect for you. In that case, set it up so that example.com is an HTTP redirect to www.example.com.

Some DNS providers have come forward with custom solutions that allow CNAME-like behavior on the zone apex. To my knowledge, we have DNSimple's ALIAS record and DNS Made Easy's ANAME record; both behave similarly.

Using those, you could setup your records as (using zonefile notation, even tho you'll probably do this on their web user interface):

@   IN ALIAS your-app-name.herokuapp.com.
www IN CNAME your-app-name.herokuapp.com.

Remember @ here is a shorthand for the root domain (example.com). Also mind you that the trailing dots are important, both in zonefiles, and some web user interfaces.

See also:

Remarks:

  • Amazon's Route 53 also has an ALIAS record type, but it's somewhat limited, in that it only works to point within AWS. At the moment I would not recommend using this for a Heroku setup.

  • Some people confuse DNS providers with domain name registrars, as there's a bit of overlap with companies offering both. Mind you that to switch your DNS over to one of the aforementioned providers, you only need to update your nameserver records with your current domain registrar. You do not need to transfer your domain registration.

Detecting the onload event of a window opened with window.open

var myPopup = window.open(...);
myPopup.addEventListener('load', myFunction, false);

If you care about IE, use the following as the second line instead:

myPopup[myPopup.addEventListener ? 'addEventListener' : 'attachEvent'](
  (myPopup.attachEvent ? 'on' : '') + 'load', myFunction, false
);

As you can see, supporting IE is quite cumbersome and should be avoided if possible. I mean, if you need to support IE because of your audience, by all means, do so.

How to ssh from within a bash script?

There's yet another way to do it using Shared Connections, ie: somebody initiates the connection, using a password, and every subsequent connection will multiplex over the same channel, negating the need for re-authentication. ( And its faster too )

# ~/.ssh/config 
ControlMaster auto
ControlPath ~/.ssh/pool/%r@%h

then you just have to log in, and as long as you are logged in, the bash script will be able to open ssh connections.

You can then stop your script from working when somebody has not already opened the channel by:

ssh ... -o KbdInteractiveAuthentication=no ....

NLS_NUMERIC_CHARACTERS setting for decimal

Jaanna, the session parameters in Oracle SQL Developer are dependent on your client computer, while the NLS parameters on PL/SQL is from server.

For example the NLS_NUMERIC_CHARACTERS on client computer can be ',.' while it's '.,' on server.

So when you run script from PL/SQL and Oracle SQL Developer the decimal separator can be completely different for the same script, unless you alter session with your expected NLS_NUMERIC_CHARACTERS in the script.

One way to easily test your session parameter is to do:

select to_number(5/2) from dual;

What is "String args[]"? parameter in main method Java

When a java class is executed from the console, the main method is what is called. In order for this to happen, the definition of this main method must be

public static void main(String [])

The fact that this string array is called args is a standard convention, but not strictly required. You would populate this array at the command line when you invoke your program

java MyClass a b c

These are commonly used to define options of your program, for example files to write to or read from.

How to pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array?

I think we should sent in this format

var array = [1, 2, 3, 4, 5];
$.post('/controller/MyAction', $.param({ data: array }, true), function(data) {});

Its already mentioned in Pass array to mvc Action via AJAX

It worked for me

Multidimensional arrays in Swift

var array: Int[][] = [[1,2,3],[4,5,6],[7,8,9]]

for first in array {
    for second in first {
        println("value \(second)")
    }
}

To achieve what you're looking for you need to initialize the array to the correct template and then loop to add the row and column arrays:

var NumColumns = 27
var NumRows = 52
var array = Array<Array<Int>>()
var value = 1

for column in 0..NumColumns {
    var columnArray = Array<Int>()
    for row in 0..NumRows {
        columnArray.append(value++)
    }
    array.append(columnArray)
}

println("array \(array)")

How do I mock an open used in a with statement (using the Mock framework in Python)?

With the latest versions of mock, you can use the really useful mock_open helper:

mock_open(mock=None, read_data=None)

A helper function to create a mock to replace the use of open. It works for open called directly or used as a context manager.

The mock argument is the mock object to configure. If None (the default) then a MagicMock will be created for you, with the API limited to methods or attributes available on standard file handles.

read_data is a string for the read method of the file handle to return. This is an empty string by default.

>>> from mock import mock_open, patch
>>> m = mock_open()
>>> with patch('{}.open'.format(__name__), m, create=True):
...    with open('foo', 'w') as h:
...        h.write('some stuff')

>>> m.assert_called_once_with('foo', 'w')
>>> handle = m()
>>> handle.write.assert_called_once_with('some stuff')

Angular 2: How to style host element of the component?

For anyone looking to style child elements of a :host here is an example of how to use ::ng-deep

:host::ng-deep <child element>

e.g :host::ng-deep span { color: red; }

As others said /deep/ is deprecated

Convert date field into text in Excel

You can use TEXT like this as part of a concatenation

=TEXT(A1,"dd-mmm-yy") & " other string"

enter image description here

C# Collection was modified; enumeration operation may not execute

I suspect the error is caused by this:

foreach (KeyValuePair<int, int> kvp in rankings)

rankings is a dictionary, which is IEnumerable. By using it in a foreach loop, you're specifying that you want each KeyValuePair from the dictionary in a deferred manner. That is, the next KeyValuePair is not returned until your loop iterates again.

But you're modifying the dictionary inside your loop:

rankings[kvp.Key] = rankings[kvp.Key] + 4;

which isn't allowed...so you get the exception.

You could simply do this

foreach (KeyValuePair<int, int> kvp in rankings.ToArray())

Combining a class selector and an attribute selector with jQuery

This code works too:

$("input[reference=12345].myclass").css('border', '#000 solid 1px');

Select multiple columns in data.table by their numeric indices

From v1.10.2 onwards, you can also use ..

dt <- data.table(a=1:2, b=2:3, c=3:4)

keep_cols = c("a", "c")

dt[, ..keep_cols]

How to append rows to an R data frame

Update

Not knowing what you are trying to do, I'll share one more suggestion: Preallocate vectors of the type you want for each column, insert values into those vectors, and then, at the end, create your data.frame.

Continuing with Julian's f3 (a preallocated data.frame) as the fastest option so far, defined as:

# pre-allocate space
f3 <- function(n){
  df <- data.frame(x = numeric(n), y = character(n), stringsAsFactors = FALSE)
  for(i in 1:n){
    df$x[i] <- i
    df$y[i] <- toString(i)
  }
  df
}

Here's a similar approach, but one where the data.frame is created as the last step.

# Use preallocated vectors
f4 <- function(n) {
  x <- numeric(n)
  y <- character(n)
  for (i in 1:n) {
    x[i] <- i
    y[i] <- i
  }
  data.frame(x, y, stringsAsFactors=FALSE)
}

microbenchmark from the "microbenchmark" package will give us more comprehensive insight than system.time:

library(microbenchmark)
microbenchmark(f1(1000), f3(1000), f4(1000), times = 5)
# Unit: milliseconds
#      expr         min          lq      median         uq         max neval
#  f1(1000) 1024.539618 1029.693877 1045.972666 1055.25931 1112.769176     5
#  f3(1000)  149.417636  150.529011  150.827393  151.02230  160.637845     5
#  f4(1000)    7.872647    7.892395    7.901151    7.95077    8.049581     5

f1() (the approach below) is incredibly inefficient because of how often it calls data.frame and because growing objects that way is generally slow in R. f3() is much improved due to preallocation, but the data.frame structure itself might be part of the bottleneck here. f4() tries to bypass that bottleneck without compromising the approach you want to take.


Original answer

This is really not a good idea, but if you wanted to do it this way, I guess you can try:

for (i in 1:10) {
  df <- rbind(df, data.frame(x = i, y = toString(i)))
}

Note that in your code, there is one other problem:

  • You should use stringsAsFactors if you want the characters to not get converted to factors. Use: df = data.frame(x = numeric(), y = character(), stringsAsFactors = FALSE)

Efficiently getting all divisors of a given number

int result_num;
bool flag;

cout << "Number          Divisors\n";

for (int number = 1; number <= 35; number++)
{
    flag = false;
    cout << setw(3) << number << setw(14);

    for (int i = 1; i <= number; i++) 
    {
        result_num = number % i;

        if (result_num == 0 && flag == true)
        {
            cout << "," << i;
        }

        if (result_num == 0 && flag == false)
        {
            cout << i;
        }

        flag = true;
    }

    cout << endl;   
}
cout << "Press enter to continue.....";
cin.ignore();
return 0;
}

How to query nested objects?

The two query mechanism work in different ways, as suggested in the docs at the section Subdocuments:

When the field holds an embedded document (i.e, subdocument), you can either specify the entire subdocument as the value of a field, or “reach into” the subdocument using dot notation, to specify values for individual fields in the subdocument:

Equality matches within subdocuments select documents if the subdocument matches exactly the specified subdocument, including the field order.


In the following example, the query matches all documents where the value of the field producer is a subdocument that contains only the field company with the value 'ABC123' and the field address with the value '123 Street', in the exact order:

db.inventory.find( {
    producer: {
        company: 'ABC123',
        address: '123 Street'
    }
});

Override body style for content in an iframe

Perhaps it's changed now, but I have used a separate stylesheet with this element:

.feedEkList iframe
{
max-width: 435px!important;
width: 435px!important;
height: 320px!important;
}

to successfully style embedded youtube iframes...see the blog posts on this page.