Programs & Examples On #Assembly resolution

Could not load file or assembly System.Net.Http, Version=4.0.0.0 with ASP.NET (MVC 4) Web API OData Prerelease

I have faced same type of issue and followed the below steps to resolved the issue

Go to Tools --> Library Package Manager --> Package Manager Console and run the below command

Install-Package Microsoft.ASPNet.WebAPI -pre

nvm is not compatible with the npm config "prefix" option:

It might be the problem if you have your home directory mounted somewhere, due nvm does not work properly with symlinks. Because I don't care where is my $NVM_DIR located I run this and all works fine:

$ mv ~/.nvm /tmp/
$ export NVM_DIR="/tmp/.nvm"
$ nvm use --delete-prefix v6.9.1

Apache shutdown unexpectedly

This problem may occur because of skype installation in the system. Skype and apache service always conflict. Make sure your skype is not started before starting xampp.

How do I create an empty array/matrix in NumPy?

You can use the append function. For rows:

>>> from numpy import *
>>> a = array([10,20,30])
>>> append(a, [[1,2,3]], axis=0)
array([[10, 20, 30],      
       [1, 2, 3]])

For columns:

>>> append(a, [[15],[15]], axis=1)
array([[10, 20, 30, 15],      
       [1, 2, 3, 15]])

EDIT
Of course, as mentioned in other answers, unless you're doing some processing (ex. inversion) on the matrix/array EVERY time you append something to it, I would just create a list, append to it then convert it to an array.

Android refresh current activity

this is what worked for me as seen here.

Just use it or add it to a static class helper and just call it from anywher in your project.

/**
Current Activity instance will go through its lifecycle to onDestroy() and a new instance then created after it.
*/
@SuppressLint("NewApi")
  public static final void recreateActivityCompat(final Activity a) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
      a.recreate();
    } else {
      final Intent intent = a.getIntent();
      intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
      a.finish();
      a.overridePendingTransition(0, 0);
      a.startActivity(intent);
      a.overridePendingTransition(0, 0);
   }
}

How to printf a 64-bit integer as hex?

Edit: Use printf("val = 0x%" PRIx64 "\n", val); instead.

Try printf("val = 0x%llx\n", val);. See the printf manpage:

ll (ell-ell). A following integer conversion corresponds to a long long int or unsigned long long int argument, or a following n conversion corresponds to a pointer to a long long int argument.

Edit: Even better is what @M_Oehm wrote: There is a specific macro for that, because unit64_t is not always a unsigned long long: PRIx64 see also this stackoverflow answer

How to read a configuration file in Java

Create a configuration file and put your entries there.

SERVER_PORT=10000     
THREAD_POOL_COUNT=3     
ROOT_DIR=/home/   

You can load this file using Properties.load(fileName) and retrieved values you get(key);

SQL Server - find nth occurrence in a string

My SQL supports the function of a substring_Index where it will return the postion of a value in a string for the n occurance. A similar User defined function could be written to achieve this. Example in the link

Alternatively you could use charindex function call it x times to report the location of each _ given a starting postion +1 of the previously found instance. until a 0 is found

Edit: NM Charindex is the correct function

Deny all, allow only one IP through htaccess

This can be improved by using the directive designed for that task.

ErrorDocument 403 /specific_page.html
Order Allow,Deny
Allow from 111.222.333.444

Where 111.222.333.444 is your static IP address.

When using the "Order Allow,Deny" directive the requests must match either Allow or Deny, if neither is met, the request is denied.

http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#order

How do I convert dmesg timestamp to custom date format?

So KevZero requested a less kludgy solution, so I came up with the following:

sed -r 's#^\[([0-9]+\.[0-9]+)\](.*)#echo -n "[";echo -n $(date --date="@$(echo "$(grep btime /proc/stat|cut -d " " -f 2)+\1" | bc)" +"%c");echo -n "]";echo -n "\2"#e'

Here's an example:

$ dmesg|tail | sed -r 's#^\[([0-9]+\.[0-9]+)\](.*)#echo -n "[";echo -n $(date --date="@$(echo "$(grep btime /proc/stat|cut -d " " -f 2)+\1" | bc)" +"%c");echo -n "]";echo -n "\2"#e'
[2015-12-09T04:29:20 COT] cfg80211:   (57240000 KHz - 63720000 KHz @ 2160000 KHz), (N/A, 0 mBm), (N/A)
[2015-12-09T04:29:23 COT] wlp3s0: authenticate with dc:9f:db:92:d3:07
[2015-12-09T04:29:23 COT] wlp3s0: send auth to dc:9f:db:92:d3:07 (try 1/3)
[2015-12-09T04:29:23 COT] wlp3s0: authenticated
[2015-12-09T04:29:23 COT] wlp3s0: associate with dc:9f:db:92:d3:07 (try 1/3)
[2015-12-09T04:29:23 COT] wlp3s0: RX AssocResp from dc:9f:db:92:d3:07 (capab=0x431 status=0 aid=6)
[2015-12-09T04:29:23 COT] wlp3s0: associated
[2015-12-09T04:29:56 COT] thinkpad_acpi: EC reports that Thermal Table has changed
[2015-12-09T04:29:59 COT] i915 0000:00:02.0: BAR 6: [??? 0x00000000 flags 0x2] has bogus alignment
[2015-12-09T05:00:52 COT] thinkpad_acpi: EC reports that Thermal Table has changed

If you want it to perform a bit better, put the timestamp from proc into a variable instead :)

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

You should install python 3.6 version because python 3.7 version doesn't support pyaudio 1 step : Then download the .whl file
according to your python version and the configuration of your machine in your python folder which is newly installed. For me it is python 3.6 and 64 bit machine. Download the file from here (https://www.lfd.uci.edu/~gohlke/pythonlibs/) 2 step : run your cmd and type " pip install your downloaded file name here "

CSS: how to position element in lower right?

Set the CSS position: relative; on the box. This causes all absolute positions of objects inside to be relative to the corners of that box. Then set the following CSS on the "Bet 5 days ago" line:

position: absolute;
bottom: 0;
right: 0;

If you need to space the text farther away from the edge, you could change 0 to 2px or similar.

Right align and left align text in same HTML table cell

Do you mean like this?

<!-- ... --->
<td>
   this text should be left justified
   and this text should be right justified?
</td>
<!-- ... --->

If yes

<!-- ... --->
<td>
   <p style="text-align: left;">this text should be left justified</p>
   <p style="text-align: right;">and this text should be right justified?</p>
</td>
<!-- ... --->

How do I convert a Django QuerySet into list of dicts?

You do not exactly define what the dictionaries should look like, but most likely you are referring to QuerySet.values(). From the official django documentation:

Returns a ValuesQuerySet — a QuerySet subclass that returns dictionaries when used as an iterable, rather than model-instance objects.

Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.

How to call a method defined in an AngularJS directive?

Building on Oliver's answer - you might not always need to access a directive's inner methods, and in those cases you probably don't want to have to create a blank object and add a control attr to the directive just to prevent it from throwing an error (cannot set property 'takeTablet' of undefined).

You also might want to use the method in other places within the directive.

I would add a check to make sure scope.control exists, and set methods to it in a similar fashion to the revealing module pattern

app.directive('focusin', function factory() {
  return {
    restrict: 'E',
    replace: true,
    template: '<div>A:{{control}}</div>',
    scope: {
      control: '='
    },
    link : function (scope, element, attrs) {
      var takenTablets = 0;
      var takeTablet = function() {
        takenTablets += 1;  
      }

      if (scope.control) {
        scope.control = {
          takeTablet: takeTablet
        };
      }
    }
  };
});

Summarizing multiple columns with dplyr?

For completeness: with dplyr v0.2 ddply with colwise will also do this:

> ddply(df, .(grp), colwise(mean))
  grp        a    b        c        d
1   1 4.333333 4.00 1.000000 2.000000
2   2 2.000000 2.75 2.750000 2.750000
3   3 3.000000 4.00 4.333333 3.666667

but it is slower, at least in this case:

> microbenchmark(ddply(df, .(grp), colwise(mean)), 
                  df %>% group_by(grp) %>% summarise_each(funs(mean)))
Unit: milliseconds
                                            expr      min       lq     mean
                ddply(df, .(grp), colwise(mean))     3.278002 3.331744 3.533835
 df %>% group_by(grp) %>% summarise_each(funs(mean)) 1.001789 1.031528 1.109337

   median       uq      max neval
 3.353633 3.378089 7.592209   100
 1.121954 1.133428 2.292216   100

Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

You can not. You will / do break a lot of things. Like relationships. WHich rely on the number being pulled back which EF can not do in the way you set it up. THe price for breaking every pattern there is.

Generate the GUID in the C# layer, so that relationships can continue working.

How to terminate a Python script

Another way is:

raise SystemExit

Getting the last element of a list

If your str() or list() objects might end up being empty as so: astr = '' or alist = [], then you might want to use alist[-1:] instead of alist[-1] for object "sameness".

The significance of this is:

alist = []
alist[-1]   # will generate an IndexError exception whereas 
alist[-1:]  # will return an empty list
astr = ''
astr[-1]    # will generate an IndexError exception whereas
astr[-1:]   # will return an empty str

Where the distinction being made is that returning an empty list object or empty str object is more "last element"-like then an exception object.

Android runOnUiThread explanation

If you already have the data "for (Parcelable currentHeadline : allHeadlines)," then why are you doing that in a separate thread?

You should poll the data in a separate thread, and when it's finished gathering it, then call your populateTables method on the UI thread:

private void populateTable() {
    runOnUiThread(new Runnable(){
        public void run() {
            //If there are stories, add them to the table
            for (Parcelable currentHeadline : allHeadlines) {
                addHeadlineToTable(currentHeadline);
            }
            try {
                dialog.dismiss();
            } catch (final Exception ex) {
                Log.i("---","Exception in thread");
            }
        }
    });
}

How to get jQuery dropdown value onchange event

If you have simple dropdown like:

<select name="status" id="status">
    <option value="1">Active</option>
    <option value="0">Inactive</option>
</select>

Then you can use this code for getting value:

$(function(){

 $("#status").change(function(){
     var status = this.value;
     alert(status);
   if(status=="1")
     $("#icon_class, #background_class").hide();// hide multiple sections
  });

});

Format datetime to YYYY-MM-DD HH:mm:ss in moment.js

Use different format or pattern to get the information from the date

_x000D_
_x000D_
var myDate = new Date("2015-06-17 14:24:36");_x000D_
console.log(moment(myDate).format("YYYY-MM-DD HH:mm:ss"));_x000D_
console.log("Date: "+moment(myDate).format("YYYY-MM-DD"));_x000D_
console.log("Year: "+moment(myDate).format("YYYY"));_x000D_
console.log("Month: "+moment(myDate).format("MM"));_x000D_
console.log("Month: "+moment(myDate).format("MMMM"));_x000D_
console.log("Day: "+moment(myDate).format("DD"));_x000D_
console.log("Day: "+moment(myDate).format("dddd"));_x000D_
console.log("Time: "+moment(myDate).format("HH:mm")); // Time in24 hour format_x000D_
console.log("Time: "+moment(myDate).format("hh:mm A"));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_

For more info: https://momentjs.com/docs/#/parsing/string-format/

"rm -rf" equivalent for Windows?

RMDIR or RD if you are using the classic Command Prompt (cmd.exe):

rd /s /q "path"

RMDIR [/S] [/Q] [drive:]path

RD [/S] [/Q] [drive:]path

/S Removes all directories and files in the specified directory in addition to the directory itself. Used to remove a directory tree.

/Q Quiet mode, do not ask if ok to remove a directory tree with /S

If you are using PowerShell you can use Remove-Item (which is aliased to del, erase, rd, ri, rm and rmdir) and takes a -Recurse argument that can be shorted to -r

rd -r "path"

What's the point of the X-Requested-With header?

A good reason is for security - this can prevent CSRF attacks because this header cannot be added to the AJAX request cross domain without the consent of the server via CORS.

Only the following headers are allowed cross domain:

  • Accept
  • Accept-Language
  • Content-Language
  • Last-Event-ID
  • Content-Type

any others cause a "pre-flight" request to be issued in CORS supported browsers.

Without CORS it is not possible to add X-Requested-With to a cross domain XHR request.

If the server is checking that this header is present, it knows that the request didn't initiate from an attacker's domain attempting to make a request on behalf of the user with JavaScript. This also checks that the request wasn't POSTed from a regular HTML form, of which it is harder to verify it is not cross domain without the use of tokens. (However, checking the Origin header could be an option in supported browsers, although you will leave old browsers vulnerable.)

New Flash bypass discovered

You may wish to combine this with a token, because Flash running on Safari on OSX can set this header if there's a redirect step. It appears it also worked on Chrome, but is now remediated. More details here including different versions affected.

OWASP Recommend combining this with an Origin and Referer check:

This defense technique is specifically discussed in section 4.3 of Robust Defenses for Cross-Site Request Forgery. However, bypasses of this defense using Flash were documented as early as 2008 and again as recently as 2015 by Mathias Karlsson to exploit a CSRF flaw in Vimeo. But, we believe that the Flash attack can't spoof the Origin or Referer headers so by checking both of them we believe this combination of checks should prevent Flash bypass CSRF attacks. (NOTE: If anyone can confirm or refute this belief, please let us know so we can update this article)

However, for the reasons already discussed checking Origin can be tricky.

Update

Written a more in depth blog post on CORS, CSRF and X-Requested-With here.

What IDE to use for Python?

Results

Spreadsheet version

spreadsheet screenshot

Alternatively, in plain text: (also available as a a screenshot)

                         Bracket Matching -.  .- Line Numbering
                          Smart Indent -.  |  |  .- UML Editing / Viewing
         Source Control Integration -.  |  |  |  |  .- Code Folding
                    Error Markup -.  |  |  |  |  |  |  .- Code Templates
  Integrated Python Debugging -.  |  |  |  |  |  |  |  |  .- Unit Testing
    Multi-Language Support -.  |  |  |  |  |  |  |  |  |  |  .- GUI Designer (Qt, Eric, etc)
   Auto Code Completion -.  |  |  |  |  |  |  |  |  |  |  |  |  .- Integrated DB Support
     Commercial/Free -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  .- Refactoring
   Cross Platform -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom              |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |  |  |  |  |*many plugins
Editra            |Y |F |Y |Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |
Emacs             |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
Eric Ide          |Y |F |Y |  |Y |Y |  |Y |  |Y |  |Y |  |Y |  |  |  |
Geany             |Y |F |Y*|Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |*very limited
Gedit             |Y |F |Y¹|Y |  |  |  |Y |Y |Y |  |  |Y²|  |  |  |  |¹with plugin; ²sort of
Idle              |Y |F |Y |  |Y |  |  |Y |Y |  |  |  |  |  |  |  |  |
IntelliJ          |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit             |Y |F |  |Y |  |  |  |  |Y |Y |  |Y |  |  |  |  |  |
KDevelop          |Y |F |Y*|Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |*no type inference
Komodo            |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |Y |  |
NetBeans*         |Y |F |Y |Y |Y |  |Y |Y |Y |Y |Y |Y |Y |Y |  |  |Y |*pre-v7.0
Notepad++         |W |F |Y |Y |  |Y*|Y*|Y*|Y |Y |  |Y |Y*|  |  |  |  |*with plugin
Pfaide            |W |C |Y |Y |  |  |  |Y |Y |Y |  |Y |Y |  |  |  |  |
PIDA              |LW|F |Y |Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |VIM based
PTVS              |W |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |  |  |Y*|  |Y |*WPF bsed
PyCharm           |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse)   |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
PyScripter        |W |F |Y |  |Y |Y |  |Y |Y |Y |  |Y |Y |Y |  |  |  |
PythonWin         |W |F |Y |  |Y |  |  |Y |Y |  |  |Y |  |  |  |  |  |
SciTE             |Y |F¹|  |Y |  |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |¹Mac version is
ScriptDev         |W |C |Y |Y |Y |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |    commercial
Spyder            |Y |F |Y |  |Y |Y |  |Y |Y |Y |  |  |  |  |  |  |  |
Sublime Text      |Y |CF|Y |Y |  |Y |Y |Y |Y |Y |  |Y |Y |Y*|  |  |  |extensible w/Python,
TextMate          |M |F |  |Y |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |    *PythonTestRunner
UliPad            |Y |F |Y |Y |Y |  |  |Y |Y |  |  |  |Y |Y |  |  |  |
Vim               |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |
Visual Studio     |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde           |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |*support for C
Zeus              |W |C |  |  |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
   Cross Platform -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
     Commercial/Free -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  '- Refactoring
   Auto Code Completion -'  |  |  |  |  |  |  |  |  |  |  |  |  '- Integrated DB Support
    Multi-Language Support -'  |  |  |  |  |  |  |  |  |  |  '- GUI Designer (Qt, Eric, etc)
  Integrated Python Debugging -'  |  |  |  |  |  |  |  |  '- Unit Testing
                    Error Markup -'  |  |  |  |  |  |  '- Code Templates
         Source Control Integration -'  |  |  |  |  '- Code Folding
                          Smart Indent -'  |  |  '- UML Editing / Viewing
                         Bracket Matching -'  '- Line Numbering

Acronyms used:

 L  - Linux
 W  - Windows
 M  - Mac
 C  - Commercial
 F  - Free
 CF - Commercial with Free limited edition
 ?  - To be confirmed

I don't mention basics like syntax highlighting as I expect these by default.


This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.

PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?

We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments

Submit edits to the spreadsheet

Git - remote: Repository not found

I was trying to clone a repo and was facing this issue, I tried removing all git related credentials from windows credentials manager after that while trying to clone git was asking me for my credentials and failing with error invalid username or password. This was happening because the repo I was trying to clone was under an organization on github and that organization had two factor auth enabled and git bash probably do not know how to handle 2fa. So I generated a token from https://github.com/settings/tokens and used the github token instead of password while trying to clone the repo and that worked.

Java 8 stream map to list of keys sorted by values

Map<Integer, String> map = new HashMap<>();
map.put(1, "B");
map.put(2, "C");
map.put(3, "D");
map.put(4, "A");

List<String> list = map.values()
                       .stream()
                       .sorted()
                       .collect(Collectors.toList());

Output: [A, B, C, D]

How to iterate over the keys and values with ng-repeat in AngularJS?

Here's a working example:

<div class="item item-text-wrap" ng-repeat="(key,value) in form_list">
  <b>{{key}}</b> : {{value}}
</div>

edited

C# - What does the Assert() method do? Is it still useful?

Assert also gives you another opportunity to chuckle at Microsoft's UI design skills. I mean: a dialog with three buttons Abort, Retry, Ignore, and an explanation of how to interpret them in the title bar!

CMD what does /im (taskkill)?

it allows you to kill a task based on the image name like taskkill /im iexplore.exe or taskkill /im notepad.exe

How to print in C

printf is a fair bit more complicated than that. You have to supply a format string, and then the variables to apply to the format string. If you just supply one variable, C will assume that is the format string and try to print out all the bytes it finds in it until it hits a terminating nul (0x0).

So if you just give it an integer, it will merrily march through memory at the location your integer is stored, dumping whatever garbage is there to the screen, until it happens to come across a byte containing 0.

For a Java programmer, I'd imagine this is a rather rude introduction to C's lack of type checking. Believe me, this is only the tip of the iceberg. This is why, while I applaud your desire to expand your horizons by learning C, I highly suggest you do whatever you can to avoid writing real programs in it.

(This goes for everyone else reading this too.)

Using ffmpeg to change framerate

Simply specify the desired framerate in "-r " option before the input file:

ffmpeg -y -r 24 -i seeing_noaudio.mp4 seeing.mp4

Options affect the next file AFTER them. "-r" before an input file forces to reinterpret its header as if the video was encoded at the given framerate. No recompression is necessary. There was a small utility avifrate.exe to patch avi file headers directly to change the framerate. ffmpeg command above essentially does the same, but has to copy the entire file.

python to arduino serial read & write

You shouldn't be closing the serial port in Python between writing and reading. There is a chance that the port is still closed when the Arduino responds, in which case the data will be lost.

while running:  
    # Serial write section
    setTempCar1 = 63
    setTempCar2 = 37
    setTemp1 = str(setTempCar1)
    setTemp2 = str(setTempCar2)
    print ("Python value sent: ")
    print (setTemp1)
    ard.write(setTemp1)
    time.sleep(6) # with the port open, the response will be buffered 
                  # so wait a bit longer for response here

    # Serial read section
    msg = ard.read(ard.inWaiting()) # read everything in the input buffer
    print ("Message from arduino: ")
    print (msg)

The Python Serial.read function only returns a single byte by default, so you need to either call it in a loop or wait for the data to be transmitted and then read the whole buffer.

On the Arduino side, you should consider what happens in your loop function when no data is available.

void loop()
{
  // serial read section
  while (Serial.available()) // this will be skipped if no data present, leading to
                             // the code sitting in the delay function below
  {
    delay(30);  //delay to allow buffer to fill 
    if (Serial.available() >0)
    {
      char c = Serial.read();  //gets one byte from serial buffer
      readString += c; //makes the string readString
    }
  }

Instead, wait at the start of the loop function until data arrives:

void loop()
{
  while (!Serial.available()) {} // wait for data to arrive
  // serial read section
  while (Serial.available())
  {
    // continue as before

EDIT 2

Here's what I get when interfacing with your Arduino app from Python:

>>> import serial
>>> s = serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=5)
>>> s.write('2')
1
>>> s.readline()
'Arduino received: 2\r\n'

So that seems to be working fine.

In testing your Python script, it seems the problem is that the Arduino resets when you open the serial port (at least my Uno does), so you need to wait a few seconds for it to start up. You are also only reading a single line for the response, so I've fixed that in the code below also:

#!/usr/bin/python
import serial
import syslog
import time

#The following line is for serial over GPIO
port = '/dev/tty.usbmodem1411' # note I'm using Mac OS-X


ard = serial.Serial(port,9600,timeout=5)
time.sleep(2) # wait for Arduino

i = 0

while (i < 4):
    # Serial write section

    setTempCar1 = 63
    setTempCar2 = 37
    ard.flush()
    setTemp1 = str(setTempCar1)
    setTemp2 = str(setTempCar2)
    print ("Python value sent: ")
    print (setTemp1)
    ard.write(setTemp1)
    time.sleep(1) # I shortened this to match the new value in your Arduino code

    # Serial read section
    msg = ard.read(ard.inWaiting()) # read all characters in buffer
    print ("Message from arduino: ")
    print (msg)
    i = i + 1
else:
    print "Exiting"
exit()

Here's the output of the above now:

$ python ardser.py
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Exiting

pull/push from multiple remote locations

I wanted to work in VSO/TFS, then push publicly to GitHub when ready. Initial repo created in private VSO. When it came time to add to GitHub I did:

git remote add mygithubrepo https://github.com/jhealy/kinect2.git
git push -f mygithubrepo master

Worked like a champ...

For a sanity check, issue "git remote -v" to list the repositories associated with a project.

C:\dev\kinect\vso-repo-k2work\FaceNSkinWPF>git remote -v
githubrepo      https://github.com/jhealy/kinect2.git (fetch)
githubrepo      https://github.com/jhealy/kinect2.git (push)
origin  https://devfish.visualstudio.com/DefaultCollection/_git/Kinect2Work (fetch)
origin  https://devfish.visualstudio.com/DefaultCollection/_git/Kinect2Work (push)

Simple way, worked for me... Hope this helps someone.

REST API Best practices: Where to put parameters?

According to the URI standard the path is for hierarchical parameters and the query is for non-hierarchical parameters. Ofc. it can be very subjective what is hierarchical for you.

In situations where multiple URIs are assigned to the same resource I like to put the parameters - necessary for identification - into the path and the parameters - necessary to build the representation - into the query. (For me this way it is easier to route.)

For example:

  • /users/123 and /users/123?fields="name, age"
  • /users and /users?name="John"&age=30

For map reduce I like to use the following approaches:

  • /users?name="John"&age=30
  • /users/name:John/age:30

So it is really up to you (and your server side router) how you construct your URIs.

note: Just to mention these parameters are query parameters. So what you are really doing is defining a simple query language. By complex queries (which contain operators like and, or, greater than, etc.) I suggest you to use an already existing query language. The capabilities of URI templates are very limited...

Firebase: how to generate a unique numeric ID for key?

As explained above, you can use the Firebase default push id.

If you want something numeric you can do something based on the timestamp to avoid collisions

f.e. something based on date,hour,second,ms, and some random int at the end

01612061353136799031

Which translates to:

016-12-06 13:53:13:679 9031

It all depends on the precision you need (social security numbers do the same with some random characters at the end of the date). Like how many transactions will be expected during the day, hour or second. You may want to lower precision to favor ease of typing.

You can also do a transaction that increments the number id, and on success you will have a unique consecutive number for that user. These can be done on the client or server side.

(https://firebase.google.com/docs/database/android/read-and-write)

Execute a large SQL script (with GO commands)

I look at this a few times at the end decided with EF implementation A bit modified for SqlConnection

public static void ExecuteSqlScript(this SqlConnection sqlConnection, string sqlBatch)
        {
            // Handle backslash utility statement (see http://technet.microsoft.com/en-us/library/dd207007.aspx)
            sqlBatch = Regex.Replace(sqlBatch, @"\\(\r\n|\r|\n)", string.Empty);

            // Handle batch splitting utility statement (see http://technet.microsoft.com/en-us/library/ms188037.aspx)
            var batches = Regex.Split(
                sqlBatch,
                string.Format(CultureInfo.InvariantCulture, @"^\s*({0}[ \t]+[0-9]+|{0})(?:\s+|$)", BatchTerminator),
                RegexOptions.IgnoreCase | RegexOptions.Multiline);

            for (int i = 0; i < batches.Length; ++i)
            {
                // Skip batches that merely contain the batch terminator
                if (batches[i].StartsWith(BatchTerminator, StringComparison.OrdinalIgnoreCase) ||
                    (i == batches.Length - 1 && string.IsNullOrWhiteSpace(batches[i])))
                {
                    continue;
                }

                // Include batch terminator if the next element is a batch terminator
                if (batches.Length > i + 1 &&
                    batches[i + 1].StartsWith(BatchTerminator, StringComparison.OrdinalIgnoreCase))
                {
                    int repeatCount = 1;

                    // Handle count parameter on the batch splitting utility statement
                    if (!string.Equals(batches[i + 1], BatchTerminator, StringComparison.OrdinalIgnoreCase))
                    {
                        repeatCount = int.Parse(Regex.Match(batches[i + 1], @"([0-9]+)").Value, CultureInfo.InvariantCulture);
                    }

                    for (int j = 0; j < repeatCount; ++j)
                    {
                       var command = sqlConnection.CreateCommand();
                       command.CommandText = batches[i];
                       command.ExecuteNonQuery();
                    }
                }
                else
                {
                    var command = sqlConnection.CreateCommand();
                    command.CommandText = batches[i];
                    command.ExecuteNonQuery();
                }
            }
        }

How can I check if the array of objects have duplicate property values?

In TS and ES6 you can create a new Set with the property to be unique and compare it's size to the original array.

_x000D_
_x000D_
const values = [_x000D_
  { name: 'someName1' },_x000D_
  { name: 'someName2' },_x000D_
  { name: 'someName3' },_x000D_
  { name: 'someName1' }_x000D_
]_x000D_
_x000D_
const uniqueValues = new Set(values.map(v => v.name));_x000D_
_x000D_
if (uniqueValues.size < values.length) {_x000D_
  console.log('duplicates found')_x000D_
}
_x000D_
_x000D_
_x000D_

JavaFX open new window

The code below worked for me I used part of the code above inside the button class.

public Button signupB;

public void handleButtonClick (){

    try {
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(getClass().getResource("sceneNotAvailable.fxml"));
        /*
         * if "fx:controller" is not set in fxml
         * fxmlLoader.setController(NewWindowController);
         */
        Scene scene = new Scene(fxmlLoader.load(), 630, 400);
        Stage stage = new Stage();
        stage.setTitle("New Window");
        stage.setScene(scene);
        stage.show();
    } catch (IOException e) {
        Logger logger = Logger.getLogger(getClass().getName());
        logger.log(Level.SEVERE, "Failed to create new Window.", e);
    }

}

}

Specify sudo password for Ansible

This worked for me... Created file /etc/sudoers.d/90-init-users file with NOPASSWD

echo "user ALL=(ALL)       NOPASSWD:ALL" > 90-init-users

where "user" is your userid.

Can I pass a JavaScript variable to another browser window?

Yes browsers clear all ref. for a window. So you have to search a ClassName of something on the main window or use cookies as Javascript homemade ref.

I have a radio on my project page. And then you turn on for the radio it´s starts in a popup window and i controlling the main window links on the main page and show status of playing and in FF it´s easy but in MSIE not so Easy at all. But it can be done.

Darkening an image with CSS (In any shape)

Webkit only solution

Quick solution, relies on the -webkit-mask-image property. -webkit-mask-image sets a mask image for an element.

There are a few gotchas with this method:

  • Obviously, only works in Webkit browsers
  • Requires an additional wrapper to apply the :after psuedo-element (IMG tags can't have :before/:after pseudo elements, grr)
  • Because there's an additional wrapper, I'm not sure how to use the attr(…) CSS function to get the IMG tag URL, so it's hard-coded into the CSS separately.

If you can look past those issues, this might be a possible solution. SVG filters will be even more flexible, and Canvas solutions will be even more flexible and have a wider range of support (SVG doesn't have Android 2.x support).

Set value for particular cell in pandas DataFrame with iloc

One thing I would add here is that the at function on a dataframe is much faster particularly if you are doing a lot of assignments of individual (not slice) values.

df.at[index, 'col_name'] = x

In my experience I have gotten a 20x speedup. Here is a write up that is Spanish but still gives an impression of what's going on.

Remove non-numeric characters (except periods and commas) from a string

You could use preg_replace to swap out all non-numeric characters and the comma and period/full stop as follows:

$testString = '12.322,11T';
echo preg_replace('/[^0-9,.]+/', '', $testString);

The pattern can also be expressed as /[^\d,.]+/

How to convert base64 string to image?

This should do the trick:

image = open("image.png", "wb")
image.write(base64string.decode('base64'))
image.close()

check if variable empty

you can use isset() routine .

also additionaly you can refer an range of is_type () functions like

is_string(), is_float(),is_int() etc to further specificaly test

Xcode: Could not locate device support files

Having the same exact issue with iOS 10.3 and Xcode 8.2.1. I'm not going to download the new Xcode beta just to fix this. Come on Apple!

To anyone reading this, you have to go to https://developer.apple.com/download/ and get the latest version, which might even be the beta, if the stable release doesn't work.

In the future, I would be aware if you update iOS on your devices you may break Xcode/iOS version so update wisely if you want to keep testing on it without jumping through hoops that Apple makes.

How to use WebRequest to POST some data and read response?

From MSDN

// Create a request using a URL that can receive a post. 
WebRequest request = WebRequest.Create ("http://contoso.com/PostAccepter.aspx ");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();

Take into account that the information must be sent in the format key1=value1&key2=value2

How to return a file using Web API?

I've been wondering if there was a simple way to download a file in a more ... "generic" way. I came up with this.

It's a simple ActionResult that will allow you to download a file from a controller call that returns an IHttpActionResult. The file is stored in the byte[] Content. You can turn it into a stream if needs be.

I used this to return files stored in a database's varbinary column.

    public class FileHttpActionResult : IHttpActionResult
    {
        public HttpRequestMessage Request { get; set; }

        public string FileName { get; set; }
        public string MediaType { get; set; }
        public HttpStatusCode StatusCode { get; set; }

        public byte[] Content { get; set; }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            HttpResponseMessage response = new HttpResponseMessage(StatusCode);

            response.StatusCode = StatusCode;
            response.Content = new StreamContent(new MemoryStream(Content));
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            response.Content.Headers.ContentDisposition.FileName = FileName;
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(MediaType);

            return Task.FromResult(response);
        }
    }

How to delete multiple rows in SQL where id = (x to y)

If you need to delete based on a list, you can use IN:

DELETE FROM your_table
WHERE id IN (value1, value2, ...);

If you need to delete based on the result of a query, you can also use IN:

DELETE FROM your_table
WHERE id IN (select aColumn from ...);

(Notice that the subquery must return only one column)

If you need to delete based on a range of values, either you use BETWEEN or you use inequalities:

DELETE FROM your_table
WHERE id BETWEEN bottom_value AND top_value;

or

DELETE FROM your_table
WHERE id >= a_value AND id <= another_value;

Jquery Ajax Loading image

Please note that: ajaxStart / ajaxStop is not working for ajax jsonp request (ajax json request is ok)

I am using jquery 1.7.2 while writing this.

here is one of the reference I found: http://bugs.jquery.com/ticket/8338

Get the time difference between two datetimes

Typescript: following should work,

export const getTimeBetweenDates = ({
  until,
  format
}: {
  until: number;
  format: 'seconds' | 'minutes' | 'hours' | 'days';
}): number => {
  const date = new Date();
  const remainingTime = new Date(until * 1000);
  const getFrom = moment([date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()]);
  const getUntil = moment([remainingTime.getUTCFullYear(), remainingTime.getUTCMonth(), remainingTime.getUTCDate()]);
  const diff = getUntil.diff(getFrom, format);
  return !isNaN(diff) ? diff : null;
};

Cannot install Aptana Studio 3.6 on Windows

I had the same problem. I solved by installing NodeJS from this link: http://go.aptana.com/installer_nodejs_windows and Git latest version from https://git-scm.com/downloads.

Finally I was able to run the Aptana installer with no problems.

#1062 - Duplicate entry for key 'PRIMARY'

Repair the database by your domain provider cpanel.

Or see if you didnt merged something in the phpMyAdmin

How to find the array index with a value?

When the lists aren't extremely long, this is the best way I know:

function getIndex(val) {
    for (var i = 0; i < imageList.length; i++) {
        if (imageList[i] === val) {
            return i;
        }
    }
}

var imageList = [100, 200, 300, 400, 500];
var index = getIndex(200);

100% width in React Native Flexbox

Editted:

In order to flex only the center text, a different approach can be taken - Unflex the other views.

  • Let flexDirection remain at 'column'
  • remove the alignItems : 'center' from container
  • add alignSelf:'center' to the textviews that you don't want to flex

You can wrap the Text component in a View component and give the View a flex of 1.

The flex will give :

100% width if the flexDirection:'row' in styles.container

100% height if the flexDirection:'column' in styles.container

Python - Dimension of Data Frame

df.shape, where df is your DataFrame.

How to strip all whitespace from string

TL/DR

This solution was tested using Python 3.6

To strip all spaces from a string in Python3 you can use the following function:

def remove_spaces(in_string: str):
    return in_string.translate(str.maketrans({' ': ''})

To remove any whitespace characters (' \t\n\r\x0b\x0c') you can use the following function:

import string
def remove_whitespace(in_string: str):
    return in_string.translate(str.maketrans(dict.fromkeys(string.whitespace)))

Explanation

Python's str.translate method is a built-in class method of str, it takes a table and returns a copy of the string with each character mapped through the passed translation table. Full documentation for str.translate

To create the translation table str.maketrans is used. This method is another built-in class method of str. Here we use it with only one parameter, in this case a dictionary, where the keys are the characters to be replaced mapped to values with the characters replacement value. It returns a translation table for use with str.translate. Full documentation for str.maketrans

The string module in python contains some common string operations and constants. string.whitespace is a constant which returns a string containing all ASCII characters that are considered whitespace. This includes the characters space, tab, linefeed, return, formfeed, and vertical tab.Full documentation for string

In the second function dict.fromkeys is used to create a dictionary where the keys are the characters in the string returned by string.whitespace each with value None. Full documentation for dict.fromkeys

Maven fails to find local artifact

I had DependencyResolutionException in Ubuntu Linux when I've installed local artifacts via a shell script. The solution was to delete the local artifacts and install them again "manually" - calling mvn install:install-file via terminal.

How to query for Xml values and attributes from table in SQL Server?

I don't understand why some people are suggesting using cross apply or outer apply to convert the xml into a table of values. For me, that just brought back way too much data.

Here's my example of how you'd create an xml object, then turn it into a table.

(I've added spaces in my xml string, just to make it easier to read.)

DECLARE @str nvarchar(2000)

SET @str = ''
SET @str = @str + '<users>'
SET @str = @str + '  <user>'
SET @str = @str + '     <firstName>Mike</firstName>'
SET @str = @str + '     <lastName>Gledhill</lastName>'
SET @str = @str + '     <age>31</age>'
SET @str = @str + '  </user>'
SET @str = @str + '  <user>'
SET @str = @str + '     <firstName>Mark</firstName>'
SET @str = @str + '     <lastName>Stevens</lastName>'
SET @str = @str + '     <age>42</age>'
SET @str = @str + '  </user>'
SET @str = @str + '  <user>'
SET @str = @str + '     <firstName>Sarah</firstName>'
SET @str = @str + '     <lastName>Brown</lastName>'
SET @str = @str + '     <age>23</age>'
SET @str = @str + '  </user>'
SET @str = @str + '</users>'

DECLARE @xml xml
SELECT @xml = CAST(CAST(@str AS VARBINARY(MAX)) AS XML) 

--  Iterate through each of the "users\user" records in our XML
SELECT 
    x.Rec.query('./firstName').value('.', 'nvarchar(2000)') AS 'FirstName',
    x.Rec.query('./lastName').value('.', 'nvarchar(2000)') AS 'LastName',
    x.Rec.query('./age').value('.', 'int') AS 'Age'
FROM @xml.nodes('/users/user') as x(Rec)

And here's the output:

enter image description here

Using C++ base class constructors?

No, that's not how it is done. Normal way to initialize the base class is in the initialization list :

class A
{
public: 
    A(int val) {}
};

class B : public A
{
public:
  B( int v) : A( v )
  {
  }
};


void main()
{
    B b(10);
}

const to Non-const Conversion in C++

The actual code to cast away the const-ness of your pointer would be:

BoxT<T> * nonConstObj = const_cast<BoxT<T> *>(constObj);

But note that this really is cheating. A better solution would either be to figure out why you want to modify a const object, and redesign your code so you don't have to.... or remove the const declaration from your vector, if it turns out you don't really want those items to be read-only after all.

When to use std::size_t?

When using size_t be careful with the following expression

size_t i = containner.find("mytoken");
size_t x = 99;
if (i-x>-1 && i+x < containner.size()) {
    cout << containner[i-x] << " " << containner[i+x] << endl;
}

You will get false in the if expression regardless of what value you have for x. It took me several days to realize this (the code is so simple that I did not do unit test), although it only take a few minutes to figure the source of the problem. Not sure it is better to do a cast or use zero.

if ((int)(i-x) > -1 or (i-x) >= 0)

Both ways should work. Here is my test run

size_t i = 5;
cerr << "i-7=" << i-7 << " (int)(i-7)=" << (int)(i-7) << endl;

The output: i-7=18446744073709551614 (int)(i-7)=-2

I would like other's comments.

JQuery Ajax Post results in 500 Internal Server Error

You can also get that error in VB if the function you're calling starts with Public Shared Function rather than Public Function in the webservice. (As might happen if you move or copy the function out of a class). Just another thing to watch for.

What is an application binary interface (ABI)?

Functionality: A set of contracts which affect the compiler, assembly writers, the linker, and the operating system. The contracts specify how functions are laid out, where parameters are passed, how parameters are passed, how function returns work. These are generally specific to a (processor architecture, operating system) tuple.

Existing entities: parameter layout, function semantics, register allocation. For instance, the ARM architectures has numerous ABIs (APCS, EABI, GNU-EABI, never mind a bunch of historical cases) - using the a mixed ABI will result in your code simply not working when calling across boundaries.

Consumer: The compiler, assembly writers, operating system, CPU specific architecture.

Who needs these details? The compiler, assembly writers, linkers which do code generation (or alignment requirements), operating system (interrupt handling, syscall interface). If you did assembly programming, you were conforming to an ABI!

C++ name mangling is a special case - its a linker and dynamic linker centered issue - if name mangling is not standardized, then dynamic linking will not work. Henceforth, the C++ ABI is called just that, the C++ ABI. It is not a linker level issue, but instead a code generation issue. Once you have a C++ binary, it is not possible to make it compatible with another C++ ABI (name mangling, exception handling) without recompiling from source.

ELF is a file format for the use of a loader and dynamic linker. ELF is a container format for binary code and data, and as such specifies the ABI of a piece of code. I would not consider ELF to be an ABI in the strict sense, as PE executables are not an ABI.

All ABIs are instruction set specific. An ARM ABI will not make sense on an MSP430 or x86_64 processor.

Windows has several ABIs - for instance, fastcall and stdcall are two common use ABIs. The syscall ABI is different again.

How to solve a timeout error in Laravel 5

Add above query

ini_set("memory_limit", "10056M");

PHP CURL CURLOPT_SSL_VERIFYPEER ignored

We had the same problem on a CentOS7 machine. Disabling the VERIFYHOST VERIFYPEER did not solve the problem, we did not have the cURL error anymore but the response still was invalid. Doing a wget to the same link as the cURL was doing also resulted in a certificate error.

-> Our solution also was to reboot the VPS, this solved it and we were able to complete the request again.

For us this seemed to be a memory corruption problem. Rebooting the VPS reloaded the libary in the memory again and now it works. So if the above solution from @clover does not work try to reboot your machine.

Javascript code for showing yesterday's date and todays date

Yesterday's date is simply today's date less one, so:

var d = new Date();
d.setDate(d.getDate() - 1);

If today is 1 April, then it is set to 0 April which is converted to 31 March.

Since you also wanted to do some other stuff, here are some functions to do it:

// Check if d is a valid date
// Must be format year-month name-date
// e.g. 2011-MAR-12 or 2011-March-6
// Capitalisation is not important
function validDate(d) {
  var bits = d.split('-');
  var t = stringToDate(d);
  return t.getFullYear() == bits[0] && 
         t.getDate() == bits[2];
}

// Convert string in format above to a date object
function stringToDate(s) {
  var bits = s.split('-');
  var monthNum = monthNameToNumber(bits[1]);
  return new Date(bits[0], monthNum, bits[2]);
}

// Convert month names like mar or march to 
// number, capitalisation not important
// Month number is calendar month - 1.
var monthNameToNumber = (function() {
  var monthNames = (
     'jan feb mar apr may jun jul aug sep oct nov dec ' +
     'january february march april may june july august ' +
     'september october november december'
     ).split(' ');

  return function(month) {
    var i = monthNames.length;
    month = month.toLowerCase(); 

    while (i--) {
      if (monthNames[i] == month) {
        return i % 12;
      }
    }
  }
}());

// Given a date in above format, return
// previous day as a date object
function getYesterday(d) {
  d = stringToDate(d);
  d.setDate(d.getDate() - 1)
  return d;
}

// Given a date object, format
// per format above
var formatDate = (function() {
  var months = 'jan feb mar apr may jun jul aug sep oct nov dec'.split(' ');
  function addZ(n) {
    return n<10? '0'+n : ''+n;
  }
  return function(d) {
    return d.getFullYear() + '-' + 
           months[d.getMonth()] + '-' + 
           addZ(d.getDate());
  }
}());

function doStuff(d) {

  // Is it format year-month-date?
  if (!validDate(d)) {
    alert(d + ' is not a valid date');
    return;
  } else {
    alert(d + ' is a valid date');
  }
  alert(
    'Date in was: ' + d +
    '\nDay before: ' + formatDate(getYesterday(d))
  );
}


doStuff('2011-feb-08');
// Shows 2011-feb-08 is a valid date
//       Date in was: 2011-feb-08
//       Day before: 2011-feb-07

Circular (or cyclic) imports in Python

Module a.py :

import b
print("This is from module a")

Module b.py

import a
print("This is from module b")

Running "Module a" will output:

>>> 
'This is from module a'
'This is from module b'
'This is from module a'
>>> 

It output this 3 lines while it was supposed to output infinitival because of circular importing. What happens line by line while running"Module a" is listed here:

  1. The first line is import b. so it will visit module b
  2. The first line at module b is import a. so it will visit module a
  3. The first line at module a is import b but note that this line won't be executed again anymore, because every file in python execute an import line just for once, it does not matter where or when it is executed. so it will pass to the next line and print "This is from module a".
  4. After finish visiting whole module a from module b, we are still at module b. so the next line will print "This is from module b"
  5. Module b lines are executed completely. so we will go back to module a where we started module b.
  6. import b line have been executed already and won't be executed again. the next line will print "This is from module a" and program will be finished.

How to write a stored procedure using phpmyadmin and how to use it through php?

All the answers above are making certain assumptions. There are basic problems in 1and1 and certain other hosting providers are using phpMyAdmin versions which are very old and have an issue that defined delimiter is ; and there is no way to change it from phpMyAdmin. Following are the ways

  1. Create a new PHPMyAdmin on the hosting provider. Attached link gives you idea http://internetbandaid.com/2009/04/05/install-phpmyadmin-on-1and1/
  2. Go thru the complicated route of be able to access the your hosting providers mySQL from your dekstop. It is complicated but the best if you are a serious developer. here is a link to do it http://franklinstrube.com/blog/remote-mysql-administration-for-1and1/

Hope this helps

Adding a new entry to the PATH variable in ZSH

  1. Added path to ~/.zshrc

    sudo vi ~/.zshrc

    add new path

    export PATH="$PATH:[NEW_DIRECTORY]/bin"
    
  2. Update ~/.zshrc

    Save ~/.zshrc

    source ~/.zshrc

  3. Check PATH

    echo $PATH

How to create a button programmatically?

Write this sample code in Swift 4.2 for add Button Programmatically.

override func viewDidLoad() {
    super.viewDidLoad()
        let myButton = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
        myButton.backgroundColor = .green
        myButton.setTitle("Hello UIButton", for: .normal)
        myButton.addTarget(self, action: #selector(myButtonAction), for: .touchUpInside)
        self.view.addSubview(myButton)
}

 @objc func myButtonAction(sender: UIButton!) {
    print("My Button tapped")
}

Specify system property to Maven project

I have learned it is also possible to do this with the exec-maven-plugin if you're doing a "standalone" java app.

            <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>${maven.exec.plugin.version}</version>
            <executions>
                <execution>
                    <goals>
                        <goal>java</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <mainClass>${exec.main-class}</mainClass>
                <systemProperties>
                    <systemProperty>
                        <key>myproperty</key>
                        <value>myvalue</value>
                    </systemProperty>
                </systemProperties>
            </configuration>
        </plugin>

Curl error: Operation timed out

$curl = curl_init();

  curl_setopt_array($curl, array(
  CURLOPT_URL => "", // Server Path
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 3000, // increase this
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\"email\":\"[email protected]\",\"password\":\"markus William\",\"username\":\"Daryl Brown\",\"mobile\":\"013132131112\","msg":"No more SSRIs." }",
  CURLOPT_HTTPHEADER => array(
    "Content-Type: application/json",
    "Postman-Token: 4867c7a3-2b3d-4e9a-9791-ed6dedb046b1",
    "cache-control: no-cache"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

initialize array index "CURLOPT_TIMEOUT" with a value in seconds according to time required for response .

Using Keras & Tensorflow with AMD GPU

Technically you can if you use something like OpenCL, but Nvidia's CUDA is much better and OpenCL requires other steps that may or may not work. I would recommend if you have an AMD gpu, use something like Google Colab where they provide a free Nvidia GPU you can use when coding.

Difference between string and text in rails?

String translates to "Varchar" in your database, while text translates to "text". A varchar can contain far less items, a text can be of (almost) any length.

For an in-depth analysis with good references check http://www.pythian.com/news/7129/text-vs-varchar/

Edit: Some database engines can load varchar in one go, but store text (and blob) outside of the table. A SELECT name, amount FROM products could, be a lot slower when using text for name than when you use varchar. And since Rails, by default loads records with SELECT * FROM... your text-columns will be loaded. This will probably never be a real problem in your or my app, though (Premature optimization is ...). But knowing that text is not always "free" is good to know.

What is difference between cacerts and keystore?

Check your JAVA_HOME path. As systems looks for a java.policy file which is located in JAVA_HOME/jre/lib/security. Your JAVA_HOME should always be ../JAVA/JDK.

SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)

In my case I accidentally used SSL in the Virtualhost configuration for port 80, instead of 443.

How can I compare two lists in python and return matches

If you want a boolean value:

>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(b) == set(a)  & set(b) and set(a) == set(a) & set(b)
False
>>> a = [3,1,2]
>>> b = [1,2,3]
>>> set(b) == set(a)  & set(b) and set(a) == set(a) & set(b)
True

how to send a post request with a web browser

with a form, just set method to "post"

<form action="blah.php" method="post">
  <input type="text" name="data" value="mydata" />
  <input type="submit" />
</form>

In C#, should I use string.Empty or String.Empty or "" to intitialize a string?

On http://blogs.msdn.com/b/brada/archive/2003/04/22/49997.aspx :

As David implies, there difference between String.Empty and "" are pretty small, but there is a difference. "" actually creates an object, it will likely be pulled out of the string intern pool, but still... while String.Empty creates no object... so if you are really looking for ultimately in memory efficiency, I suggest String.Empty. However, you should keep in mind the difference is so trival you will like never see it in your code...
As for System.String.Empty or string.Empty or String.Empty... my care level is low ;-)

How do I remove time part from JavaScript date?

Parse that string into a Date object:

var myDate = new Date('10/11/1955 10:40:50 AM');

Then use the usual methods to get the date's day of month (getDate) / month (getMonth) / year (getFullYear).

var noTime = new Date(myDate.getFullYear(), myDate.getMonth(), myDate.getDate());

How to select clear table contents without destroying the table?

I reworked Doug Glancy's solution to avoid rows deletion, which can lead to #Ref issue in formulae.

Sub ListReset(lst As ListObject)
'clears a listObject while leaving row 1 empty, with formulae
    With lst
        If .ShowAutoFilter Then .AutoFilter.ShowAllData
        On Error Resume Next
        With .DataBodyRange
            .Offset(1).Rows.Clear
            .Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
        End With
        On Error GoTo 0
        .Resize .Range.Rows("1:2")
    End With
End Sub

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

I created a possibly faster implementation by using 0-1 range for RGBS and V and 0-6 range for Hue (avoiding the division), and grouping the cases into two categories:

#include <math.h>
#include <float.h>

void fromRGBtoHSV(float rgb[], float hsv[])
{
//    for(int i=0; i<3; ++i)
//        rgb[i] = max(0.0f, min(1.0f, rgb[i]));

     hsv[0] = 0.0f;
     hsv[2] = max(rgb[0], max(rgb[1], rgb[2]));
     const float delta = hsv[2] - min(rgb[0], min(rgb[1], rgb[2]));

     if (delta < FLT_MIN)
         hsv[1] = 0.0f;
     else
     {
         hsv[1] = delta / hsv[2];
         if (rgb[0] >= hsv[2])
         {
             hsv[0] = (rgb[1] - rgb[2]) / delta;
             if (hsv[0] < 0.0f)
                 hsv[0] += 6.0f;
         }
         else if (rgb[1] >= hsv[2])
             hsv[0] = 2.0f + (rgb[2] - rgb[0]) / delta;
         else
             hsv[0] = 4.0f + (rgb[0] - rgb[1]) / delta;
     }    
}

void fromHSVtoRGB(const float hsv[], float rgb[])
{
    if(hsv[1] < FLT_MIN)
        rgb[0] = rgb[1] = rgb[2] = hsv[2];
    else
    {
        const float h = hsv[0];
        const int i = (int)h;
        const float f = h - i;
        const float p = hsv[2] * (1.0f - hsv[1]);

        if (i & 1) {
            const float q = hsv[2] * (1.0f - (hsv[1] * f));
            switch(i) {
            case 1:
                rgb[0] = q;
                rgb[1] = hsv[2];
                rgb[2] = p;
                break;
            case 3:
                rgb[0] = p;
                rgb[1] = q;
                rgb[2] = hsv[2];
                break;
            default:
                rgb[0] = hsv[2];
                rgb[1] = p;
                rgb[2] = q;
                break;
            }
        }
        else
        {
            const float t = hsv[2] * (1.0f - (hsv[1] * (1.0f - f)));
            switch(i) {
            case 0:
                rgb[0] = hsv[2];
                rgb[1] = t;
                rgb[2] = p;
                break;
            case 2:
                rgb[0] = p;
                rgb[1] = hsv[2];
                rgb[2] = t;
                break;
            default:
                rgb[0] = t;
                rgb[1] = p;
                rgb[2] = hsv[2];
                break;
            }
        }
    }
}

For 0-255 range just * 255.0f + 0.5f and assign it to an unsigned char (or divide by 255.0 to get the opposite).

How to select rows with no matching entry in another table?

I Dont Knew Which one Is Optimized (compared to @AdaTheDev ) but This one seems to be quicker when I use (atleast for me)

SELECT id  FROM  table_1 EXCEPT SELECT DISTINCT (table1_id) table1_id FROM table_2

If You want to get any other specific attribute you can use:

SELECT COUNT(*) FROM table_1 where id in (SELECT id  FROM  table_1 EXCEPT SELECT DISTINCT (table1_id) table1_id FROM table_2);

Installing mcrypt extension for PHP on OSX Mountain Lion

sudo apt-get install php5-mcrypt

ln -s /etc/php5/mods-available/mcrypt.ini /etc/php5/fpm/conf.d/mcrypt.ini

service php5-fpm restart

service nginx restart

How to execute the start script with Nodemon

In package json:

{
  "name": "abc",
  "version": "0.0.1",
  "description": "my server",
  "scripts": {
    "start": "nodemon my_file.js"
  },
  "devDependencies": {
    "nodemon": "~1.3.8",
  },
  "dependencies": {

  }
}

Then from the terminal you can use npm start

Nodemon installation: https://www.npmjs.com/package/nodemon

HTTPS setup in Amazon EC2

Use Elastic Load Balacing, it supports SSL termination at the Load Balancer, including offloading SSL decryption from application instances and providing centralized management of SSL certificates.

Android Studio Checkout Github Error "CreateProcess=2" (Windows)

I faced same issue in android studio 3.2.1, solved the issue by setting git path in System Environment variable

C:\Program Files\Git\bin\,C:\Program Files\Git\bin\

And I imported the project once again and solved the issue!!!

Note : Check your android studio git settings has properly set the correct path to git.exe

enter image description here

Does JavaScript have the interface type (such as Java's 'interface')?

You need interfaces in Java since it is statically typed and the contract between classes should be known during compilation. In JavaScript it is different. JavaScript is dynamically typed; it means that when you get the object you can just check if it has a specific method and call it.

Selecting text in an element (akin to highlighting with your mouse)

I liked lepe's answer except for a few things:

  1. Browser-sniffing, jQuery or no isn't optimal
  2. DRY
  3. Doesn't work in IE8 if obj's parent doesn't support createTextRange
  4. Chrome's ability to use setBaseAndExtent should be leveraged (IMO)
  5. Will not select text spanning across multiple DOM elements (elements within the "selected" element). In other words if you call selText on a div containing multiple span elements, it will not select the text of each of those elements. That was a deal-breaker for me, YMMV.

Here's what I came up with, with a nod to lepe's answer for inspiration. I'm sure I'll be ridiculed as this is perhaps a bit heavy-handed (and actually could be moreso but I digress). But it works and avoids browser-sniffing and that's the point.

selectText:function(){

    var range,
        selection,
        obj = this[0],
        type = {
            func:'function',
            obj:'object'
        },
        // Convenience
        is = function(type, o){
            return typeof o === type;
        };

    if(is(type.obj, obj.ownerDocument)
        && is(type.obj, obj.ownerDocument.defaultView)
        && is(type.func, obj.ownerDocument.defaultView.getSelection)){

        selection = obj.ownerDocument.defaultView.getSelection();

        if(is(type.func, selection.setBaseAndExtent)){
            // Chrome, Safari - nice and easy
            selection.setBaseAndExtent(obj, 0, obj, $(obj).contents().size());
        }
        else if(is(type.func, obj.ownerDocument.createRange)){

            range = obj.ownerDocument.createRange();

            if(is(type.func, range.selectNodeContents)
                && is(type.func, selection.removeAllRanges)
                && is(type.func, selection.addRange)){
                // Mozilla
                range.selectNodeContents(obj);
                selection.removeAllRanges();
                selection.addRange(range);
            }
        }
    }
    else if(is(type.obj, document.body) && is(type.obj, document.body.createTextRange)) {

        range = document.body.createTextRange();

        if(is(type.obj, range.moveToElementText) && is(type.obj, range.select)){
            // IE most likely
            range.moveToElementText(obj);
            range.select();
        }
    }

    // Chainable
    return this;
}

That's it. Some of what you see is the for readability and/or convenience. Tested on Mac in latest versions of Opera, Safari, Chrome, Firefox and IE. Also tested in IE8. Also I typically only declare variables if/when needed inside code blocks but jslint suggested they all be declared up top. Ok jslint.

Edit I forgot to include how to tie this in to the op's code:

function SelectText(element) {
    $("#" + element).selectText();
}

Cheers

Java default constructor

When you create a new Module object, java compiler add a default constructor for you because there is no constructor at all.

class Module{} // you will never see the default constructor

If you add any kind of constructor even and non-arg one, than java thing you have your own and don't add a default constructor anymore.

This is an non-arg constructor that internelly call the super() constructor from his parent class even you don't have one. (if your class don't have a parent class than Object.Class constructor will be call)

    class Module{

        Module() {} // this look like a default constructor but in not. 
    }

How to use SVG markers in Google Maps API v3

As mentioned by others in this thread, don't forget to explicitly set the width and height attributes in the svg like so:

<svg id="some_id" data-name="some_name" xmlns="http://www.w3.org/2000/svg"
     viewBox="0 0 26 42"
     width="26px" height="42px">

if you don't do that no js manipulation can help you as gmaps will not have a frame of reference and always use a standard size.

(i know it has been mentioned in some comments, but they are easy to miss. This information helped me in various cases)

Mockito: Trying to spy on method is calling the original method

One more possible scenario which may causing issues with spies is when you're testing spring beans (with spring test framework) or some other framework that is proxing your objects during test.

Example

@Autowired
private MonitoringDocumentsRepository repository

void test(){
    repository = Mockito.spy(repository)
    Mockito.doReturn(docs1, docs2)
            .when(repository).findMonitoringDocuments(Mockito.nullable(MonitoringDocumentSearchRequest.class));
}

In above code both Spring and Mockito will try to proxy your MonitoringDocumentsRepository object, but Spring will be first, which will cause real call of findMonitoringDocuments method. If we debug our code just after putting a spy on repository object it will look like this inside debugger:

repository = MonitoringDocumentsRepository$$EnhancerBySpringCGLIB$$MockitoMock$

@SpyBean to the rescue

If instead @Autowired annotation we use @SpyBean annotation, we will solve above problem, the SpyBean annotation will also inject repository object but it will be firstly proxied by Mockito and will look like this inside debugger

repository = MonitoringDocumentsRepository$$MockitoMock$$EnhancerBySpringCGLIB$

and here is the code:

@SpyBean
private MonitoringDocumentsRepository repository

void test(){
    Mockito.doReturn(docs1, docs2)
            .when(repository).findMonitoringDocuments(Mockito.nullable(MonitoringDocumentSearchRequest.class));
}

ionic build Android | error: No installed build tools found. Please install the Android build tools

Warning for developers using Virtual Machines

I spent a very long time trying to resolve this issue. I tried everything in this post and many more solutions on the web. However, after many failures and going through what everyone on the web was saying I still couldn't resolve the issue on my VM - which is a Windows 10 image on VMWare Workstation.

After reviewing all the solutions and descriptions of machines/operating systems people were developing on the glaring difference in my setup was I was developing in a VM.

Solution: I pulled all my code onto the host machine (Windows 10 OS), reinstalled all the dependencies, and sure as heck it all worked out first go around. After a lot of research I found some warnings that Android Studio has some known issues around installing properly in some VMs. So if you were like me & tried all solutions (many times over) and nothing worked, but you're in a VM, you may need to consider building on your host (or other physical machine)

How can I nullify css property?

.c1 {
    height: unset;
}

The unset value added in CSS3 also solves this problem and it's even more universal method than auto or initial because it sets to every CSS property its default value and additionally its default behawior relative to its parent.

Note that initial value breaks aforementioned behavior.

From MDN:

Like these two other CSS-wide keywords, it can be applied to any CSS property, including the CSS shorthand all. This keyword resets the property to its inherited value if it inherits from its parent or to its initial value if not.

C: socket connection timeout

The two socket options SO_RCVTIMEO and SO_SNDTIMEO have no effect on connect. Below is a link to the screenshot which includes this explanation, here I am just briefing it. The apt way of implementing timeouts with connect are using signal or select or poll.

Signals

connect can be interrupted by a self generated signal SIGALRM by using syscall (wrapper) alarm. But, a signal disposition should be installed for the same signal otherwise the program would be terminated. The code goes like this...

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<signal.h>
#include<errno.h>

static void signal_handler(int signo)
{
    return; // Do nothing just interrupt.
}

int main()
{
    /* Register signal handler */

    struct sigaction act, oact;

    act.sa_handler = signal_handler;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;

#ifdef SA_INTERRUPT
    act.sa_flags |= SA_INTERRUPT;
#endif

    if(sigaction(SIGALRM, &act, &oact) < 0)  // Error registering signal handler.
    {
        fprintf(stderr, "Error registering signal disposition\n");
        exit(1);
    }

    /* Prepare your socket and sockaddr structures */

    int sockfd;
    struct sockaddr* servaddr;

    /* Implementing timeout connect */

    int sec = 30;

    if(alarm(sec) != 0)
        fprintf(stderr, "Already timer was set\n");

    if(connect(sockfd, servaddr, sizeof(struct sockaddr)) < 0)
    {
        if(errno == EINTR)
            fprintf(stderr, "Connect timeout\n");
        else
            fprintf(stderr, "Connect failed\n");

        close(sockfd);

        exit(1);
    }

    alarm(0);  /* turn off the alarm */

    sigaction(SIGALRM, &oact, NULL);  /* Restore the default actions of SIGALRM */

    /* Use socket */


    /* End program */

    close(sockfd);
    return 0;
}

Select or Poll

As already some users provided nice explanation on how to use select to achieve connect timeout, it would not be necessary for me to reiterate the same. poll can be used in the same way. However, there are few mistakes that are common in all of the answers, which I would like to address.

  • Even though socket is non-blocking, if the server to which we are connecting is on the same local machine, connect may return with success. So it is advised to check the return value of connect before calling select.

  • Berkeley-derived implementations (and POSIX) have the following rules for non-blocking sockets and connect.

    1) When the connection completes successfully, the descriptor becomes writable (p. 531 of TCPv2).

    2) When the connection establishment encounters an error, the descriptor becomes both readable and writable (p. 530 of TCPv2).

So the code should handle these cases, here I just code the necessary modifications.

/* All the code stays */

/* Modifications at connect */

int conn_ret = connect(sockfd, servaddr, sizeof(struct sockdaddr));

if(conn_ret == 0)
    goto done;

/* Modifications at select */

int sec = 30;
for( ; ; )
{
    struct timeval timeo;
    timeo.tv_sec = sec;
    timeo.tv_usec = 0;

    fd_set wr_set, rd_set;
    FDZERO(&wr_set);
    FD_SET(sockfd, &wr_set);
    rd_set = wr_set;
    int sl_ret = select(sockfd + 1, &rd_set, &wr_set, NULL, &timeo);

    /* All the code stays */
}


done:

    /* Use your socket */

Text from Unix Network Programming Volume 1

How do you build a Singleton in Dart?

After reading all the alternatives I came up with this, which reminds me a "classic singleton":

class AccountService {
  static final _instance = AccountService._internal();

  AccountService._internal();

  static AccountService getInstance() {
    return _instance;
  }
}

How to check if a float value is a whole number

>>> def is_near_integer(n, precision=8, get_integer=False):
...     if get_integer:
...         return int(round(n, precision))
...     else:
...         return round(n) == round(n, precision)
...
>>> print(is_near_integer(10648 ** (1.0/3)))
True
>>> print(is_near_integer(10648 ** (1.0/3), get_integer=True))
22
>>> for i in [4.9, 5.1, 4.99, 5.01, 4.999, 5.001, 4.9999, 5.0001, 4.99999, 5.000
01, 4.999999, 5.000001]:
...     print(i, is_near_integer(i, 4))
...
4.9 False
5.1 False
4.99 False
5.01 False
4.999 False
5.001 False
4.9999 False
5.0001 False
4.99999 True
5.00001 True
4.999999 True
5.000001 True
>>>

How do you get the index of the current iteration of a foreach loop?

Why foreach ?!

The simplest way is using for instead of foreach if you are using List:

for (int i = 0 ; i < myList.Count ; i++)
{
    // Do something...
}

Or if you want use foreach:

foreach (string m in myList)
{
     // Do something...
}

You can use this to know the index of each loop:

myList.indexOf(m)

How to bundle vendor scripts separately and require them as needed with Webpack?

Also not sure if I fully understand your case, but here is config snippet to create separate vendor chunks for each of your bundles:

entry: {
  bundle1: './build/bundles/bundle1.js',
  bundle2: './build/bundles/bundle2.js',
  'vendor-bundle1': [
    'react',
    'react-router'
  ],
  'vendor-bundle2': [
    'react',
    'react-router',
    'flummox',
    'immutable'
  ]
},

plugins: [
  new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor-bundle1',
    chunks: ['bundle1'],
    filename: 'vendor-bundle1.js',
    minChunks: Infinity
  }),
  new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor-bundle2',
    chunks: ['bundle2'],
    filename: 'vendor-bundle2-whatever.js',
    minChunks: Infinity
  }),
]

And link to CommonsChunkPlugin docs: http://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin

Should I always use a parallel stream when possible?

Never parallelize an infinite stream with a limit. Here is what happens:

    public static void main(String[] args) {
        // let's count to 1 in parallel
        System.out.println(
            IntStream.iterate(0, i -> i + 1)
                .parallel()
                .skip(1)
                .findFirst()
                .getAsInt());
    }

Result

    Exception in thread "main" java.lang.OutOfMemoryError
        at ...
        at java.base/java.util.stream.IntPipeline.findFirst(IntPipeline.java:528)
        at InfiniteTest.main(InfiniteTest.java:24)
    Caused by: java.lang.OutOfMemoryError: Java heap space
        at java.base/java.util.stream.SpinedBuffer$OfInt.newArray(SpinedBuffer.java:750)
        at ...

Same if you use .limit(...)

Explanation here: Java 8, using .parallel in a stream causes OOM error

Similarly, don't use parallel if the stream is ordered and has much more elements than you want to process, e.g.

public static void main(String[] args) {
    // let's count to 1 in parallel
    System.out.println(
            IntStream.range(1, 1000_000_000)
                    .parallel()
                    .skip(100)
                    .findFirst()
                    .getAsInt());
}

This may run much longer because the parallel threads may work on plenty of number ranges instead of the crucial one 0-100, causing this to take very long time.

Reference member variables as class members

It's called dependency injection via constructor injection: class A gets the dependency as an argument to its constructor and saves the reference to dependent class as a private variable.

There's an interesting introduction on wikipedia.

For const-correctness I'd write:

using T = int;

class A
{
public:
  A(const T &thing) : m_thing(thing) {}
  // ...

private:
   const T &m_thing;
};

but a problem with this class is that it accepts references to temporary objects:

T t;
A a1{t};    // this is ok, but...

A a2{T()};  // ... this is BAD.

It's better to add (requires C++11 at least):

class A
{
public:
  A(const T &thing) : m_thing(thing) {}
  A(const T &&) = delete;  // prevents rvalue binding
  // ...

private:
  const T &m_thing;
};

Anyway if you change the constructor:

class A
{
public:
  A(const T *thing) : m_thing(*thing) { assert(thing); }
  // ...

private:
   const T &m_thing;
};

it's pretty much guaranteed that you won't have a pointer to a temporary.

Also, since the constructor takes a pointer, it's clearer to users of A that they need to pay attention to the lifetime of the object they pass.


Somewhat related topics are:

Android Studio Gradle DSL method not found: 'android()' -- Error(17,0)

I have tried to manage this issue via below steps :

Delete android { ... } block in top level root gradle file

Look into

 compileSdkVersion 22
 buildToolsVersion "22.0.0"

lines of code in app/gradle file here only one of the version persent in below dropdown should be present else it would give provide option to downloaad the same.

enter image description here

How to edit nginx.conf to increase file size upload

You can increase client_max_body_size and upload_max_filesize + post_max_size all day long. Without adjusting HTTP timeout it will never work.

//You need to adjust this, and probably on PHP side also. client_body_timeout 2min // 1GB fileupload

Can't find file executable in your configured search path for gnc gcc compiler

Just open your setting->compiler and click on the reset defaults and it will start work.

Conditionally Remove Dataframe Rows with R

Use the which function:

A <- c('a','a','b','b','b')
B <- c(1,0,1,1,0)
d <- data.frame(A, B)

r <- with(d, which(B==0, arr.ind=TRUE))
newd <- d[-r, ]

How to animate a View with Translate Animation in Android

In order to move a View anywhere on the screen, I would recommend placing it in a full screen layout. By doing so, you won't have to worry about clippings or relative coordinates.

You can try this sample code:

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" android:id="@+id/rootLayout">

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="MOVE" android:layout_centerHorizontal="true"/>

    <ImageView
        android:id="@+id/img1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_marginLeft="10dip"/>
    <ImageView
        android:id="@+id/img2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_centerVertical="true" android:layout_alignParentRight="true"/>
    <ImageView
        android:id="@+id/img3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_alignParentBottom="true" android:layout_marginBottom="100dip"/>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" android:clipChildren="false" android:clipToPadding="false">

        <ImageView
            android:id="@+id/img4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_marginTop="150dip"/>
    </LinearLayout>

</RelativeLayout>

Your activity

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ((Button) findViewById( R.id.btn1 )).setOnClickListener( new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            ImageView img = (ImageView) findViewById( R.id.img1 );              
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img2 );
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img3 );                
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img4 );
            moveViewToScreenCenter( img );
        }
    });
}

private void moveViewToScreenCenter( View view )
{
    RelativeLayout root = (RelativeLayout) findViewById( R.id.rootLayout );
    DisplayMetrics dm = new DisplayMetrics();
    this.getWindowManager().getDefaultDisplay().getMetrics( dm );
    int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();

    int originalPos[] = new int[2];
    view.getLocationOnScreen( originalPos );

    int xDest = dm.widthPixels/2;
    xDest -= (view.getMeasuredWidth()/2);
    int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;

    TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
    anim.setDuration(1000);
    anim.setFillAfter( true );
    view.startAnimation(anim);
}

The method moveViewToScreenCenter gets the View's absolute coordinates and calculates how much distance has to move from its current position to reach the center of the screen. The statusBarOffset variable measures the status bar height.

I hope you can keep going with this example. Remember that after the animation your view's position is still the initial one. If you tap the MOVE button again and again the same movement will repeat. If you want to change your view's position do it after the animation is finished.

CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page

Some solutions didn't work for me but the best option I found was the example below when i decided to use the flex option.

_x000D_
_x000D_
html, body{
    height: 100%;   
}

body{
    display: flex;
    flex-direction: column;
}

.main-contents{ 
    flex: 1 0 auto;
    min-height: 100%;
    margin-bottom: -77px;
  background-color: #CCC;
}

.footer{
    height:  77px;
    min-height: 77px;
    width: 100%;
    bottom: 0;
    left: 0;
    background: #000000;
    flex-shrink: 0;
    flex-direction: row;
    position: relative;
    
    
}

.footer-text{
  color: #FFF;
}

@media screen and (max-width: 767px){
    #content{
        padding-bottom: 0;
    }
    .footer{
        position: relative;
        /*position: absolute;*/
        height: 77px;
        width: 100%;
        bottom: 0;
        left: 0;
    }

}
_x000D_
<html>
  <body>
    <div class="main-contents" >
      this is the main content
    </div>
  </body>

  <footer class="footer">
    <p class="footer-text">This is the sticky footer</p>
  </footer>

</html>
_x000D_
_x000D_
_x000D_

Get output parameter value in ADO.NET

That looks more explicit for me:

int? id = outputIdParam.Value is DbNull ? default(int?) : outputIdParam.Value;

Java: Sending Multiple Parameters to Method

Suppose you have void method that prints many objects;

public static void print( Object... values){
   for(Object c : values){
      System.out.println(c);
   }
}

Above example I used vararge as an argument that accepts values from 0 to N.

From comments: What if 2 strings and 5 integers ??

Answer:

print("string1","string2",1,2,3,4,5);

How to get a random number between a float range?

Use random.uniform(a, b):

>>> random.uniform(1.5, 1.9)
1.8733202628557872

How to update/refresh specific item in RecyclerView

In your RecyclerView adapter, you should have an ArrayList and also one method addItemsToList(items) to add list items to the ArrayList. Then you can add list items by call adapter.addItemsToList(items) dynamically. After all your list items added to the ArrayList then you can call adapter.notifyDataSetChanged() to display your list.

You can use the notifyDataSetChanged in the adapter for the RecyclerView

Calculate logarithm in python

From the documentation:

With one argument, return the natural logarithm of x (to base e).

With two arguments, return the logarithm of x to the given base, calculated as log(x)/log(base).

But the log10 is made available as math.log10(), which does not resort to log division if possible.

Creating a REST API using PHP

In your example, it’s fine as it is: it’s simple and works. The only things I’d suggest are:

  1. validating the data POSTed
  2. make sure your API is sending the Content-Type header to tell the client to expect a JSON response:

    header('Content-Type: application/json');
    echo json_encode($response);
    

Other than that, an API is something that takes an input and provides an output. It’s possible to “over-engineer” things, in that you make things more complicated that need be.

If you wanted to go down the route of controllers and models, then read up on the MVC pattern and work out how your domain objects fit into it. Looking at the above example, I can see maybe a MathController with an add() action/method.

There are a few starting point projects for RESTful APIs on GitHub that are worth a look.

How do I delay a function call for 5 seconds?

You can use plain javascript, this will call your_func once, after 5 seconds:

setTimeout(function() { your_func(); }, 5000);

If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)

There is also a plugin I've used once. It has oneTime and everyTime methods.

select dept names who have more than 2 employees whose salary is greater than 1000

SELECT DEPTNAME
FROM(SELECT D.DEPTNAME,COUNT(EMPID) AS TOTEMP
     FROM DEPT AS D,EMPLOYEE AS E
     WHERE D.DEPTID=E.DEPTID AND SALARY>1000
     GROUP BY D.DEPTID
     )
WHERE TOTEMP>2;

Selecting default item from Combobox C#

Remember that collections in C# are zero-based (in other words, the first item in a collection is at position zero). If you have two items in your list, and you want to select the last item, use SelectedIndex = 1.

Determine the data types of a data frame's columns

Here is a function that is part of the helpRFunctions package that will return a list of all of the various data types in your data frame, as well as the specific variable names associated with that type.

install.package('devtools') # Only needed if you dont have this installed.
library(devtools)
install_github('adam-m-mcelhinney/helpRFunctions')
library(helpRFunctions)
my.data <- data.frame(y=rnorm(5), 
                  x1=c(1:5), 
                  x2=c(TRUE, TRUE, FALSE, FALSE, FALSE),
                  X3=letters[1:5])
t <- list.df.var.types(my.data)
t$factor
t$integer
t$logical
t$numeric

You could then do something like var(my.data[t$numeric]).

Hope this is helpful!

Permissions error when connecting to EC2 via SSH on Mac OSx

Tagging on to mecca831's answer:

ssh -v -i generated-key.pem [email protected]

[[email protected] ~]$ sudo passwd ec2-user newpassword newpassword

[[email protected] ~]$ sudo vi /etc/ssh/sshd_config Modify the file as follows:

    # To disable tunneled clear text passwords, change to no here!
    PasswordAuthentication yes
    #PermitEmptyPasswords no
    # EC2 uses keys for remote access
    #PasswordAuthentication no

Save

[[email protected] ~]$ sudo service sshd stop [[email protected] ~]$ sudo service sshd start

you should be able to exit and ssh in as follows:

ssh [email protected]

and be prompted for password no longer needing the key.

How to change background and text colors in Sublime Text 3

To view Theme files for ST3, install PackageResourceViewer via PackageControl.

Then, you can use the Ctrl + Shift + P >> PackageResourceViewer: Open Resource to view theme files.

To edit a specific background color, you need to create a new file in your user packages folder Packages/User/SublimeLinter with the same name as the theme currently applied to your sublime text file.

However, if your theme is a 3rd party theme package installed via package control, you can edit the hex value in that file directly, under background. For example:


<dict>
  <dict>
    <key>background</key>
    <string>#073642</string>
  </dict>
</dict>

Otherwise, if you are trying to modify a native sublime theme, add the following to the new file you create (named the same as the native theme, such as Monokai.sublime-color-scheme) with your color choice


{
  "globals":
  {
      "background": "rgb(5,5,5)"
  }
}

Then, you can open the file you wish the syntax / color to be applied to and then go to Syntax-Specific settings (under Preferences) and add the path of the file to the syntax specific settings file like so:


{
    "color_scheme": "Packages/User/SublimeLinter/Monokai.sublime-color-scheme"
}

Note that if you have installed a theme via package control, it probably has the .tmTheme file extension.

If you are wanting to edit the background color of the sidebar to be darker, go to Preferences > Theme > Adaptive.sublime-theme

This my answer based on my personal experience and info gleaned from the accepted answer on this page, if you'd like more information.

Catching FULL exception message

Errors and exceptions in PowerShell are structured objects. The error message you see printed on the console is actually a formatted message with information from several elements of the error/exception object. You can (re-)construct it yourself like this:

$formatstring = "{0} : {1}`n{2}`n" +
                "    + CategoryInfo          : {3}`n" +
                "    + FullyQualifiedErrorId : {4}`n"
$fields = $_.InvocationInfo.MyCommand.Name,
          $_.ErrorDetails.Message,
          $_.InvocationInfo.PositionMessage,
          $_.CategoryInfo.ToString(),
          $_.FullyQualifiedErrorId

$formatstring -f $fields

If you just want the error message displayed in your catch block you can simply echo the current object variable (which holds the error at that point):

try {
  ...
} catch {
  $_
}

If you need colored output use Write-Host with a formatted string as described above:

try {
  ...
} catch {
  ...
  Write-Host -Foreground Red -Background Black ($formatstring -f $fields)
}

With that said, usually you don't want to just display the error message as-is in an exception handler (otherwise the -ErrorAction Stop would be pointless). The structured error/exception objects provide you with additional information that you can use for better error control. For instance you have $_.Exception.HResult with the actual error number. $_.ScriptStackTrace and $_.Exception.StackTrace, so you can display stacktraces when debugging. $_.Exception.InnerException gives you access to nested exceptions that often contain additional information about the error (top level PowerShell errors can be somewhat generic). You can unroll these nested exceptions with something like this:

$e = $_.Exception
$msg = $e.Message
while ($e.InnerException) {
  $e = $e.InnerException
  $msg += "`n" + $e.Message
}
$msg

In your case the information you want to extract seems to be in $_.ErrorDetails.Message. It's not quite clear to me if you have an object or a JSON string there, but you should be able to get information about the types and values of the members of $_.ErrorDetails by running

$_.ErrorDetails | Get-Member
$_.ErrorDetails | Format-List *

If $_.ErrorDetails.Message is an object you should be able to obtain the message string like this:

$_.ErrorDetails.Message.message

otherwise you need to convert the JSON string to an object first:

$_.ErrorDetails.Message | ConvertFrom-Json | Select-Object -Expand message

Depending what kind of error you're handling, exceptions of particular types might also include more specific information about the problem at hand. In your case for instance you have a WebException which in addition to the error message ($_.Exception.Message) contains the actual response from the server:

PS C:\> $e.Exception | Get-Member

   TypeName: System.Net.WebException

Name             MemberType Definition
----             ---------- ----------
Equals           Method     bool Equals(System.Object obj), bool _Exception.E...
GetBaseException Method     System.Exception GetBaseException(), System.Excep...
GetHashCode      Method     int GetHashCode(), int _Exception.GetHashCode()
GetObjectData    Method     void GetObjectData(System.Runtime.Serialization.S...
GetType          Method     type GetType(), type _Exception.GetType()
ToString         Method     string ToString(), string _Exception.ToString()
Data             Property   System.Collections.IDictionary Data {get;}
HelpLink         Property   string HelpLink {get;set;}
HResult          Property   int HResult {get;}
InnerException   Property   System.Exception InnerException {get;}
Message          Property   string Message {get;}
Response         Property   System.Net.WebResponse Response {get;}
Source           Property   string Source {get;set;}
StackTrace       Property   string StackTrace {get;}
Status           Property   System.Net.WebExceptionStatus Status {get;}
TargetSite       Property   System.Reflection.MethodBase TargetSite {get;}

which provides you with information like this:

PS C:\> $e.Exception.Response

IsMutuallyAuthenticated : False
Cookies                 : {}
Headers                 : {Keep-Alive, Connection, Content-Length, Content-T...}
SupportsHeaders         : True
ContentLength           : 198
ContentEncoding         :
ContentType             : text/html; charset=iso-8859-1
CharacterSet            : iso-8859-1
Server                  : Apache/2.4.10
LastModified            : 17.07.2016 14:39:29
StatusCode              : NotFound
StatusDescription       : Not Found
ProtocolVersion         : 1.1
ResponseUri             : http://www.example.com/
Method                  : POST
IsFromCache             : False

Since not all exceptions have the exact same set of properties you may want to use specific handlers for particular exceptions:

try {
  ...
} catch [System.ArgumentException] {
  # handle argument exceptions
} catch [System.Net.WebException] {
  # handle web exceptions
} catch {
  # handle all other exceptions
}

If you have operations that need to be done regardless of whether an error occured or not (cleanup tasks like closing a socket or a database connection) you can put them in a finally block after the exception handling:

try {
  ...
} catch {
  ...
} finally {
  # cleanup operations go here
}

How to Read and Write from the Serial Port

Note that usage of a SerialPort.DataReceived event is optional. You can set proper timeout using SerialPort.ReadTimeout and continuously call SerialPort.Read() after you wrote something to a port until you get a full response.

Moreover you can use SerialPort.BaseStream property to extract an underlying Stream instance. The benefit of using a Stream is that you can easily utilize various decorators with it:

var port = new SerialPort();
// LoggingStream inherits Stream, implements IDisposable, needen abstract methods and 
// overrides needen virtual methods. 
Stream portStream = new LoggingStream(port.BaseStream);
portStream.Write(...); // Logs write buffer.
portStream.Read(...); // Logs read buffer.

For more information check:

How to pass parameters on onChange of html select

jQuery solution

How do I get the text value of a selected option

Select elements typically have two values that you want to access.
First there's the value to be sent to the server, which is easy:

$( "#myselect" ).val();
// => 1

The second is the text value of the select.
For example, using the following select box:

<select id="myselect">
  <option value="1">Mr</option>
  <option value="2">Mrs</option>
  <option value="3">Ms</option>
  <option value="4">Dr</option>
  <option value="5">Prof</option>
</select>

If you wanted to get the string "Mr" if the first option was selected (instead of just "1") you would do that in the following way:

$( "#myselect option:selected" ).text();
// => "Mr"  

See also

Check for file exists or not in sql server?

You can achieve this using a cursor but the performance is much slower than whileloop.. Here's the code:

set nocount on
declare cur cursor local fast_forward for
    (select filepath from Directory)
open cur;
declare @fullpath varchar(250);
declare @isExists int;

fetch from cur into @fullpath
while @@FETCH_STATUS = 0
    begin
        exec xp_fileexist @fullpath, @isExists out
        if @isExists = 1            
            print @fullpath + char(9) + char(9) + 'file exists'
        else            
            print @fullpath + char(9) + char(9) + 'file does not exists'
        fetch from cur into @fullpath
    end
close cur
deallocate cur

or you can put it in a tempTable if you want to integrate it in your frontend..

create proc GetFileStatus as
begin
    set nocount on
    create table #tempFileStatus(FilePath varchar(300),FileStatus varchar(30))
    declare cur cursor local fast_forward for
        (select filepath from Directory)
    open cur;
    declare @fullpath varchar(250);
    declare @isExists int;

    fetch from cur into @fullpath
    while @@FETCH_STATUS = 0
        begin
            exec xp_fileexist @fullpath, @isExists out
            if @isExists = 1                
                insert into #tempFileStatus values(@fullpath,'File exist')
            else
                insert into #tempFileStatus values(@fullpath,'File does not exists')
            fetch from cur into @fullpath
        end
    close cur
    deallocate cur
    select * from #tempFileStatus
    drop table #tempFileStatus
end

then call it using:

exec GetFileStatus

Binary numbers in Python

If you're talking about bitwise operators, then you're after:

~ Not
^ XOR
| Or
& And

Otherwise, binary numbers work exactly the same as decimal numbers, because numbers are numbers, no matter how you look at them. The only difference between decimal and binary is how we represent that data when we are looking at it.

PHP json_encode json_decode UTF-8

json utf8 encode and decode:

json_encode($data, JSON_UNESCAPED_UNICODE)

json_decode($json, false, 512, JSON_UNESCAPED_UNICODE)

force utf8 might be helpfull too: http://pastebin.com/2XKqYU49

Git Pull While Ignoring Local Changes?

I usually do:

git checkout .
git pull

In the project's root folder.

How to add class active on specific li on user click with jQuery

 $(document).ready(function () {
    $('.dates li a').click(function (e) {

        $('.dates li a').removeClass('active');

        var $parent = $(this);
        if (!$parent.hasClass('active')) {
            $parent.addClass('active');
        }
        e.preventDefault();
    });
});

How to fill in proxy information in cntlm config file?

Without any configuration, you can simply issue the following command (modifying myusername and mydomain with your own information):

cntlm -u myusername -d mydomain -H

or

cntlm -u myusername@mydomain -H

It will ask you the password of myusername and will give you the following output:

PassLM          1AD35398BE6565DDB5C4EF70C0593492
PassNT          77B9081511704EE852F94227CF48A793
PassNTLMv2      A8FC9092D566461E6BEA971931EF1AEC    # Only for user 'myusername', domain 'mydomain'

Then create the file cntlm.ini (or cntlm.conf on Linux using default path) with the following content (replacing your myusername, mydomain and A8FC9092D566461E6BEA971931EF1AEC with your information and the result of the previous command):

Username    myusername
Domain      mydomain

Proxy       my_proxy_server.com:80
NoProxy     127.0.0.*, 192.168.*

Listen      127.0.0.1:5865
Gateway     yes

SOCKS5Proxy 5866

Auth        NTLMv2
PassNTLMv2  A8FC9092D566461E6BEA971931EF1AEC

Then you will have a local open proxy on local port 5865 and another one understanding SOCKS5 protocol at local port 5866.

How do I indent multiple lines at once in Notepad++?

If you're using QuickText and like pressing Tab for it, you can otherwise change the indentation key.

Go Settings > Shortcup Mapper > Scintilla Command. Look at the number 10.

  • I changed 10 to : CTRL + ALT + RIGHT and
  • 11 to : CTRL+ ALT+ LEFT.

Now I think it's even better than the TABL / SHIFT + TAB as default.

How do I sort an observable collection?

This worked for me, found it long time ago somewhere.

// SortableObservableCollection
public class SortableObservableCollection<T> : ObservableCollection<T>
    {
        public SortableObservableCollection(List<T> list)
            : base(list)
        {
        }

        public SortableObservableCollection()
        {
        }

        public void Sort<TKey>(Func<T, TKey> keySelector, System.ComponentModel.ListSortDirection direction)
        {
            switch (direction)
            {
                case System.ComponentModel.ListSortDirection.Ascending:
                    {
                        ApplySort(Items.OrderBy(keySelector));
                        break;
                    }
                case System.ComponentModel.ListSortDirection.Descending:
                    {
                        ApplySort(Items.OrderByDescending(keySelector));
                        break;
                    }
            }
        }

        public void Sort<TKey>(Func<T, TKey> keySelector, IComparer<TKey> comparer)
        {
            ApplySort(Items.OrderBy(keySelector, comparer));
        }

        private void ApplySort(IEnumerable<T> sortedItems)
        {
            var sortedItemsList = sortedItems.ToList();

            foreach (var item in sortedItemsList)
            {
                Move(IndexOf(item), sortedItemsList.IndexOf(item));
            }
        }
    }

Usage:

MySortableCollection.Sort(x => x, System.ComponentModel.ListSortDirection.Ascending);

Convert String to SecureString

You don't. The whole reason for using the SecureString object is to avoid creating a string object (which is loaded into memory and kept there in plaintext until garbage collection). However, you can add characters to a SecureString by appending them.

var s = new SecureString();
s.AppendChar('d');
s.AppendChar('u');
s.AppendChar('m');
s.AppendChar('b');
s.AppendChar('p');
s.AppendChar('a');
s.AppendChar('s');
s.AppendChar('s');
s.AppendChar('w');
s.AppendChar('d');

SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>

you can use this option for call soap with wdsl :

$opts = array(
            'http' => array(
                'user_agent' => 'PHPSoapClient'
            )
        );
        $context = stream_context_create($opts);

        $soapClientOptions = array(
            'stream_context' => $context,
            'cache_wsdl' => WSDL_CACHE_NONE
        );

        $wsdlUrl = 'your wsdl url';
        $soapClient = new SoapClient($wsdlUrl, $soapClientOptions);

        $result = $soapClient->VerifyTransaction($refNum, $MerchantCode);

Spring Boot: How can I set the logging level with application.properties?

You can do that using your application.properties.

logging.level.=ERROR -> Sets the root logging level to error
...
logging.level.=DEBUG -> Sets the root logging level to DEBUG

logging.file=${java.io.tmpdir}/myapp.log -> Sets the absolute log file path to TMPDIR/myapp.log

A sane default set of application.properties regarding logging using profiles would be: application.properties:

spring.application.name=<your app name here>
logging.level.=ERROR
logging.file=${java.io.tmpdir}/${spring.application.name}.log

application-dev.properties:

logging.level.=DEBUG
logging.file=

When you develop inside your favourite IDE you just add a -Dspring.profiles.active=dev as VM argument to the run/debug configuration of your app.

This will give you error only logging in production and debug logging during development WITHOUT writing the output to a log file. This will improve the performance during development ( and save SSD drives some hours of operation ;) ).

How to parse json string in Android?

Below is the link which guide in parsing JSON string in android.

http://www.ibm.com/developerworks/xml/library/x-andbene1/?S_TACT=105AGY82&S_CMP=MAVE

Also according to your json string code snippet must be something like this:-

JSONObject mainObject = new JSONObject(yourstring);

JSONObject universityObject = mainObject.getJSONObject("university");
JSONString name = universityObject.getString("name");  
JSONString url = universityObject.getString("url");

Following is the API reference for JSOnObject: https://developer.android.com/reference/org/json/JSONObject.html#getString(java.lang.String)

Same for other object.

Spark java.lang.OutOfMemoryError: Java heap space

You should increase the driver memory. In your $SPARK_HOME/conf folder you should find the file spark-defaults.conf, edit and set the spark.driver.memory 4000m depending on the memory on your master, I think. This is what fixed the issue for me and everything runs smoothly

Find IP address of directly connected device

To use DHCP, you'd have to run a DHCP server on the primary and a client on the secondary; the primary could then query the server to find out what address it handed out. Probably overkill.

I can't help you with Windows directly. On Unix, the "arp" command will tell you what IP addresses are known to be attached to the local ethernet segment. Windows will have this same information (since it's a core part of the IP/Ethernet interface) but I don't know how you get at it.

Of course, the networking stack will only know about the other host if it has previously seen traffic from it. You may have to first send a broadcast packet on the interface to elicit some sort of response and thus populate the local ARP table.

Formatting dates on X axis in ggplot2

To show months as Jan 2017 Feb 2017 etc:

scale_x_date(date_breaks = "1 month", date_labels =  "%b %Y") 

Angle the dates if they take up too much space:

theme(axis.text.x=element_text(angle=60, hjust=1))

What is the purpose of Order By 1 in SQL select statement?

I believe in Oracle it means order by column #1

Redirect from an HTML page

Redirect using JavaScript, <noscript> in case JS is disabled.

<script>
    window.location.replace("https://google.com");
</script>

<noscript>
    <a href="https://google.com">Click here if you are not redirected automatically.</a>
</noscript>

How to use sed to replace only the first occurrence in a file?

 # sed script to change "foo" to "bar" only on the first occurrence
 1{x;s/^/first/;x;}
 1,/foo/{x;/first/s///;x;s/foo/bar/;}
 #---end of script---

or, if you prefer: Editor's note: works with GNU sed only.

sed '0,/foo/s//bar/' file 

Source

How to change column width in DataGridView?

You could set the width of the abbrev column to a fixed pixel width, then set the width of the description column to the width of the DataGridView, minus the sum of the widths of the other columns and some extra margin (if you want to prevent a horizontal scrollbar from appearing on the DataGridView):

dataGridView1.Columns[1].Width = 108;  // or whatever width works well for abbrev
dataGridView1.Columns[2].Width = 
    dataGridView1.Width 
    - dataGridView1.Columns[0].Width 
    - dataGridView1.Columns[1].Width 
    - 72;  // this is an extra "margin" number of pixels

If you wanted the description column to always take up the "remainder" of the width of the DataGridView, you could put something like the above code in a Resize event handler of the DataGridView.

How to push to History in React Router v4?

React Router v4 is fundamentally different from v3 (and earlier) and you cannot do browserHistory.push() like you used to.

This discussion seems related if you want more info:

  • Creating a new browserHistory won't work because <BrowserRouter> creates its own history instance, and listens for changes on that. So a different instance will change the url but not update the <BrowserRouter>.
  • browserHistory is not exposed by react-router in v4, only in v2.

Instead you have a few options to do this:

  • Use the withRouter high-order component

    Instead you should use the withRouter high order component, and wrap that to the component that will push to history. For example:

    import React from "react";
    import { withRouter } from "react-router-dom";
    
    class MyComponent extends React.Component {
      ...
      myFunction() {
        this.props.history.push("/some/Path");
      }
      ...
    }
    export default withRouter(MyComponent);
    

    Check out the official documentation for more info:

    You can get access to the history object’s properties and the closest <Route>'s match via the withRouter higher-order component. withRouter will re-render its component every time the route changes with the same props as <Route> render props: { match, location, history }.


  • Use the context API

    Using the context might be one of the easiest solutions, but being an experimental API it is unstable and unsupported. Use it only when everything else fails. Here's an example:

    import React from "react";
    import PropTypes from "prop-types";
    
    class MyComponent extends React.Component {
      static contextTypes = {
        router: PropTypes.object
      }
      constructor(props, context) {
         super(props, context);
      }
      ...
      myFunction() {
        this.context.router.history.push("/some/Path");
      }
      ...
    }
    

    Have a look at the official documentation on context:

    If you want your application to be stable, don't use context. It is an experimental API and it is likely to break in future releases of React.

    If you insist on using context despite these warnings, try to isolate your use of context to a small area and avoid using the context API directly when possible so that it's easier to upgrade when the API changes.

pgadmin4 : postgresql application server could not be contacted.

if you are using Mac OS X here is a fix: Open terminal and run this command

pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log restart

and for other OS just restart your Postgresql server, it will solve

Then start pgAdmin4, it will start as normal

Share or comment if saved someone

Using boolean values in C

From best to worse:

Option 1 (C99 and newer)

#include <stdbool.h>

Option 2

typedef enum { false, true } bool;

Option 3

typedef int bool;
enum { false, true };

Option 4

typedef int bool;
#define true 1
#define false 0

#Explanation

  • Option 1 will work only if you use C99 (or newer) and it's the "standard way" to do it. Choose this if possible.
  • Options 2, 3 and 4 will have in practice the same identical behavior. #2 and #3 don't use #defines though, which in my opinion is better.

If you are undecided, go with #1!

This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console

In the API manager menu, you should be able to click overview, select the relevant API under the Google Maps APIs heading and map icon.

Your page might be using some other API's , like Places. Enable them all and see if it helps.

Google Places API Web Service Google Maps Geocoding API

How to fill in form field, and submit, using javascript?

It would be something like:

document.getElementById("username").value="Username";
document.forms[0].submit()

Or similar edit: you guys are too fast ;)

Using %f with strftime() in Python to get microseconds

You are looking at the wrong documentation. The time module has different documentation.

You can use the datetime module strftime like this:

>>> from datetime import datetime
>>>
>>> now = datetime.now()
>>> now.strftime("%H:%M:%S.%f")
'12:19:40.948000'

How to ignore files/directories in TFS for avoiding them to go to central source repository?

For VS2015 and VS2017

Works with TFS (on-prem) or VSO (Visual Studio Online - the Azure-hosted offering)

The NuGet documentation provides instructions on how to accomplish this and I just followed them successfully for Visual Studio 2015 & Visual Studio 2017 against VSTS (Azure-hosted TFS). Everything is fully updated as of Nov 2016 Aug 2018.

I recommend you follow NuGet's instructions but just to recap what I did:

  1. Make sure your packages folder is not committed to TFS. If it is, get it out of there.
  2. Everything else we create below goes into the same folder that your .sln file exists in unless otherwise specified (NuGet's instructions aren't completely clear on this).
  3. Create a .nuget folder. You can use Windows Explorer to name it .nuget. for it to successfully save as .nuget (it automatically removes the last period) but directly trying to name it .nuget may not work (you may get an error or it may change the name, depending on your version of Windows). Or name the directory nuget, and open the parent directory in command line prompt. type. ren nuget .nuget
  4. Inside of that folder, create a NuGet.config file and add the following contents and save it:

NuGet.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <solution>
        <add key="disableSourceControlIntegration" value="true" />
    </solution>
</configuration>
  1. Go back in your .sln's folder and create a new text file and name it .tfignore (if using Windows Explorer, use the same trick as above and name it .tfignore.)
  2. Put the following content into that file:

.tfignore:

# Ignore the NuGet packages folder in the root of the repository.
# If needed, prefix 'packages' with additional folder names if it's 
# not in the same folder as .tfignore.
packages

# include package target files which may be required for msbuild,
# again prefixing the folder name as needed.
!packages/*.targets
  1. Save all of this, commit it to TFS, then close & re-open Visual Studio and the Team Explorer should no longer identify the packages folder as a pending check-in.
  2. Copy/pasted via Windows Explorer the .tfignore file and .nuget folder to all of my various solutions and committed them and I no longer have the packages folder trying to sneak into my source control repo!

Further Customization

While not mine, I have found this .tfignore template by sirkirby to be handy. The example in my answer covers the Nuget packages folder but this template includes some other things as well as provides additional examples that can be useful if you wish to customize this further.

Android basics: running code in the UI thread

There is a fourth way using Handler

new Handler().post(new Runnable() {
    @Override
    public void run() {
        // Code here will run in UI thread
    }
});

Obtain form input fields using jQuery?

When I needed to do an ajax call with all the form fields, I had problems with the :input selector returning all checkboxes whether or not they were checked. I added a new selector to just get the submit-able form elements:

$.extend($.expr[':'],{
    submitable: function(a){
        if($(a).is(':checkbox:not(:checked)'))
        {
            return false;
        }
        else if($(a).is(':input'))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
});

usage:

$('#form_id :submitable');

I've not tested it with multiple select boxes yet though but It works for getting all the form fields in the way a standard submit would.

I used this when customising the product options on an OpenCart site to include checkboxes and text fields as well as the standard select box type.

Hide div element when screen size is smaller than a specific size

@media only screen and (max-width: 1026px) { 
  #fadeshow1 { 
    display: none; 
  } 
}

Any time the screen is less than 1026 pixels wide, anything inside the { } will apply.

Some browsers don't support media queries. You can get round this using a javascript library like Respond.JS

Open Popup window using javascript

First point is- showing multiple popups is not desirable in terms of usability.

But you can achieve it by using multiple popup names

var newwindow;
function createPop(url, name)
{    
   newwindow=window.open(url,name,'width=560,height=340,toolbar=0,menubar=0,location=0');  
   if (window.focus) {newwindow.focus()}
}

Better approach will be showing both in a single page in two different iFrames or Divs.

Update:

So I will suggest to create a new tab in the test.aspx page to show the report, instead of replacing the image content and placing the pdf.

How to implement a confirmation (yes/no) DialogPreference?

Android comes with a built-in YesNoPreference class that does exactly what you want (a confirm dialog with yes and no options). See the official source code here.

Unfortunately, it is in the com.android.internal.preference package, which means it is a part of Android's private APIs and you cannot access it from your application (private API classes are subject to change without notice, hence the reason why Google does not let you access them).

Solution: just re-create the class in your application's package by copy/pasting the official source code from the link I provided. I've tried this, and it works fine (there's no reason why it shouldn't).

You can then add it to your preferences.xml like any other Preference. Example:

<com.example.myapp.YesNoPreference
    android:dialogMessage="Are you sure you want to revert all settings to their default values?"
    android:key="com.example.myapp.pref_reset_settings_key"
    android:summary="Revert all settings to their default values."
    android:title="Reset Settings" />

Which looks like this:

screenshot

HTML button opening link in new tab

With Bootstrap you can use an anchor like a button.

<a class="btn btn-success" href="https://www.google.com" target="_blank">Google</a>

And use target="_blank" to open the link in a new tab.

What is unit testing and how do you do it?

What is unit testing?

Unit testing simply verifies that individual units of code (mostly functions) work as expected. Usually you write the test cases yourself, but some can be automatically generated.

The output from a test can be as simple as a console output, to a "green light" in a GUI such as NUnit, or a different language-specific framework.

Performing unit tests is designed to be simple, generally the tests are written in the form of functions that will determine whether a returned value equals the value you were expecting when you wrote the function (or the value you will expect when you eventually write it - this is called Test Driven Development when you write the tests first).

How do you perform unit tests?

Imagine a very simple function that you would like to test:

int CombineNumbers(int a, int b) {
    return a+b;
}

The unit test code would look something like this:

void TestCombineNumbers() {
    Assert.IsEqual(CombineNumbers(5, 10), 15); // Assert is an object that is part of your test framework
    Assert.IsEqual(CombineNumbers(1000, -100), 900);
}

When you run the tests, you will be informed that these tests have passed. Now that you've built and run the tests, you know that this particular function, or unit, will perform as you expect.

Now imagine another developer comes along and changes the CombineNumbers() function for performance, or some other reason:

int CombineNumbers(int a, int b) {
    return a * b;
}

When the developer runs the tests that you have created for this very simple function, they will see that the first Assert fails, and they now know that the build is broken.

When should you perform unit tests?

They should be done as often as possible. When you are performing tests as part of the development process, your code is automatically going to be designed better than if you just wrote the functions and then moved on. Also, concepts such as Dependency Injection are going to evolve naturally into your code.

The most obvious benefit is knowing down the road that when a change is made, no other individual units of code were affected by it if they all pass the tests.

How to define hash tables in Bash?

I also used the bash4 way but I find and annoying bug.

I needed to update dynamically the associative array content so i used this way:

for instanceId in $instanceList
do
   aws cloudwatch describe-alarms --output json --alarm-name-prefix $instanceId| jq '.["MetricAlarms"][].StateValue'| xargs | grep -E 'ALARM|INSUFFICIENT_DATA'
   [ $? -eq 0 ] && statusCheck+=([$instanceId]="checkKO") || statusCheck+=([$instanceId]="allCheckOk"
done

I find out that with bash 4.3.11 appending to an existing key in the dict resulted in appending the value if already present. So for example after some repetion the content of the value was "checkKOcheckKOallCheckOK" and this was not good.

No problem with bash 4.3.39 where appenging an existent key means to substisture the actuale value if already present.

I solved this just cleaning/declaring the statusCheck associative array before the cicle:

unset statusCheck; declare -A statusCheck

Which Java library provides base64 encoding/decoding?

Within Apache Commons, commons-codec-1.7.jar contains a Base64 class which can be used to encode.

Via Maven:

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>20041127.091804</version>
</dependency>

Direct Download

Math functions in AngularJS bindings

The easiest way to do simple math with Angular is directly in the HTML markup for individual bindings as needed, assuming you don't need to do mass calculations on your page. Here's an example:

{{(data.input/data.input2)| number}} 

In this case you just do the math in the () and then use a filter | to get a number answer. Here's more info on formatting Angular numbers as text:

https://docs.angularjs.org/api/ng/filter

How to add Drop-Down list (<select>) programmatically?

var sel = document.createElement('select');
sel.name = 'drop1';
sel.id = 'Select1';

var cars = [
  "volvo",
  "saab",
  "mercedes",
  "audi"
];

var options_str = "";

cars.forEach( function(car) {
  options_str += '<option value="' + car + '">' + car + '</option>';
});

sel.innerHTML = options_str;


window.onload = function() {
  document.body.appendChild(sel);
};

How to get the focused element with jQuery?

// Get the focused element:
var $focused = $(':focus');

// No jQuery:
var focused = document.activeElement;

// Does the element have focus:
var hasFocus = $('foo').is(':focus');

// No jQuery:
elem === elem.ownerDocument.activeElement;

Which one should you use? quoting the jQuery docs:

As with other pseudo-class selectors (those that begin with a ":"), it is recommended to precede :focus with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare $(':focus') is equivalent to $('*:focus'). If you are looking for the currently focused element, $( document.activeElement ) will retrieve it without having to search the whole DOM tree.

The answer is:

document.activeElement

And if you want a jQuery object wrapping the element:

$(document.activeElement)

Mockito - difference between doReturn() and when()

The two syntaxes for stubbing are roughly equivalent. However, you can always use doReturn/when for stubbing; but there are cases where you can't use when/thenReturn. Stubbing void methods is one such. Others include use with Mockito spies, and stubbing the same method more than once.

One thing that when/thenReturn gives you, that doReturn/when doesn't, is type-checking of the value that you're returning, at compile time. However, I believe this is of almost no value - if you've got the type wrong, you'll find out as soon as you run your test.

I strongly recommend only using doReturn/when. There is no point in learning two syntaxes when one will do.

You may wish to refer to my answer at Forming Mockito "grammars" - a more detailed answer to a very closely related question.

How to read a CSV file into a .NET Datatable

this is the code i use it but your apps must run with net version 3.5

private void txtRead_Click(object sender, EventArgs e)
        {
           // var filename = @"d:\shiptest.txt";

            openFileDialog1.InitialDirectory = "d:\\";
            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                if (openFileDialog1.FileName != "")
                {
                    var reader = ReadAsLines(openFileDialog1.FileName);

                    var data = new DataTable();

                    //this assume the first record is filled with the column names
                    var headers = reader.First().Split(',');
                    foreach (var header in headers)
                    {
                        data.Columns.Add(header);
                    }

                    var records = reader.Skip(1);
                    foreach (var record in records)
                    {
                        data.Rows.Add(record.Split(','));
                    }

                    dgList.DataSource = data;
                }
            }
        }

        static IEnumerable<string> ReadAsLines(string filename)
        {
            using (StreamReader reader = new StreamReader(filename))
                while (!reader.EndOfStream)
                    yield return reader.ReadLine();
        }

Fatal error: Class 'Illuminate\Foundation\Application' not found

In my case composer was not installed in that directory. So I run

composer install

then error resolved.

or you can try

composer update --no-scripts
cd bootstrap/cache/->rm -rf *.php
composer dump-autoload

How to get today's Date?

Is there are more correct way?

Yes, there is.

LocalDate.now( 
    ZoneId.of( "America/Montreal" ) 
).atStartOfDay(
    ZoneId.of( "America/Montreal" )
)

java.time

Java 8 and later now has the new java.time framework built-in. See Tutorial. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.

Examples

Some examples follow, using java.time. Note how they specify a time zone. If omitted, your JVM’s current default time zone. That default can vary, even changing at any moment during runtime, so I suggest you specify a time zone explicitly rather than rely implicitly on the default.

Here is an example of date-only, without time-of-day nor time zone.

ZoneId zonedId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zonedId );
System.out.println( "today : " + today );

today : 2015-10-19

Here is an example of getting current date-time.

ZoneId zonedId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( zonedId );
System.out.println( "zdt : " + zdt );

When run:

zdt : 2015-10-19T18:07:02.910-04:00[America/Montreal]

First Moment Of The Day

The Question asks for the date-time where the time is set to zero. This assumes the first moment of the day is always the time 00:00:00.0 but that is not always the case. Daylight Saving Time (DST) and perhaps other anomalies mean the day may begin at a different time such as 01:00.0.

Fortunately, java.time has a facility to determine the first moment of a day appropriate to a particular time zone, LocalDate::atStartOfDay. Let's see some code using the LocalDate named today and the ZoneId named zoneId from code above.

ZonedDateTime todayStart = today.atStartOfDay( zoneId );

zdt : 2015-10-19T00:00:00-04:00[America/Montreal]

Interoperability

If you must have a java.util.Date for use with classes not yet updated to work with the java.time types, convert. Call the java.util.Date.from( Instant instant ) method.

java.util.Date date = java.util.Date.from( zdt.toInstant() );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How can I create a copy of an object in Python?

To get a fully independent copy of an object you can use the copy.deepcopy() function.

For more details about shallow and deep copying please refer to the other answers to this question and the nice explanation in this answer to a related question.

Using $window or $location to Redirect in AngularJS

You have to put:

<html ng-app="urlApp" ng-controller="urlCtrl">

This way the angular function can access into "window" object

How to create multidimensional array

I've written a one linear for this:

[1, 3, 1, 4, 1].reduceRight((x, y) => new Array(y).fill().map(() => JSON.parse(JSON.stringify(x))), 0);

I feel however I can spend more time to make a JSON.parse(JSON.stringify())-free version which is used for cloning here.

Btw, have a look at my another answer here.

Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

As I mentioned in your other question:

The problem to do with that fact, that you invented your own non-standard attributes (which you shouldn't have done in the first place), and now new standardized attributes (or attributes in the process of being standardized) are colliding with them.

The proper solution is to completely remove your invented attributes and replace them with something sensible, for example classes (class="Montantetextfield fieldname-Montante required allow-decimal-values"), or store them in JavaScript:

var validationData = {
  "Montante": {fieldname: "Montante", required: true, allowDecimalValues: true}
}

If the proper solution isn't viable, you'll have to rename them. In that case you should use the prefix data-... because that is reserved by HTML5 for such purposes, and it's less likely to collide with something - but it still could, so you should seriously consider the first solution - even it is more work to change.

How to check how many letters are in a string in java?

1) To answer your question:

  String s="Java";
  System.out.println(s.length()); 

How to map an array of objects in React

you must put object in your JSX, It`s easy way to do this just see my simple code here:

const link = [
  {
   name: "Cold Drink",
   link: "/coldDrink"
  },
  {
   name: "Hot Drink",
   link: "/HotDrink"
  },

{ name: "chease Cake", link: "/CheaseCake" } ]; and you must map this array in your code with simple object see this code :

const links = (this.props.link);
{links.map((item, i) => (
 <li key={i}>
   <Link to={item.link}>{item.name}</Link>
 </li>
 ))}

I hope this answer will be helpful for you ...:)

What is the C++ function to raise a number to a power?

int power (int i, int ow) // works only for ow >= 1
{ // but does not require <cmath> library!=)
    if (ow > 1)
    {
         i = i * power (i, ow - 1);
    }
    return i;
}

cout << power(6,7); //you can enter variables here

How do I debug jquery AJAX calls?

here is what I would do in order to debug and get the php errors into javascript console.log after an ajax call:

    $('#ChangePermission').click(function () {
    $.ajax({
        url: 'change_permission.php',
        type: 'POST',
        data: {
            'user': document.GetElementById("user").value,
            'perm': document.GetElementById("perm").value
        },
        success: function (data) {
            console.log(data);  
        },
        error: function (data) {
            console.log(data);
        }
    });
});

on the php side I would start by asking for all error returned to string concat and echo as a json encoded response that will includes php error messages as well if any.

<?php

error_reporting(E_ALL);
require_once(functions . php);
$result = "true";
$DBH = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);  
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH = $DBH->prepare("INSERT INTO people ( username, permissions ) values (?, ?)");

if (isset($_POST["user"]) && isset($_POST["perm"])) {
    $STH->bindParam(1, $_POST["user"], PDO::PARAM_STR);
    $STH->bindParam(2, $_POST["perm"], PDO::PARAM_STR);
}
try {
    $STH->execute();
} catch (PDOException $e) {
    $result .= $e->getMessage;
}
echo json_encode($result);
?>

How to get primary key of table?

For a PHP approach, you can use mysql_field_flags

$q = mysql_query('select * from table limit 1');

for($i = 0; $i < mysql_num_fields(); $i++)
    if(strpos(mysql_field_tags($q, $i), 'primary_key') !== false)
        echo mysql_field_name($q, $i)." is a primary key\n";

Getting "Skipping JaCoCo execution due to missing execution data file" upon executing JaCoCo

There might a case where some other argline setup or plugin in pom may be overriding jacoco execution order setup.

argLine set to -javaagent:/Users/davea/.m2/repository/org/jacoco/org.jacoco.agent/0.6.2.201302030002/org.jacoco.agent-0.6.2.201302030002-runtime.jar=destfile=/Users/davea/Dropbox/workspace/myproject/target/jacoco.exec

One of the example

           <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.16</version>
                <configuration>
                    <forkCount>5</forkCount>
                    <reuseForks>true</reuseForks>
                    <argLine>-Dnet.sf.ehcache.disabled=true</argLine>
                </configuration>
            </plugin>

After getting rid of argLine from these plugins, jacoco started to work normally.

How to attach a file using mail command on Linux?

There are a lot of answers here using mutt or mailx or people saying mail doesn't support "-a"

First, Ubuntu 14.0.4 mail from mailutils supports this:

mail -A filename -s "subject" [email protected]

Second, I found that by using the "man mail" command and searching for "attach"

Padding characters in printf

Trivial (but working) solution:

echo -e "---------------------------- [UP]\r$PROC_NAME "

Failed to resolve: com.android.support:appcompat-v7:26.0.0

1 - in build.gradle change my supportLibVersion to 26.0.0

2 - in app/build.gradle use :

implementation "com.android.support:appcompat v7:${rootProject.ext.supportLibVersion}"

3 - cd android

4 - ./gradlew clean

5 - ./gradlew assembleRelease

batch script - read line by line

Try this:

@echo off
for /f "tokens=*" %%a in (input.txt) do (
  echo line=%%a
)
pause

because of the tokens=* everything is captured into %a

edit: to reply to your comment, you would have to do that this way:

@echo off
for /f "tokens=*" %%a in (input.txt) do call :processline %%a

pause
goto :eof

:processline
echo line=%*

goto :eof

:eof

Because of the spaces, you can't use %1, because that would only contain the part until the first space. And because the line contains quotes, you can also not use :processline "%%a" in combination with %~1. So you need to use %* which gets %1 %2 %3 ..., so the whole line.

How do I copy a string to the clipboard?

You can use pyperclip - cross-platform clipboard module. Or Xerox - similar module, except requires the win32 Python module to work on Windows.

CSS: How can I set image size relative to parent height?

If you take answer's Shekhar K. Sharma, and it almost work, you need also add to your this height: 1px; or this width: 1px; for must work.

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

By failing to provide a decent solution, you just end up with something worse IMHO.

The common work around is as follows.

T[] ts = new T[n];

is replaced with (assuming T extends Object and not another class)

T[] ts = (T[]) new Object[n];

I prefer the first example, however more academic types seem to prefer the second, or just prefer not to think about it.

Most of the examples of why you can't just use an Object[] equally apply to List or Collection (which are supported), so I see them as very poor arguments.

Note: this is one of the reasons the Collections library itself doesn't compile without warnings. If you this use-case cannot be supported without warnings, something is fundamentally broken with the generics model IMHO.

How to retry after exception?

I use following in my codes,

   for i in range(0, 10):
    try:
        #things I need to do
    except ValueError:
        print("Try #{} failed with ValueError: Sleeping for 2 secs before next try:".format(i))
        time.sleep(2)
        continue
    break

Execute command without keeping it in history

echo "discreet";history -d $(history 1)

Getting HTML elements by their attribute names

Just another answer

Array.prototype.filter.call(
    document.getElementsByTagName('span'),
    function(el) {return el.getAttribute('property') == 'v.name';}
);

In future

Array.prototype.filter.call(
    document.getElementsByTagName('span'),
    (el) => el.getAttribute('property') == 'v.name'
)

3rd party edit

Intro

  • The call() method calls a function with a given this value and arguments provided individually.

  • The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Given this html markup

<span property="a">apple - no match</span>
<span property="v:name">onion - match</span>
<span property="b">root - match</span>
<span property="v:name">tomato - match</span>
<br />
<button onclick="findSpan()">find span</button>

you can use this javascript

function findSpan(){

    var spans = document.getElementsByTagName('span');
    var spansV = Array.prototype.filter.call(
         spans,
         function(el) {return el.getAttribute('property') == 'v:name';}
    );
    return spansV;
}

See demo

Difference between signature versions - V1 (Jar Signature) and V2 (Full APK Signature) while generating a signed APK in Android Studio?

According to this link: signature help

APK Signature Scheme v2 offers:

  1. Faster app install times
  2. More protection against unauthorized alterations to APK files.

Android 7.0 introduces APK Signature Scheme v2, a new app-signing scheme that offers faster app install times and more protection against unauthorized alterations to APK files. By default, Android Studio 2.2 and the Android Plugin for Gradle 2.2 sign your app using both APK Signature Scheme v2 and the traditional signing scheme, which uses JAR signing.

It is recommended to use APK Signature Scheme v2 but is not mandatory.

Although we recommend applying APK Signature Scheme v2 to your app, this new scheme is not mandatory. If your app doesn't build properly when using APK Signature Scheme v2, you can disable the new scheme.

How to find the privileges and roles granted to a user in Oracle?

Combining the earlier suggestions to determine your personal permissions (ie 'USER' permissions), then use this:

-- your permissions
select * from USER_ROLE_PRIVS where USERNAME= USER;
select * from USER_TAB_PRIVS where Grantee = USER;
select * from USER_SYS_PRIVS where USERNAME = USER;

-- granted role permissions
select * from ROLE_ROLE_PRIVS where ROLE IN (select granted_role from USER_ROLE_PRIVS where USERNAME= USER);
select * from ROLE_TAB_PRIVS  where ROLE IN (select granted_role from USER_ROLE_PRIVS where USERNAME= USER);
select * from ROLE_SYS_PRIVS  where ROLE IN (select granted_role from USER_ROLE_PRIVS where USERNAME= USER);

How To fix white screen on app Start up?

The user543 answer is perfect

<activity
        android:name="first Activity Name"
        android:theme="@android:style/Theme.Translucent.NoTitleBar" >
 <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
 </activity>

But:

You'r LAUNCHER Activity must extands Activity, not AppCompatActivity as it came by default!

What's the difference between an id and a class?

In the CSS, a class selector is a name preceded by a full stop (“.”) and an ID selector is a name preceded by a hash character (“#”). The difference between an ID and a class is that an ID can be used to identify one element, whereas a class can be used to identify more than one.

What is the equivalent of ngShow and ngHide in Angular 2+?

<div [hidden]="flagValue">
---content---
</div>

How to draw in JPanel? (Swing/graphics Java)

Here is a simple example. I suppose it will be easy to understand:

import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Graph extends JFrame {
JFrame f = new JFrame();
JPanel jp;


public Graph() {
    f.setTitle("Simple Drawing");
    f.setSize(300, 300);
    f.setDefaultCloseOperation(EXIT_ON_CLOSE);

    jp = new GPanel();
    f.add(jp);
    f.setVisible(true);
}

public static void main(String[] args) {
    Graph g1 = new Graph();
    g1.setVisible(true);
}

class GPanel extends JPanel {
    public GPanel() {
        f.setPreferredSize(new Dimension(300, 300));
    }

    @Override
    public void paintComponent(Graphics g) {
        //rectangle originates at 10,10 and ends at 240,240
        g.drawRect(10, 10, 240, 240);
        //filled Rectangle with rounded corners.    
        g.fillRoundRect(50, 50, 100, 100, 80, 80);
    }
}

}

And the output looks like this:

Output

Difference between web server, web container and application server

Web Server: It provides HTTP Request and HTTP response. It handles request from client only through HTTP protocol. It contains Web Container. Web Application mostly deployed on web Server. EX: Servlet JSP

Web Container: it maintains the life cycle for Servlet Object. Calls the service method for that servlet object. pass the HttpServletRequest and HttpServletResponse Object

Application Server: It holds big Enterprise application having big business logic. It is Heavy Weight or it holds Heavy weight Applications. Ex: EJB

Is it possible to use jQuery to read meta tags

jQuery now supports .data();, so if you have

<div id='author' data-content='stuff!'>

use

var author = $('#author').data("content"); // author = 'stuff!'

force client disconnect from server with socket.io and nodejs

For those who found this on google - there is a solution for this right now:

Socket.disconnect() kicks the client (server-side). No chance for the client to stay connected :)

Programmatically change the height and width of a UIImageView Xcode Swift

let screenSize: CGRect = UIScreen.mainScreen().bounds
image.frame = CGRectMake(0,0, screenSize.height * 0.2, 50)

How can I catch an error caused by mail()?

You could use the PEAR Mail classes and methods, which allows you to check for errors via:

if (PEAR::isError($mail)) {
    echo("<p>" . $mail->getMessage() . "</p>");
} else {
    echo("<p>Message successfully sent!</p>");
}

You can find an example here.

Right query to get the current number of connections in a PostgreSQL DB

The following query is very helpful

select  * from
(select count(*) used from pg_stat_activity) q1,
(select setting::int res_for_super from pg_settings where name=$$superuser_reserved_connections$$) q2,
(select setting::int max_conn from pg_settings where name=$$max_connections$$) q3;

CSV API for Java

I've used OpenCSV in the past.

import au.com.bytecode.opencsv.CSVReader;

String fileName = "data.csv";
CSVReader reader = new CSVReader(new FileReader(fileName ));

// if the first line is the header String[] header = reader.readNext();
// iterate over reader.readNext until it returns null String[] line = reader.readNext();

There were some other choices in the answers to another question.

Share link on Google+

Yep! Use the link:

https://m.google.com/app/plus/x/?v=compose&content=YOUR_TEXT

It's SHARE url (not used for plus one) button.

If this will not work (not for me) try this url:

https://plusone.google.com/_/+1/confirm?hl=ru&url=_URL_&title=_TITLE_

Or see this solution:

Adding a Google Plus (one or share) link to an email newsletter