Programs & Examples On #Libpng

libpng is the offical PNG reference library, supporting most all of PNG's features, is extensible, and has been widely used and tested for over twenty years.

dyld: Library not loaded: /usr/local/lib/libpng16.16.dylib with anything php related

I solved this by copying it over to the missing directory:

cp /opt/X11/lib/libpng15.15.dylib /usr/local/lib/libpng15.15.dylib

brew reinstall libpng kept installing libpng16, not libpng15 so I was forced to do the above.

libpng warning: iCCP: known incorrect sRGB profile

Solution

The incorrect profile could be fixed by:

  1. Opening the image with the incorrect profile using QPixmap::load
  2. Saving the image back to the disk (already with the correct profile) using QPixmap::save

Note: This solution uses the Qt Library.

Example

Here is a minimal example I have written in C++ in order to demonstrate how to implement the proposed solution:

QPixmap pixmap;
pixmap.load("badProfileImage.png");

QFile file("goodProfileImage.png");
file.open(QIODevice::WriteOnly);
pixmap.save(&file, "PNG");

The complete source code of a GUI application based on this example is available on GitHub.

UPDATE FROM 05.12.2019: The answer was and is still valid, however there was a bug in the GUI application I have shared on GitHub, causing the output image to be empty. I have just fixed it and apologise for the inconvenience!

jQuery - setting the selected value of a select control via its text description

If you are trying to bind select with ID then the following code worked for me.

<select name="0product_id[]" class="groupSelect" id="groupsel_0" onchange="productbuilder.update(this.value,0);">
    <option value="0" class="notag" id="id0_0">--Select--</option>
    <option class="notag" value="338" id="id0_338"  >Dual Promoter Puromycin Expression Plasmid - pSF-CMV-PGK-Puro  > £114.00</option>
    <option class="notag" value="282" id="id0_282"  >EMCV IRES Puromycin Expression Plasmid - pSF-CMV-EMCV-Puro  > £114.00</option>
    <option class="notag" value="265" id="id0_265"  >FMDV IRES Puromycin Expression Plasmid - pSF-CMV-FMDV-Puro  > £114.00</option>
    <option class="notag" value="101" id="id0_101"  >Puromycin Selection Plasmid - pSF-CMV-Ub-Puro AscI  > £114.00</option>
    <option class="notag" value="105" id="id0_105"  >Puromycin Selection SV40 Ori Plasmid - pSF-CMV-Ub-Puro-SV40 Ori SbfI  > £114.00</option></select>

AND THIS IS TEH JS CODE

$( document ).ready(function() {
      var text = "EMCV IRES Puromycin Expression Plasmid - pSF-CMV-EMCV-Puro  > £114.00";
      alert(text);
$("#groupsel_0 option").filter(function() {
  //may want to use $.trim in here
  return $(this).text() == text;
}).prop('selected', true);
});

Remove the last chars of the Java String variable

I think you want to remove the last five characters ('.', 'n', 'u', 'l', 'l'):

path = path.substring(0, path.length() - 5);

Note how you need to use the return value - strings are immutable, so substring (and other methods) don't change the existing string - they return a reference to a new string with the appropriate data.

Or to be a bit safer:

if (path.endsWith(".null")) {
  path = path.substring(0, path.length() - 5);
}

However, I would try to tackle the problem higher up. My guess is that you've only got the ".null" because some other code is doing something like this:

path = name + "." + extension;

where extension is null. I would conditionalise that instead, so you never get the bad data in the first place.

(As noted in a question comment, you really should look through the String API. It's one of the most commonly-used classes in Java, so there's no excuse for not being familiar with it.)

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

If you are counting letters, the above solution will fail for some unicode symbols. For example for these 5 characters sample.length() will return 6 instead of 5:

String sample = "\u760c\u0444\u03b3\u03b5\ud800\udf45"; // ???e

The codePointCount function was introduced in Java 1.5 and I understand gives better results for glyphs etc

sample.codePointCount(0, sample.length()) // returns 5

http://globalizer.wordpress.com/2007/01/16/utf-8-and-string-length-limitations/

Arduino COM port doesn't work

Abstract: Steps of How to resolve "Serial port 'COM1' not found" in fedora 17.

Today install the packages for Arduino in Fedora 17. (yum install arduino) and I have the same problem: I decided to upload an example to the chip. and got the same error "Serial port 'COM1' not found".

In this case when I run Arduino program, some banner appears which warns me that my user is not in 'dialout' and 'lock' group. Do you want add your user in this groups? I click in add button, but for some reason the program fail and not say nothing.

Step1: recognize the Arduino device unplug your Arduino and list /dev files:

#ls -l /dev

plug your Arduino and go and list /dev files

#ls -l /dev

Find the new file (device) that was not before plugging, for example:

ttyACM0 or ttyUSB1

Read this properties:

ls -l /dev/ttyACM0

crw-rw---- 1 root dialout 166, 0 Dec 24 19:25 /dev/ttyACM0

the first c mean that Arduino is a character device.

user owner: root

group owner: dialout

mayor number: 166

minor number: 0

Step2: set your user as group owner.

If you do:

groups <yourUser>

And you are not in 'dialout' and/or 'lock' group. Add yourself in this groups run as root:

usermod -aG lock <yourUser>
usermod -aG dialout <yourUser>

restart the pc, and set /dev/<yourDeviceFile> as your serial port before upload.

Remove all classes that begin with a certain string

Using 2nd signature of $.fn.removeClass :

// Considering:
var $el = $('<div class="  foo-1 a b foo-2 c foo"/>');

function makeRemoveClassHandler(regex) {
  return function (index, classes) {
    return classes.split(/\s+/).filter(function (el) {return regex.test(el);}).join(' ');
  }
}

$el.removeClass(makeRemoveClassHandler(/^foo-/));
//> [<div class=?"a b c foo">?</div>?]

How to get domain root url in Laravel 4?

use directly where you want controller or web.php

Request::getHost();

Creating watermark using html and css

#watermark
{
 position:fixed;
 bottom:5px;
 right:5px;
 opacity:0.5;
 z-index:99;
 color:white;
}

jSFiddle

How do I get the difference between two Dates in JavaScript?

<html>
<head>
<script>
function dayDiff()
{
     var start = document.getElementById("datepicker").value;
     var end= document.getElementById("date_picker").value;
     var oneDay = 24*60*60*1000; 
     var firstDate = new Date(start);
     var secondDate = new Date(end);    
     var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
    document.getElementById("leave").value =diffDays ;
 }
</script>
</head>
<body>
<input type="text" name="datepicker"value=""/>
<input type="text" name="date_picker" onclick="function dayDiff()" value=""/>
<input type="text" name="leave" value=""/>
</body>
</html>

What is the most efficient way to check if a value exists in a NumPy array?

The most convenient way according to me is:

(Val in X[:, col_num])

where Val is the value that you want to check for and X is the array. In your example, suppose you want to check if the value 8 exists in your the third column. Simply write

(8 in X[:, 2])

This will return True if 8 is there in the third column, else False.

React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

The solution that worked for me is that:- I moved my data.json file from src to public directory. Then used fetch API to fetch the file.

fetch('./data.json').then(response => {
          console.log(response);
          return response.json();
        }).then(data => {
          // Work with JSON data here
          console.log(data);
        }).catch(err => {
          // Do something for an error here
          console.log("Error Reading data " + err);
        });

The problem was that after compiling react app the fetch request looks for the file at URL "http://localhost:3000/data.json" which is actually the public directory of my react app. But unfortunately while compiling react app data.json file is not moved from src to public directory. So we have to explicitly move data.json file from src to public directory.

jQuery select option elements by value

options = $("#span_id>select>option[value='"+i+"']");
option = options.text();
alert(option); 

here is the fiddle http://jsfiddle.net/hRFYF/

Eclipse add Tomcat 7 blank server name

The easiest solution is to create a new workspace in eclipse/STS.

File -> Switch Workspace -> Others...

How to identify unused CSS definitions from multiple CSS files in a project

Chrome Developer Tools has an Audits tab which can show unused CSS selectors.

Run an audit, then, under Web Page Performance see Remove unused CSS rules

enter image description here

XML Error: There are multiple root elements

Wrap the xml in another element

<wrapper>
<parent>
    <child>
        Text
    </child>
</parent>
<parent>
    <child>
        <grandchild>
            Text
        </grandchild>
        <grandchild>
            Text
        </grandchild>
    </child>
    <child>
        Text
    </child>
</parent>
</wrapper>

m2e lifecycle-mapping not found

m2e 1.7 introduces a new syntax for lifecycle mapping metadata that doesn't cause this warning anymore:

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
    <execution>

        <!-- This executes the goal in Eclipse on project import.
             Other options like are available, eg ignore.  -->
        <?m2e execute?>

        <phase>generate-sources</phase>
        <goals><goal>add-source</goal></goals>
        <configuration>
            <sources>
                <source>src/bootstrap/java</source>
            </sources>
        </configuration>
    </execution>
</executions>
</plugin>

NuGet: 'X' already has a dependency defined for 'Y'

I faced this error on outdated version of Visual Studio 2010. Due to project configuration I was not able to update this version to newer. Therefore, update of NuGet advised above did not fix things for me.

Root reason for the error in this and similar situations is in dependencies of the package you try to install, which are not compatible with .NET version available in your project.

Universal solution is not obligatory update of Visual Studio or .NET but in installation of older NuGet versions of the same package compatible with your system.

It is not possible to tell for sure, which of earlier versions will work. In my case, this command installed the package without any NuGet updates.

Install-Package X -Version [compatible version number]

What can be the reasons of connection refused errors?

If you try to open a TCP connection to another host and see the error "Connection refused," it means that

  1. You sent a TCP SYN packet to the other host.
  2. Then you received a TCP RST packet in reply.

RST is a bit on the TCP packet which indicates that the connection should be reset. Usually it means that the other host has received your connection attempt and is actively refusing your TCP connection, but sometimes an intervening firewall may block your TCP SYN packet and send a TCP RST back to you.

See https://tools.ietf.org/html/rfc793 page 69:

SYN-RECEIVED STATE

If the RST bit is set

If this connection was initiated with a passive OPEN (i.e., came from the LISTEN state), then return this connection to LISTEN state and return. The user need not be informed. If this connection was initiated with an active OPEN (i.e., came from SYN-SENT state) then the connection was refused, signal the user "connection refused". In either case, all segments on the retransmission queue should be removed. And in the active OPEN case, enter the CLOSED state and delete the TCB, and return.

Priority queue in .Net

I found one by Julian Bucknall on his blog here - http://www.boyet.com/Articles/PriorityQueueCSharp3.html

We modified it slightly so that low-priority items on the queue would eventually 'bubble-up' to the top over time, so they wouldn't suffer starvation.

Select All checkboxes using jQuery

Try this

$(document).ready(function () {
    $("#ckbCheckAll").click(function () {
        $("#checkBoxes input").prop('checked', $(this).prop('checked'));
    });
});

That should do it :)

Checking cin input stream produces an integer

Heh, this is an old question that could use a better answer.

User input should be obtained as a string and then attempt-converted to the data type you desire. Conveniently, this also allows you to answer questions like “what type of data is my input?”

Here is a function I use a lot. Other options exist, such as in Boost, but the basic premise is the same: attempt to perform the string?type conversion and observe the success or failure:

template <typename T>
std::optional <T> string_to( const std::string& s )
{
  std::istringstream ss( s );
  T result;
  ss >> result >> std::ws;      // attempt the conversion
  if (ss.eof()) return result;  // success
  return {};                    // failure
}

Using the optional type is just one way. You could also throw an exception or return a default value on failure. Whatever works for your situation.

Here is an example of using it:

int n;
std::cout << "n? ";
{
  std::string s;
  getline( std::cin, s );
  auto x = string_to <int> ( s );
  if (!x) return complain();
  n = *x;
}
std::cout << "Multiply that by seven to get " << (7 * n) << ".\n";

limitations and type identification

In order for this to work, of course, there must exist a method to unambiguously extract your data type from a stream. This is the natural order of things in C++ — that is, business as usual. So no surprises here.

The next caveat is that some types subsume others. For example, if you are trying to distinguish between int and double, check for int first, since anything that converts to an int is also a double.

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.

Concatenating two std::vectors

Add this one to your header file:

template <typename T> vector<T> concat(vector<T> &a, vector<T> &b) {
    vector<T> ret = vector<T>();
    copy(a.begin(), a.end(), back_inserter(ret));
    copy(b.begin(), b.end(), back_inserter(ret));
    return ret;
}

and use it this way:

vector<int> a = vector<int>();
vector<int> b = vector<int>();

a.push_back(1);
a.push_back(2);
b.push_back(62);

vector<int> r = concat(a, b);

r will contain [1,2,62]

C++: Rounding up to the nearest multiple of a number

well for one thing, since i dont really understand what you want to do, the lines

int roundUp = roundDown + multiple;
int roundCalc = roundUp;
return (roundCalc); 

could definitely be shortened to

int roundUp = roundDown + multiple;
return roundUp;

Linq: GroupBy, Sum and Count

I don't understand where the first "result with sample data" is coming from, but the problem in the console app is that you're using SelectMany to look at each item in each group.

I think you just want:

List<ResultLine> result = Lines
    .GroupBy(l => l.ProductCode)
    .Select(cl => new ResultLine
            {
                ProductName = cl.First().Name,
                Quantity = cl.Count().ToString(),
                Price = cl.Sum(c => c.Price).ToString(),
            }).ToList();

The use of First() here to get the product name assumes that every product with the same product code has the same product name. As noted in comments, you could group by product name as well as product code, which will give the same results if the name is always the same for any given code, but apparently generates better SQL in EF.

I'd also suggest that you should change the Quantity and Price properties to be int and decimal types respectively - why use a string property for data which is clearly not textual?

How to install SignTool.exe for Windows 10

If you only want SignTool and really want to minimize the install, here is a way that I just reverse-engineered my way to:

  1. Download the .iso file from https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk (current download link is http://go.microsoft.com/fwlink/p/?LinkID=2022797) The .exe download will not work, since it's an online installer that pulls down its dependencies at runtime.
  2. Unpack the .iso with a tool such as 7-zip.
  3. Install the Installers/Windows SDK Signing Tools-x86_en-us.msi file - it's only 388 KiB large. For reference, it pulls in its files from the following .cab files, so these are also needed for a standalone install:
    • 4c3ef4b2b1dc72149f979f4243d2accf.cab (339 KiB)
    • 685f3d4691f444bc382762d603a99afc.cab (1002 KiB)
    • e5c4b31ff9997ac5603f4f28cd7df602.cab (389 KiB)
    • e98fa5eb5fee6ce17a7a69d585870b7c.cab (1.2 MiB)

There we go - you will now have the signtool.exe file and companions in C:\Program Files (x86)\Windows Kits\10\bin\10.0.17763.0\x64 (replace x64 with x86, arm or arm64 if you need it for another CPU architecture.)


It is also possible to commit signtool.exe and the other files from this folder into your version control repository if want to use it in e.g. CI scenarios. I have tried it and it seems to work fine.

(All files are probably not necessary since there are also some other .exe tools in this folder that might be responsible for these dependencies, but I am not sure which ones could be removed to make the set of files even smaller. Someone else is free to investigate further in this area. :) I tried to just copy signtool.* and that didn't work, so at least some of the other files are needed.)

unix diff side-to-side results?

From man diff, you can use -y to do side-by-side.

-y, --side-by-side
       output in two columns

Hence, say:

diff -y /tmp/test1  /tmp/test2

Test

$ cat a                $ cat b
hello                  hello
my name                my name
is me                  is you

Let's compare them:

$ diff -y a b
hello                                                           hello
my name                                                         my name
is me                                                         | is you

how to get date of yesterday using php?

you can do this by

date("F j, Y", time() - 60 * 60 * 24);

or by

date("F j, Y", strtotime("yesterday"));

What's the u prefix in a Python string?

It's Unicode.

Just put the variable between str(), and it will work fine.

But in case you have two lists like the following:

a = ['co32','co36']
b = [u'co32',u'co36']

If you check set(a)==set(b), it will come as False, but if you do as follows:

b = str(b)
set(a)==set(b)

Now, the result will be True.

CreateProcess error=2, The system cannot find the file specified

The complete first argument of exec is being interpreted as the executable. Use

p = rt.exec(new String[] {"winrar.exe", "x", "h:\\myjar.jar", "*.*", "h:\\new" }
            null, 
            dir);

Change package name for Android in React Native

You can use react-native-rename package which will take of all the necessary changes of package name under

app/mainapplication.java

AndroidManifest.xml

but make sure to manually change the package name of all files under the java/com folder. because when i created an splash screen activity the old package name is not updated.

https://www.npmjs.com/package/react-native-rename

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

As accepted answer has provided required info, and for more info about using and disabling App Transport Security one can find more on this.

For Per-Domain Exceptions add these to the Info.plist:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSExceptionDomains</key>
  <dict>
    <key>yourserver.com</key>
    <dict>
      <!--Include to allow subdomains-->
      <key>NSIncludesSubdomains</key>
      <true/>
      <!--Include to allow HTTP requests-->
      <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
      <true/>
      <!--Include to specify minimum TLS version-->
      <key>NSTemporaryExceptionMinimumTLSVersion</key>
      <string>TLSv1.1</string>
    </dict>
  </dict>
</dict>

But What If I Don’t Know All the Insecure Domains I Need to Use? Use following key in your Info.plist

<key>NSAppTransportSecurity</key>
<dict>
  <!--Include to allow all connections (DANGER)-->
  <key>NSAllowsArbitraryLoads</key>
      <true/>
</dict>

For more detail you can get from this link.

Modifying the "Path to executable" of a windows service

A little bit deeper with 'SC' command, we are able to extract all 'Services Name' and got all 'QueryServiceConfig' :)

>SC QUERY > "%computername%-services.txt" [enter]

>FIND "SERVICE_NAME: " "%computername%-services.txt" /i > "%computername%-services-name.txt" [enter]

>NOTEPAD2 "%computername%-services-name.txt" [enter]

Do 'small' NOTEPAD2 editing.. Select 'SERVICE_NAME: ', CTRL+H, click 'Replace All' Imagine that we can do 'Replace All' within 'CMD'

Then, continue with 'CMD'..

>FOR /F "DELIMS= SKIP=2" %S IN ('TYPE "%computername%-services-name.txt"') DO @SC QC "%S" >> "%computername%-services-list-config.txt" [enter]

>NOTEPAD2 "%computername%-services-list-config.txt" [enter]

it is 'SERVICES on Our Machine' Raw data is ready for feeding 'future batch file' so the result is look like this below!!!

+ -------------+-------------------------+---------------------------+---------------+--------------------------------------------------+------------------+-----+----------------+--------------+--------------------+
| SERVICE_NAME | TYPE                    | START_TYPE                | ERROR_CONTROL | BINARY_PATH_NAME                                 | LOAD_ORDER_GROUP | TAG | DISPLAY_NAME   | DEPENDENCIES | SERVICE_START_NAME |
+ -------------+-------------------------+---------------------------+---------------+--------------------------------------------------+------------------+-----+----------------+--------------+--------------------+
+ WSearch      | 10  WIN32_OWN_PROCESS   | 2   AUTO_START  (DELAYED) | 1   NORMAL    | C:\Windows\system32\SearchIndexer.exe /Embedding | none             | 0   | Windows Search | RPCSS        | LocalSystem        |
+ wuauserv     | 20  WIN32_SHARE_PROCESS | 2   AUTO_START  (DELAYED) | 1   NORMAL    | C:\Windows\system32\svchost.exe -k netsvcs       | none             | 0   | Windows Update | rpcss        | LocalSystem        |

But, HTML will be pretty easier :D

Any bright ideas for improvement are welcome V^_^

Downloading images with node.js

I'd suggest using the request module. Downloading a file is as simple as the following code:

var fs = require('fs'),
    request = require('request');

var download = function(uri, filename, callback){
  request.head(uri, function(err, res, body){
    console.log('content-type:', res.headers['content-type']);
    console.log('content-length:', res.headers['content-length']);

    request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
  });
};

download('https://www.google.com/images/srpr/logo3w.png', 'google.png', function(){
  console.log('done');
});

Centos/Linux setting logrotate to maximum file size for all logs

As mentioned by Zeeshan, the logrotate options size, minsize, maxsize are triggers for rotation.

To better explain it. You can run logrotate as often as you like, but unless a threshold is reached such as the filesize being reached or the appropriate time passed, the logs will not be rotated.

The size options do not ensure that your rotated logs are also of the specified size. To get them to be close to the specified size you need to call the logrotate program sufficiently often. This is critical.

For log files that build up very quickly (e.g. in the hundreds of MB a day), unless you want them to be very large you will need to ensure logrotate is called often! this is critical.

Therefore to stop your disk filling up with multi-gigabyte log files you need to ensure logrotate is called often enough, otherwise the log rotation will not work as well as you want.

on Ubuntu, you can easily switch to hourly rotation by moving the script /etc/cron.daily/logrotate to /etc/cron.hourly/logrotate

Or add

*/5 * * * * /etc/cron.daily/logrotate 

To your /etc/crontab file. To run it every 5 minutes.

The size option ignores the daily, weekly, monthly time options. But minsize & maxsize take it into account.

The man page is a little confusing there. Here's my explanation.

minsize rotates only when the file has reached an appropriate size and the set time period has passed. e.g. minsize 50MB + daily If file reaches 50MB before daily time ticked over, it'll keep growing until the next day.

maxsize will rotate when the log reaches a set size or the appropriate time has passed. e.g. maxsize 50MB + daily. If file is 50MB and we're not at the next day yet, the log will be rotated. If the file is only 20MB and we roll over to the next day then the file will be rotated.

size will rotate when the log > size. Regardless of whether hourly/daily/weekly/monthly is specified. So if you have size 100M - it means when your log file is > 100M the log will be rotated if logrotate is run when this condition is true. Once it's rotated, the main log will be 0, and a subsequent run will do nothing.

So in the op's case. Specficially 50MB max I'd use something like the following:

/var/log/logpath/*.log {
    maxsize 50M
    hourly
    missingok
    rotate 8
    compress
    notifempty
    nocreate
}

Which means he'd create 8hrs of logs max. And there would be 8 of them at no more than 50MB each. Since he's saying that he's getting multi gigabytes each day and assuming they build up at a fairly constant rate, and maxsize is used he'll end up with around close to the max reached for each file. So they will be likely close to 50MB each. Given the volume they build, he would need to ensure that logrotate is run often enough to meet the target size.

Since I've put hourly there, we'd need logrotate to be run a minimum of every hour. But since they build up to say 2 gigabytes per day and we want 50MB... assuming a constant rate that's 83MB per hour. So you can imagine if we run logrotate every hour, despite setting maxsize to 50 we'll end up with 83MB log's in that case. So in this instance set the running to every 30 minutes or less should be sufficient.

Ensure logrotate is run every 30 mins.

*/30 * * * * /etc/cron.daily/logrotate 

Could not find a part of the path ... bin\roslyn\csc.exe

Reboot Windows.

This is the only solution that worked for me after trying rebuild, delete contents of bin and rebuild, restart Visual Studio.

It's yet another example of how terrible C#/.NET build tools are.

I think (after reading many of the answers), the overall conclusion is that the cause and solution of this problem heavily depends on the setup and project, so if one answer does not work, just try another. Try non-intrusive/destructive solutions, such as restarting Visual Studio, rebooting, rebuilding, etc., FIRST, before messing with NuGet packages or reinstalling development tools. Good luck!

(NOTE: Using Visual Studio 2019, and project file was originally created in Visual Studio 2015. Maybe this helps someone investigate the issue)

(EDIT: Could this be caused by not rebooting after installing/modifying the Visual Studio installation or updating Visual Studio when the installer prompts to reboot?)

Better way to cast object to int

There's also TryParse.

From MSDN:

private static void TryToParse(string value)
   {
      int number;
      bool result = Int32.TryParse(value, out number);
      if (result)
      {
         Console.WriteLine("Converted '{0}' to {1}.", value, number);         
      }
      else
      {
         if (value == null) value = ""; 
         Console.WriteLine("Attempted conversion of '{0}' failed.", value);
      }
   }

AngularJs: Reload page

My solution to avoid the infinite loop was to create another state which have made the redirection:

$stateProvider.state('app.admin.main', {
    url: '/admin/main',
    authenticate: 'admin',
    controller: ($state, $window) => {
      $state.go('app.admin.overview').then(() => {
        $window.location.reload();
      });
    }
  });

Is it possible to refresh a single UITableViewCell in a UITableView?

reloadRowsAtIndexPaths: is fine, but still will force UITableViewDelegate methods to fire.

The simplest approach I can imagine is:

UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:indexPath];
[self configureCell:cell forIndexPath:indexPath];

It's important to invoke your configureCell: implementation on main thread, as it wont work on non-UI thread (the same story with reloadData/reloadRowsAtIndexPaths:). Sometimes it might be helpful to add:

dispatch_async(dispatch_get_main_queue(), ^
{
    [self configureCell:cell forIndexPath:indexPath];
});

It's also worth to avoid work that would be done outside of the currently visible view:

BOOL cellIsVisible = [[self.tableView indexPathsForVisibleRows] indexOfObject:indexPath] != NSNotFound;
if (cellIsVisible)
{
    ....
}

Angular: How to update queryParams without changing route

You can navigate to the current route with new query params, which will not reload your page, but will update query params.

Something like (in the component):

constructor(private router: Router) { }

public myMethodChangingQueryParams() {
  const queryParams: Params = { myParam: 'myNewValue' };

  this.router.navigate(
    [], 
    {
      relativeTo: activatedRoute,
      queryParams: queryParams, 
      queryParamsHandling: 'merge', // remove to replace all query params by provided
    });
}

Note, that whereas it won't reload the page, it will push a new entry to the browser's history. If you want to replace it in the history instead of adding new value there, you could use { queryParams: queryParams, replaceUrl: true }.

EDIT: As already pointed out in the comments, [] and the relativeTo property was missing in my original example, so it could have changed the route as well, not just query params. The proper this.router.navigate usage will be in this case:

this.router.navigate(
  [], 
  {
    relativeTo: this.activatedRoute,
    queryParams: { myParam: 'myNewValue' },
    queryParamsHandling: 'merge'
  });

Setting the new parameter value to null will remove the param from the URL.

Best way to change font colour halfway through paragraph?

<span style="color:orange;">orange text</span>

Is the only way I know of barring the font tag.

How to list all databases in the mongo shell?

For MongoDB shell version 3.0.5 insert the following command in the shell:

db.adminCommand('listDatabases')

or alternatively:

db.getMongo().getDBNames()

How to change theme for AlertDialog

For Custom Dialog:

just call super(context,R.style.<dialog style>) instead of super(context) in dialog constructor

public class MyDialog extends Dialog
{
    public MyDialog(Context context)
    {
       super(context, R.style.Theme_AppCompat_Light_Dialog_Alert)
    }
}


For AlertDialog:

Just create alertDialog with this constructor:

 new AlertDialog.Builder(
 new ContextThemeWrapper(context, android.R.style.Theme_Dialog))

How to set ChartJS Y axis title?

chart.js supports this by defaul check the link. chartjs

you can set the label in the options attribute.

options object looks like this.

options = {
            scales: {
                yAxes: [
                    {
                        id: 'y-axis-1',
                        display: true,
                        position: 'left',
                        ticks: {
                            callback: function(value, index, values) {
                                return value + "%";
                            }
                        },
                        scaleLabel:{
                            display: true,
                            labelString: 'Average Personal Income',
                            fontColor: "#546372"
                        }
                    }   
                ]
            }
        };

Java Multithreading concept and join() method

My Comments:

When I see the output, the output is mixed with One, Two, Three which are the thread names and they run simultaneously. I am not sure when you say thread is not running by main method.

Not sure if I understood your question or not. But I m putting my answer what I could understand, hope it can help you.

1) Then you created the object, it called the constructor, in construct it has start method which started the thread and executed the contents written inside run() method.

So as you created 3 objects (3 threads - one, two, three), all 3 threads started executing simultaneously.

2) Join and Synchronization They are 2 different things, Synchronization is when there are multiple threads sharing a common resource and one thread should use that resource at a time. E.g. Threads such as DepositThread, WithdrawThread etc. do share a common object as BankObject. So while DepositThread is running, the WithdrawThread will wait if they are synchronized. wait(), notify(), notifyAll() are used for inter-thread communication. Plz google to know more.

about Join(), it is when multiple threads are running, but you join. e.g. if there are two thread t1 and t2 and in multi-thread env they run, the output would be: t1-0 t2-0 t1-1 t2-1 t1-2 t2-2

and we use t1.join(), it would be: t1-0 t1-1 t1-2 t2-0 t2-1 t2-2

This is used in realtime when sometimes you don't mix up the thread in certain conditions and one depends another to be completed (not in shared resource), so you can call the join() method.

Calculate distance between 2 GPS coordinates

Java Version of Haversine Algorithm based on Roman Makarov`s reply to this thread

public class HaversineAlgorithm {

    static final double _eQuatorialEarthRadius = 6378.1370D;
    static final double _d2r = (Math.PI / 180D);

    public static int HaversineInM(double lat1, double long1, double lat2, double long2) {
        return (int) (1000D * HaversineInKM(lat1, long1, lat2, long2));
    }

    public static double HaversineInKM(double lat1, double long1, double lat2, double long2) {
        double dlong = (long2 - long1) * _d2r;
        double dlat = (lat2 - lat1) * _d2r;
        double a = Math.pow(Math.sin(dlat / 2D), 2D) + Math.cos(lat1 * _d2r) * Math.cos(lat2 * _d2r)
                * Math.pow(Math.sin(dlong / 2D), 2D);
        double c = 2D * Math.atan2(Math.sqrt(a), Math.sqrt(1D - a));
        double d = _eQuatorialEarthRadius * c;

        return d;
    }

}

How do I make a redirect in PHP?

To redirect the visitor to another page (particularly useful in a conditional loop), simply use the following code:

<?php
    header('Location: mypage.php');
?>

In this case, mypage.php is the address of the page to which you would like to redirect the visitors. This address can be absolute and may also include the parameters in this format: mypage.php?param1=val1&m2=val2)

Relative/Absolute Path

When dealing with relative or absolute paths, it is ideal to choose an absolute path from the root of the server (DOCUMENT_ROOT). Use the following format:

<?php
    header('Location: /directory/mypage.php');
?>

If ever the target page is on another server, you include the full URL:

<?php
    header('Location: http://www.ccm.net/forum/');
?>

HTTP Headers

According to HTTP protocol, HTTP headers must be sent before any type of content. This means that no characters should ever be sent before the header — not even an empty space!

Temporary/Permanent Redirections

By default, the type of redirection presented above is a temporary one. This means that search engines, such as Google Search, will not take the redirection into account when indexing.

If you would like to notify search engines that a page has been permanently moved to another location, use the following code:

<?
    header('Status: 301 Moved Permanently', false, 301);
    header('Location: new_address');
?>

For example, this page has the following code:

<?
    header('Status: 301 Moved Permanently', false, 301);
    header('Location: /pc/imprimante.php3');
    exit();
?>

When you click on the link above, you are automatically redirected to this page. Moreover, it is a permanent redirection (Status: 301 Moved Permanently). So, if you type the first URL into Google, you will automatically be redirected to the second, redirected link.

Interpretation of PHP Code

The PHP code located after the header() will be interpreted by the server, even if the visitor moves to the address specified in the redirection. In most cases, this means that you need a method to follow the header() function of the exit() function in order to decrease the load of the server:

<?
    header('Status: 301 Moved Permanently', false, 301);
    header('Location: address');
    exit();
?>

How to change option menu icon in the action bar?

1) Declare menu in your class.

private Menu menu;

2) In onCreateOptionsMenu do the following :

public boolean onCreateOptionsMenu(Menu menu) {
    this.menu = menu;
    getMenuInflater().inflate(R.menu.menu_orders_screen, menu);
    return true;
}   

3) In onOptionsItemSelected, get the item and do the changes as required(icon, text, colour, background)

public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_search) {
        return true;
    }
    if (id == R.id.ventor_status) {
        return true;
    }
    if (id == R.id.action_settings_online) {
        menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.history_converted));
        menu.getItem(1).setTitle("Online");
        return true;
    }
    if (id == R.id.action_settings_offline) {
        menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.cross));
        menu.getItem(1).setTitle("Offline");
        return true;
    }

    return super.onOptionsItemSelected(item);
}

Note:
If you have 3 menu items :
menu.getItem(0) = 1 item,
menu.getItem(1) = 2 iteam,
menu.getItem(2) = 3 item

Based on this make the changes accordingly as per your requirement.

Convert Java Array to Iterable

With Java 8, you can do this.

final int[] arr = {1, 2, 3};
final PrimitiveIterator.OfInt i1 = Arrays.stream(arr).iterator();
final PrimitiveIterator.OfInt i2 = IntStream.of(arr).iterator();
final Iterator<Integer> i3 = IntStream.of(arr).boxed().iterator();

Best way to remove the last character from a string built with stringbuilder

The simplest and most efficient way is to perform this command:

data.Length--;

by doing this you move the pointer (i.e. last index) back one character but you don't change the mutability of the object. In fact, clearing a StringBuilder is best done with Length as well (but do actually use the Clear() method for clarity instead because that's what its implementation looks like):

data.Length = 0;

again, because it doesn't change the allocation table. Think of it like saying, I don't want to recognize these bytes anymore. Now, even when calling ToString(), it won't recognize anything past its Length, well, it can't. It's a mutable object that allocates more space than what you provide it, it's simply built this way.

How do you run a script on login in *nix?

Search your local system's bash man page for ^INVOCATION for information on which file is going to be read at startup.

man bash
/^INVOCATION

Also in the FILES section,

   ~/.bash_profile
          The personal initialization file, executed for login shells
   ~/.bashrc
          The individual per-interactive-shell startup file

Add your script to the proper file. Make sure the script is in the $PATH, or use the absolute path to the script file.

What is the significance of load factor in HashMap?

For HashMap DEFAULT_INITIAL_CAPACITY = 16 and DEFAULT_LOAD_FACTOR = 0.75f it means that MAX number of ALL Entries in the HashMap = 16 * 0.75 = 12. When the thirteenth element will be added capacity (array size) of HashMap will be doubled! Perfect illustration answered this question: enter image description here image is taken from here:

https://javabypatel.blogspot.com/2015/10/what-is-load-factor-and-rehashing-in-hashmap.html

OpenCV - DLL missing, but it's not?

just open the bin folder and copy and paste the .dll files to the folder you are working in..it should fix the problem

Submit HTML form, perform javascript function (alert then redirect)

<form action="javascript:completeAndRedirect();">
    <input type="text" id="Edit1" 
    style="width:280; height:50; font-family:'Lucida Sans Unicode', 'Lucida Grande', sans-serif; font-size:22px">
</form>

Changing action to point at your function would solve the problem, in a different way.

What are SP (stack) and LR in ARM?

LR is link register used to hold the return address for a function call.

SP is stack pointer. The stack is generally used to hold "automatic" variables and context/parameters across function calls. Conceptually you can think of the "stack" as a place where you "pile" your data. You keep "stacking" one piece of data over the other and the stack pointer tells you how "high" your "stack" of data is. You can remove data from the "top" of the "stack" and make it shorter.

From the ARM architecture reference:

SP, the Stack Pointer

Register R13 is used as a pointer to the active stack.

In Thumb code, most instructions cannot access SP. The only instructions that can access SP are those designed to use SP as a stack pointer. The use of SP for any purpose other than as a stack pointer is deprecated. Note Using SP for any purpose other than as a stack pointer is likely to break the requirements of operating systems, debuggers, and other software systems, causing them to malfunction.

LR, the Link Register

Register R14 is used to store the return address from a subroutine. At other times, LR can be used for other purposes.

When a BL or BLX instruction performs a subroutine call, LR is set to the subroutine return address. To perform a subroutine return, copy LR back to the program counter. This is typically done in one of two ways, after entering the subroutine with a BL or BLX instruction:

• Return with a BX LR instruction.

• On subroutine entry, store LR to the stack with an instruction of the form: PUSH {,LR} and use a matching instruction to return: POP {,PC} ...

This link gives an example of a trivial subroutine.

Here is an example of how registers are saved on the stack prior to a call and then popped back to restore their content.

Laravel 4: Redirect to a given url

You can also use redirect() method like this:-

return redirect('https://stackoverflow.com/');

How can I use SUM() OVER()

Seems like you expected the query to return running totals, but it must have given you the same values for both partitions of AccountID.

To obtain running totals with SUM() OVER (), you need to add an ORDER BY sub-clause after PARTITION BY …, like this:

SUM(Quantity) OVER (PARTITION BY AccountID ORDER BY ID)

But remember, not all database systems support ORDER BY in the OVER clause of a window aggregate function. (For instance, SQL Server didn't support it until the latest version, SQL Server 2012.)

take(1) vs first()

Here are three Observables A, B, and C with marble diagrams to explore the difference between first, take, and single operators:

first vs take vs single operators comparison

* Legend:
--o-- value
----! error
----| completion

Play with it at https://thinkrx.io/rxjs/first-vs-take-vs-single/ .

Already having all the answers, I wanted to add a more visual explanation

Hope it helps someone

Creating a 3D sphere in Opengl using Visual C++

It doesn't seem like anyone so far has addressed the actual problem with your original code, so I thought I would do that even though the question is quite old at this point.

The problem originally had to do with the projection in relation to the radius and position of the sphere. I think you'll find that the problem isn't too complicated. The program actually works correctly, it's just that what is being drawn is very hard to see.

First, an orthogonal projection was created using the call

gluOrtho2D(0.0, 499.0, 0.0, 499.0);

which "is equivalent to calling glOrtho with near = -1 and far = 1." This means that the viewing frustum has a depth of 2. So a sphere with a radius of anything greater than 1 (diameter = 2) will not fit entirely within the viewing frustum.

Then the calls

glLoadIdentity();
glutSolidSphere(5.0, 20.0, 20.0);

are used, which loads the identity matrix of the model-view matrix and then "[r]enders a sphere centered at the modeling coordinates origin of the specified radius." Meaning, the sphere is rendered at the origin, (x, y, z) = (0, 0, 0), and with a radius of 5.

Now, the issue is three-fold:

  1. Since the window is 500x500 pixels and the width and height of the viewing frustum is almost 500 (499.0), the small radius of the sphere (5.0) makes its projected area only slightly over one fiftieth (2*5/499) of the size of the window in each dimension. This means that the apparent size of the sphere would be roughly 1/2,500th (actually pi*5^2/499^2, which is closer to about 1/3170th) of the entire window, so it might be difficult to see. This is assuming the entire circle is drawn within the area of the window. It is not, however, as we will see in point 2.
  2. Since the viewing frustum has it's left plane at x = 0 and bottom plane at y = 0, the sphere will be rendered with its geometric center in the very bottom left corner of the window so that only one quadrant of the projected sphere will be visible! This means that what would be seen is even smaller, about 1/10,000th (actually pi*5^2/(4*499^2), which is closer to 1/12,682nd) of the window size. This would make it even more difficult to see. Especially since the sphere is rendered so close to the edges/corner of the screen where you might not think to look.
  3. Since the depth of the viewing frustum is significantly smaller than the diameter of the sphere (less than half), only a sliver of the sphere will be within the viewing frustum, rendering only that part. So you will get more like a hollow circle on the screen than a solid sphere/circle. As it happens, the thickness of that sliver might represent less than 1 pixel on the screen which means we might even see nothing on the screen, even if part of the sphere is indeed within the viewing frustum.

The solution is simply to change the viewing frustum and radius of the sphere. For instance,

gluOrtho2D(-5.0, 5.0, -5.0, 5.0);
glutSolidSphere(5.0, 20, 20);

renders the following image.

r = 5.0

As you can see, only a small part is visible around the "equator", of the sphere with a radius of 5. (I changed the projection to fill the window with the sphere.) Another example,

gluOrtho2D(-1.1, 1.1, -1.1, 1.1);
glutSolidSphere(1.1, 20, 20);

renders the following image.

r = 1.1

The image above shows more of the sphere inside of the viewing frustum, but still the sphere is 0.2 depth units larger than the viewing frustum. As you can see, the "ice caps" of the sphere are missing, both the north and the south. So, if we want the entire sphere to fit within the viewing frustum which has depth 2, we must make the radius less than or equal to 1.

gluOrtho2D(-1.0, 1.0, -1.0, 1.0);
glutSolidSphere(1.0, 20, 20);

renders the following image.

r = 1.0

I hope this has helped someone. Take care!

ImageMagick security policy 'PDF' blocking conversion

Works in Ubuntu 20.04

Add this line inside <policymap>

<policy domain="module" rights="read|write" pattern="{PS,PDF,XPS}" />

Comment these lines:

  <!--
  <policy domain="coder" rights="none" pattern="PS" />
  <policy domain="coder" rights="none" pattern="PS2" />
  <policy domain="coder" rights="none" pattern="PS3" />
  <policy domain="coder" rights="none" pattern="EPS" />
  <policy domain="coder" rights="none" pattern="PDF" />
  <policy domain="coder" rights="none" pattern="XPS" />
   -->

Regular expression - starting and ending with a letter, accepting only letters, numbers and _

seeing how the rules are fairly complicated, I'd suggest the following:

/^[a-z](\w*)[a-z0-9]$/i

match the whole string and capture intermediate characters. Then either with the string functions or the following regex:

/__/

check if the captured part has two underscores in a row. For example in Python it would look like this:

>>> import re
>>> def valid(s):
    match = re.match(r'^[a-z](\w*)[a-z0-9]$', s, re.I)
    if match is not None:
        return match.group(1).count('__') == 0
    return False

Wavy shape with css

I'm not sure it's your shape but it's close - you can play with the values:

https://jsfiddle.net/7fjSc/9/

_x000D_
_x000D_
#wave {_x000D_
  position: relative;_x000D_
  height: 70px;_x000D_
  width: 600px;_x000D_
  background: #e0efe3;_x000D_
}_x000D_
#wave:before {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  border-radius: 100% 50%;_x000D_
  width: 340px;_x000D_
  height: 80px;_x000D_
  background-color: white;_x000D_
  right: -5px;_x000D_
  top: 40px;_x000D_
}_x000D_
#wave:after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  border-radius: 100% 50%;_x000D_
  width: 300px;_x000D_
  height: 70px;_x000D_
  background-color: #e0efe3;_x000D_
  left: 0;_x000D_
  top: 27px;_x000D_
}
_x000D_
<div id="wave"></div>
_x000D_
_x000D_
_x000D_

Is there a way to split a widescreen monitor in to two or more virtual monitors?

I use WinSplit Revolution for the keyboard arrangement capability and I use bblean as a replacement for Explorer. It has multiple workspace capabilities built right in and it allows you to customize it exactly how you want it to look.

How to add row in JTable?

Use:

DefaultTableModel model = new DefaultTableModel(); 
JTable table = new JTable(model); 

// Create a couple of columns 
model.addColumn("Col1"); 
model.addColumn("Col2"); 

// Append a row 
model.addRow(new Object[]{"v1", "v2"});

How to convert a string to a date in sybase

Several ways to accomplish that but be aware that your DB date_format option & date_order option settings could affect the incoming format:

Select 
   cast('2008-09-16' as date)
   convert(date,'16/09/2008',103)
   date('2008-09-16')
from dummy;

Plotting multiple time series on the same plot using ggplot()

I know this is old but it is still relevant. You can take advantage of reshape2::melt to change the dataframe into a more friendly structure for ggplot2.

Advantages:

  • allows you plot any number of lines
  • each line with a different color
  • adds a legend for each line
  • with only one call to ggplot/geom_line

Disadvantage:

  • an extra package(reshape2) required
  • melting is not so intuitive at first

For example:

jobsAFAM1 <- data.frame(
  data_date = seq.Date(from = as.Date('2017-01-01'),by = 'day', length.out = 100),
  Percent.Change = runif(5,1,100)
)

jobsAFAM2 <- data.frame(
  data_date = seq.Date(from = as.Date('2017-01-01'),by = 'day', length.out = 100),
  Percent.Change = runif(5,1,100)
)

jobsAFAM <- merge(jobsAFAM1, jobsAFAM2, by="data_date")

jobsAFAMMelted <- reshape2::melt(jobsAFAM, id.var='data_date')

ggplot(jobsAFAMMelted, aes(x=data_date, y=value, col=variable)) + geom_line()

enter image description here

Get value from SimpleXMLElement Object

You have to cast simpleXML Object to a string.

$value = (string) $xml->code[0]->lat;

Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

To add multiples params or headers you can do the following:

constructor(private _http: HttpClient) {}

//....

const url = `${environment.APP_API}/api/request`;

let headers = new HttpHeaders().set('header1', hvalue1); // create header object
headers = headers.append('header2', hvalue2); // add a new header, creating a new object
headers = headers.append('header3', hvalue3); // add another header

let params = new HttpParams().set('param1', value1); // create params object
params = params.append('param2', value2); // add a new param, creating a new object
params = params.append('param3', value3); // add another param 

return this._http.get<any[]>(url, { headers: headers, params: params })

How to connect to local instance of SQL Server 2008 Express

Haha, oh boy, I figured it out. Somehow, someway, I did not install the Database Engine when I installed SQL Server 2008. I have no idea how I missed that, but that's what happened.

How to show the text on a ImageButton?

Actually, android:text is not an argument accepted by ImageButton but, If you're trying to get a button with a specified background (not android default) use the android:background xml attribute, or declare it from the class with .setBackground();

Jquery change background color

This is how it should be:

Code:

$(function(){
  $("button").mouseover(function(){
    var $p = $("#P44");
    $p.stop()
      .css("background-color","yellow")
      .hide(1500, function() {
          $p.css("background-color","red")
            .show(1500);
      });
  });
});

Demo: http://jsfiddle.net/p7w9W/2/

Explanation:

You have to wait for the callback on the animating functions before you switch background color. You should also not use only numeric ID:s, and if you have an ID of your <p> there you shouldn't include a class in your selector.

I also enhanced your code (caching of the jQuery object, chaining, etc.)

Update: As suggested by VKolev the color is now changing when the item is hidden.

Could not load file or assembly CrystalDecisions.ReportAppServer.ClientDoc

It turns out the answer was ridiculously simple, but mystifying as to why it was necessary.

In the IIS Manager on the server, I set the application pool for my web application to not allow 32-bit assemblies.

It seems it assumes, on a 64-bit system, that you must want the 32 bit assembly. Bizarre.

How to specify credentials when connecting to boto3 S3?

I'd like expand on @JustAGuy's answer. The method I prefer is to use AWS CLI to create a config file. The reason is, with the config file, the CLI or the SDK will automatically look for credentials in the ~/.aws folder. And the good thing is that AWS CLI is written in python.

You can get cli from pypi if you don't have it already. Here are the steps to get cli set up from terminal

$> pip install awscli  #can add user flag 
$> aws configure
AWS Access Key ID [****************ABCD]:[enter your key here]
AWS Secret Access Key [****************xyz]:[enter your secret key here]
Default region name [us-west-2]:[enter your region here]
Default output format [None]:

After this you can access boto and any of the api without having to specify keys (unless you want to use a different credentials).

What is the meaning of "operator bool() const"

When writing my own unique_ptr, I found this case. Given std::unique_ptr's operator==:

template<class T1, class D1, class T2, class D2>
bool operator==(const unique_ptr<T1, D1>& x, const unique_ptr<T2, D2>& y);

template <class T, class D>
bool operator==(const unique_ptr<T, D>& x, nullptr_t) noexcept;

template <class T, class D>
bool operator==(nullptr_t, const unique_ptr<T, D>& x) noexcept;

And this test case from libstdcxx:

  std::unique_ptr<int> ptr;
  if (ptr == 0)
    { }
  if (0 == ptr)
    { }
  if (ptr != 0)
    { }
  if (0 != ptr)
    { }

Note because that ptr has a explicit operator bool() const noexcept;, so operator overload resolution works fine here, e.g., ptr == 0 chooses

 template <class T, class D>
 bool operator==(const unique_ptr<T, D>& x, nullptr_t) noexcept;`.

If it has no explicit keyword here, ptr in ptr == 0 will be converted into bool, then bool will be converted into int, because bool operator==(int, int) is built-in and 0 is int. What is waiting for us is ambiguous overload resolution error.

Here is a Minimal, Complete, and Verifiable example:

#include <cstddef>
struct A
{
    constexpr A(std::nullptr_t) {}
    operator bool() 
    {
        return true;
    }
};

constexpr bool operator ==(A, A) noexcept
{
    return true;
}

constexpr bool operator ==(A, std::nullptr_t) noexcept
{
    return true;
}

constexpr bool operator ==(std::nullptr_t, A) noexcept
{
    return true;
}

int main()
{
    A a1(nullptr);
    A a2(0);
    a1 == 0;
}

gcc:

prog.cc: In function 'int main()':
prog.cc:30:8: error: ambiguous overload for 'operator==' (operand types are 'A' and 'int')
   30 |     a1 == 0;
      |     ~~ ^~ ~
      |     |     |
      |     A     int
prog.cc:30:8: note: candidate: 'operator==(int, int)' <built-in>
   30 |     a1 == 0;
      |     ~~~^~~~
prog.cc:11:16: note: candidate: 'constexpr bool operator==(A, A)'
   11 | constexpr bool operator ==(A, A) noexcept
      |                ^~~~~~~~
prog.cc:16:16: note: candidate: 'constexpr bool operator==(A, std::nullptr_t)'
   16 | constexpr bool operator ==(A, std::nullptr_t) noexcept
      |                ^~~~~~~~

clang:

prog.cc:30:8: error: use of overloaded operator '==' is ambiguous (with operand types 'A' and 'int')
    a1 == 0;
    ~~ ^  ~
prog.cc:16:16: note: candidate function
constexpr bool operator ==(A, std::nullptr_t) noexcept
               ^
prog.cc:11:16: note: candidate function
constexpr bool operator ==(A, A) noexcept
               ^
prog.cc:30:8: note: built-in candidate operator==(int, int)
    a1 == 0;
       ^
prog.cc:30:8: note: built-in candidate operator==(float, int)
prog.cc:30:8: note: built-in candidate operator==(double, int)
prog.cc:30:8: note: built-in candidate operator==(long double, int)
prog.cc:30:8: note: built-in candidate operator==(__float128, int)
prog.cc:30:8: note: built-in candidate operator==(int, float)
prog.cc:30:8: note: built-in candidate operator==(int, double)
prog.cc:30:8: note: built-in candidate operator==(int, long double)
prog.cc:30:8: note: built-in candidate operator==(int, __float128)
prog.cc:30:8: note: built-in candidate operator==(int, long)
prog.cc:30:8: note: built-in candidate operator==(int, long long)
prog.cc:30:8: note: built-in candidate operator==(int, __int128)
prog.cc:30:8: note: built-in candidate operator==(int, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(int, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(int, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(int, unsigned __int128)
prog.cc:30:8: note: built-in candidate operator==(long, int)
prog.cc:30:8: note: built-in candidate operator==(long long, int)
prog.cc:30:8: note: built-in candidate operator==(__int128, int)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, int)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, int)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, int)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, int)
prog.cc:30:8: note: built-in candidate operator==(float, float)
prog.cc:30:8: note: built-in candidate operator==(float, double)
prog.cc:30:8: note: built-in candidate operator==(float, long double)
prog.cc:30:8: note: built-in candidate operator==(float, __float128)
prog.cc:30:8: note: built-in candidate operator==(float, long)
prog.cc:30:8: note: built-in candidate operator==(float, long long)
prog.cc:30:8: note: built-in candidate operator==(float, __int128)
prog.cc:30:8: note: built-in candidate operator==(float, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(float, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(float, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(float, unsigned __int128)
prog.cc:30:8: note: built-in candidate operator==(double, float)
prog.cc:30:8: note: built-in candidate operator==(double, double)
prog.cc:30:8: note: built-in candidate operator==(double, long double)
prog.cc:30:8: note: built-in candidate operator==(double, __float128)
prog.cc:30:8: note: built-in candidate operator==(double, long)
prog.cc:30:8: note: built-in candidate operator==(double, long long)
prog.cc:30:8: note: built-in candidate operator==(double, __int128)
prog.cc:30:8: note: built-in candidate operator==(double, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(double, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(double, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(double, unsigned __int128)
prog.cc:30:8: note: built-in candidate operator==(long double, float)
prog.cc:30:8: note: built-in candidate operator==(long double, double)
prog.cc:30:8: note: built-in candidate operator==(long double, long double)
prog.cc:30:8: note: built-in candidate operator==(long double, __float128)
prog.cc:30:8: note: built-in candidate operator==(long double, long)
prog.cc:30:8: note: built-in candidate operator==(long double, long long)
prog.cc:30:8: note: built-in candidate operator==(long double, __int128)
prog.cc:30:8: note: built-in candidate operator==(long double, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(long double, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(long double, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(long double, unsigned __int128)
prog.cc:30:8: note: built-in candidate operator==(__float128, float)
prog.cc:30:8: note: built-in candidate operator==(__float128, double)
prog.cc:30:8: note: built-in candidate operator==(__float128, long double)
prog.cc:30:8: note: built-in candidate operator==(__float128, __float128)
prog.cc:30:8: note: built-in candidate operator==(__float128, long)
prog.cc:30:8: note: built-in candidate operator==(__float128, long long)
prog.cc:30:8: note: built-in candidate operator==(__float128, __int128)
prog.cc:30:8: note: built-in candidate operator==(__float128, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(__float128, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(__float128, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(__float128, unsigned __int128)
prog.cc:30:8: note: built-in candidate operator==(long, float)
prog.cc:30:8: note: built-in candidate operator==(long, double)
prog.cc:30:8: note: built-in candidate operator==(long, long double)
prog.cc:30:8: note: built-in candidate operator==(long, __float128)
prog.cc:30:8: note: built-in candidate operator==(long, long)
prog.cc:30:8: note: built-in candidate operator==(long, long long)
prog.cc:30:8: note: built-in candidate operator==(long, __int128)
prog.cc:30:8: note: built-in candidate operator==(long, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(long, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(long, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(long, unsigned __int128)
prog.cc:30:8: note: built-in candidate operator==(long long, float)
prog.cc:30:8: note: built-in candidate operator==(long long, double)
prog.cc:30:8: note: built-in candidate operator==(long long, long double)
prog.cc:30:8: note: built-in candidate operator==(long long, __float128)
prog.cc:30:8: note: built-in candidate operator==(long long, long)
prog.cc:30:8: note: built-in candidate operator==(long long, long long)
prog.cc:30:8: note: built-in candidate operator==(long long, __int128)
prog.cc:30:8: note: built-in candidate operator==(long long, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(long long, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(long long, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(long long, unsigned __int128)
prog.cc:30:8: note: built-in candidate operator==(__int128, float)
prog.cc:30:8: note: built-in candidate operator==(__int128, double)
prog.cc:30:8: note: built-in candidate operator==(__int128, long double)
prog.cc:30:8: note: built-in candidate operator==(__int128, __float128)
prog.cc:30:8: note: built-in candidate operator==(__int128, long)
prog.cc:30:8: note: built-in candidate operator==(__int128, long long)
prog.cc:30:8: note: built-in candidate operator==(__int128, __int128)
prog.cc:30:8: note: built-in candidate operator==(__int128, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(__int128, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(__int128, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(__int128, unsigned __int128)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, float)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, double)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, long double)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, __float128)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, long)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, long long)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, __int128)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, unsigned __int128)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, float)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, double)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, long double)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, __float128)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, long)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, long long)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, __int128)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, unsigned __int128)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, float)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, double)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, long double)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, __float128)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, long)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, long long)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, __int128)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, unsigned __int128)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, float)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, double)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, long double)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, __float128)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, long)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, long long)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, __int128)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, unsigned __int128)
1 error generated.

NLS_NUMERIC_CHARACTERS setting for decimal

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

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

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

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

select to_number(5/2) from dual;

Pandas: how to change all the values of a column?

Or if one want to use lambda function in the apply function:

data['Revenue']=data['Revenue'].apply(lambda x:float(x.replace("$","").replace(",", "").replace(" ", "")))

moment.js, how to get day of week number

If you are specifically looking for the 1-7 approach...

This is the ISO weekday number. moment.js has also taken this into account. Use isoWeekday()

_x000D_
_x000D_
console.log(moment().isoWeekday()); // returns 1-7 where 1 is Monday and 7 is Sunday
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Seeing as I wrote this answer on a Tuesday, today this gives me a 2.

Install a Python package into a different directory using pip?

If you are using brew with python, unfortunately, pip/pip3 ships with very limited options. You do not have --install-option, --target, --user options as mentioned above.

Note on pip install --user
The normal pip install --user is disabled for brewed Python. This is because of a bug in distutils, because Homebrew writes a distutils.cfg which sets the package prefix. A possible workaround (which puts executable scripts in ~/Library/Python/./bin) is: python -m pip install --user --install-option="--prefix=" <package-name>

You might find this line very cumbersome. I suggest use pyenv for management. If you are using

brew upgrade python python3

Ironically you are actually downgrade pip functionality.

(I post this answer, simply because pip in my mac osx does not have --target option, and I have spent hours fixing it)

avrdude: stk500v2_ReceiveMessage(): timeout

I got this error because I didn't specify the correct programmer in the avrdude command line. You have to specify "-c arduino" if you are using an Arduino board.

This example command reads the status of the hfuse:

avrdude -c arduino -P /dev/ttyACM0 -p atmega328p -U hfuse:r:-:h

Get first day of week in SQL Server

For those who need the answer at work and creating function is forbidden by your DBA, the following solution will work:

select *,
cast(DATEADD(day, -1*(DATEPART(WEEKDAY, YouDate)-1), YourDate) as DATE) as WeekStart
From.....

This gives the start of that week. Here I assume that Sundays are the start of weeks. If you think that Monday is the start, you should use:

select *,
cast(DATEADD(day, -1*(DATEPART(WEEKDAY, YouDate)-2), YourDate) as DATE) as WeekStart
From.....

Listen to port via a Java socket

What do you actually want to achieve? What your code does is it tries to connect to a server located at 192.168.1.104:4000. Is this the address of a server that sends the messages (because this looks like a client-side code)? If I run fake server locally:

$ nc -l 4000

...and change socket address to localhost:4000, it will work and try to read something from nc-created server.

What you probably want is to create a ServerSocket and listen on it:

ServerSocket serverSocket = new ServerSocket(4000);
Socket socket = serverSocket.accept();

The second line will block until some other piece of software connects to your machine on port 4000. Then you can read from the returned socket. Look at this tutorial, this is actually a very broad topic (threading, protocols...)

How can I convert a comma-separated string to an array?

As @oportocala mentions, an empty string will not result in the expected empty array.

So to counter, do:

str
.split(',')
.map(entry => entry.trim())
.filter(entry => entry)

For an array of expected integers, do:

str
.split(',')
.map(entry => parseInt(entry))
.filter(entry => typeof entry ==='number')

Pythonic way to add datetime.date and datetime.time objects

It's in the python docs.

import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1), 
                          datetime.time(10, 23))

returns

datetime.datetime(2011, 1, 1, 10, 23)

How to strip comma in Python string

unicode('foo,bar').translate(dict([[ord(char), u''] for char in u',']))

How do I enable TODO/FIXME/XXX task tags in Eclipse?

There are apparently distributions or custom builds in which the ability to set Task Tags for non-Java files is not present. This post mentions that ColdFusion Builder (built on Eclipse) does not let you set non-Java Task Tags, but the beta version of CF Builder 2 does. (I know the OP wasn't using CF Builder, but I am, and I was wondering about this question myself ... because he didn't see the ability to set non-Java tags, I thought others might be in the same position.)

How do I get current URL in Selenium Webdriver 2 Python?

Selenium2Library has get_location():

import Selenium2Library
s = Selenium2Library.Selenium2Library()
url = s.get_location()

Disable vertical scroll bar on div overflow: auto

overflow: auto;
overflow-y: hidden;

For IE8: -ms-overflow-y: hidden;

Or Else :

To hide X:

<div style="height:150x; width:450px; overflow-x:hidden; overflow-y: scroll; padding-bottom:10px;"></div>

To hide Y:

<div style="height:150px; width:450px; overflow-x:scroll ; overflow-y: hidden; padding-bottom:10px;"></div>

Create PostgreSQL ROLE (user) if it doesn't exist

Or if the role is not the owner of any db objects one can use:

DROP ROLE IF EXISTS my_user;
CREATE ROLE my_user LOGIN PASSWORD 'my_password';

But only if dropping this user will not make any harm.

make *** no targets specified and no makefile found. stop

Unpack the source from a working directory and cd into the file directory as root. Use the commands ./configure then make and make install

How to get Wikipedia content using Wikipedia's API?

To GET first paragraph of an article:

https://en.wikipedia.org/w/api.php?action=query&titles=Belgrade&prop=extracts&format=json&exintro=1

I have created short Wikipedia API docs for my own needs. There are working examples on how to get article(s), image(s) and similar.

What is the origin of foo and bar?

tl;dr

  • "Foo" and "bar" as metasyntactic variables were popularised by MIT and DEC, the first references are in work on LISP and PDP-1 and Project MAC from 1964 onwards.

  • Many of these people were in MIT's Tech Model Railroad Club, where we find the first documented use of "foo" in tech circles in 1959 (and a variant in 1958).

  • Both "foo" and "bar" (and even "baz") were well known in popular culture, especially from Smokey Stover and Pogo comics, which will have been read by many TMRC members.

  • Also, it seems likely the military FUBAR contributed to their popularity.


The use of lone "foo" as a nonsense word is pretty well documented in popular culture in the early 20th century, as is the military FUBAR. (Some background reading: FOLDOC FOLDOC Jargon File Jargon File Wikipedia RFC3092)


OK, so let's find some references.

STOP PRESS! After posting this answer, I discovered this perfect article about "foo" in the Friday 14th January 1938 edition of The Tech ("MIT's oldest and largest newspaper & the first newspaper published on the web"), Volume LVII. No. 57, Price Three Cents:

On Foo-ism

The Lounger thinks that this business of Foo-ism has been carried too far by its misguided proponents, and does hereby and forthwith take his stand against its abuse. It may be that there's no foo like an old foo, and we're it, but anyway, a foo and his money are some party. (Voice from the bleachers- "Don't be foo-lish!")

As an expletive, of course, "foo!" has a definite and probably irreplaceable position in our language, although we fear that the excessive use to which it is currently subjected may well result in its falling into an early (and, alas, a dark) oblivion. We say alas because proper use of the word may result in such happy incidents as the following.

It was an 8.50 Thermodynamics lecture by Professor Slater in Room 6-120. The professor, having covered the front side of the blackboard, set the handle that operates the lift mechanism, turning meanwhile to the class to continue his discussion. The front board slowly, majestically, lifted itself, revealing the board behind it, and on that board, writ large, the symbols that spelled "FOO"!

The Tech newspaper, a year earlier, the Letter to the Editor, September 1937:

By the time the train has reached the station the neophytes are so filled with the stories of the glory of Phi Omicron Omicron, usually referred to as Foo, that they are easy prey.

...

It is not that I mind having lost my first four sons to the Grand and Universal Brotherhood of Phi Omicron Omicron, but I do wish that my fifth son, my baby, should at least be warned in advance.

Hopefully yours,

Indignant Mother of Five.

And The Tech in December 1938:

General trend of thought might be best interpreted from the remarks made at the end of the ballots. One vote said, '"I don't think what I do is any of Pulver's business," while another merely added a curt "Foo."


The first documented "foo" in tech circles is probably 1959's Dictionary of the TMRC Language:

FOO: the sacred syllable (FOO MANI PADME HUM); to be spoken only when under inspiration to commune with the Deity. Our first obligation is to keep the Foo Counters turning.

These are explained at FOLDOC. The dictionary's compiler Pete Samson said in 2005:

Use of this word at TMRC antedates my coming there. A foo counter could simply have randomly flashing lights, or could be a real counter with an obscure input.

And from 1996's Jargon File 4.0.0:

Earlier versions of this lexicon derived 'baz' as a Stanford corruption of bar. However, Pete Samson (compiler of the TMRC lexicon) reports it was already current when he joined TMRC in 1958. He says "It came from "Pogo". Albert the Alligator, when vexed or outraged, would shout 'Bazz Fazz!' or 'Rowrbazzle!' The club layout was said to model the (mythical) New England counties of Rowrfolk and Bassex (Rowrbazzle mingled with (Norfolk/Suffolk/Middlesex/Essex)."

A year before the TMRC dictionary, 1958's MIT Voo Doo Gazette ("Humor suplement of the MIT Deans' office") (PDF) mentions Foocom, in "The Laws of Murphy and Finagle" by John Banzhaf (an electrical engineering student):

Further research under a joint Foocom and Anarcom grant expanded the law to be all embracing and universally applicable: If anything can go wrong, it will!

Also 1964's MIT Voo Doo (PDF) references the TMRC usage:

Yes! I want to be an instant success and snow customers. Send me a degree in: ...

  • Foo Counters

  • Foo Jung


Let's find "foo", "bar" and "foobar" published in code examples.

So, Jargon File 4.4.7 says of "foobar":

Probably originally propagated through DECsystem manuals by Digital Equipment Corporation (DEC) in 1960s and early 1970s; confirmed sightings there go back to 1972.

The first published reference I can find is from February 1964, but written in June 1963, The Programming Language LISP: its Operation and Applications by Information International, Inc., with many authors, but including Timothy P. Hart and Michael Levin:

Thus, since "FOO" is a name for itself, "COMITRIN" will treat both "FOO" and "(FOO)" in exactly the same way.

Also includes other metasyntactic variables such as: FOO CROCK GLITCH / POOT TOOR / ON YOU / SNAP CRACKLE POP / X Y Z

I expect this is much the same as this next reference of "foo" from MIT's Project MAC in January 1964's AIM-064, or LISP Exercises by Timothy P. Hart and Michael Levin:

car[((FOO . CROCK) . GLITCH)]

It shares many other metasyntactic variables like: CHI / BOSTON NEW YORK / SPINACH BUTTER STEAK / FOO CROCK GLITCH / POOT TOOP / TOOT TOOT / ISTHISATRIVIALEXCERCISE / PLOOP FLOT TOP / SNAP CRACKLE POP / ONE TWO THREE / PLANE SUB THRESHER

For both "foo" and "bar" together, the earliest reference I could find is from MIT's Project MAC in June 1966's AIM-098, or PDP-6 LISP by none other than Peter Samson:

EXPLODE, like PRIN1, inserts slashes, so (EXPLODE (QUOTE FOO/ BAR)) PRIN1's as (F O O // / B A R) or PRINC's as (F O O / B A R).


Some more recallations.

@Walter Mitty recalled on this site in 2008:

I second the jargon file regarding Foo Bar. I can trace it back at least to 1963, and PDP-1 serial number 2, which was on the second floor of Building 26 at MIT. Foo and Foo Bar were used there, and after 1964 at the PDP-6 room at project MAC.

John V. Everett recalls in 1996:

When I joined DEC in 1966, foobar was already being commonly used as a throw-away file name. I believe fubar became foobar because the PDP-6 supported six character names, although I always assumed the term migrated to DEC from MIT. There were many MIT types at DEC in those days, some of whom had worked with the 7090/7094 CTSS. Since the 709x was also a 36 bit machine, foobar may have been used as a common file name there.

Foo and bar were also commonly used as file extensions. Since the text editors of the day operated on an input file and produced an output file, it was common to edit from a .foo file to a .bar file, and back again.

It was also common to use foo to fill a buffer when editing with TECO. The text string to exactly fill one disk block was IFOO$HXA127GA$$. Almost all of the PDP-6/10 programmers I worked with used this same command string.

Daniel P. B. Smith in 1998:

Dick Gruen had a device in his dorm room, the usual assemblage of B-battery, resistors, capacitors, and NE-2 neon tubes, which he called a "foo counter." This would have been circa 1964 or so.

Robert Schuldenfrei in 1996:

The use of FOO and BAR as example variable names goes back at least to 1964 and the IBM 7070. This too may be older, but that is where I first saw it. This was in Assembler. What would be the FORTRAN integer equivalent? IFOO and IBAR?

Paul M. Wexelblat in 1992:

The earliest PDP-1 Assembler used two characters for symbols (18 bit machine) programmers always left a few words as patch space to fix problems. (Jump to patch space, do new code, jump back) That space conventionally was named FU: which stood for Fxxx Up, the place where you fixed Fxxx Ups. When spoken, it was known as FU space. Later Assemblers ( e.g. MIDAS allowed three char tags so FU became FOO, and as ALL PDP-1 programmers will tell you that was FOO space.

Bruce B. Reynolds in 1996:

On the IBM side of FOO(FU)BAR is the use of the BAR side as Base Address Register; in the middle 1970's CICS programmers had to worry out the various xxxBARs...I think one of those was FRACTBAR...

Here's a straight IBM "BAR" from 1955.


Other early references:


I haven't been able to find any references to foo bar as "inverted foo signal" as suggested in RFC3092 and elsewhere.

Here are a some of even earlier F00s but I think they're coincidences/false positives:

Capture the screen shot using .NET

It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap object and draw into that using the Graphics.CopyFromScreen method.

Sample code:

using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width, 
                                            Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
    g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                     Screen.PrimaryScreen.Bounds.Y,
                     0, 0,
                     bmpScreenCapture.Size,
                     CopyPixelOperation.SourceCopy);
}

Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.

HTML - Arabic Support

The W3C has a good introduction.

In short:

HTML is a text markup language. Text means any characters, not just ones in ASCII.

  1. Save your text using a character encoding that includes the characters you want (UTF-8 is a good bet). This will probably require configuring your editor in a way that is specific to the particular editor you are using. (Obviously it also requires that you have a way to input the characters you want)
  2. Make sure your server sends the correct character encoding in the headers (how you do this depends on the server software you us)
  3. If the document you serve over HTTP specifies its encoding internally, then make sure that is correct too
  4. If anything happens to the document between you saving it and it being served up (e.g. being put in a database, being munged by a server side script, etc) then make sure that the encoding isn't mucked about with on the way.

You can also represent any unicode character with ASCII

Matching an optional substring in a regex

You can do this:

([0-9]+) (\([^)]+\))? Z

This will not work with nested parens for Y, however. Nesting requires recursion which isn't strictly regular any more (but context-free). Modern regexp engines can still handle it, albeit with some difficulties (back-references).

How can I extract a good quality JPEG image from a video file with ffmpeg?

Output the images in a lossless format such as PNG:

ffmpeg.exe -i 10fps.h264 -r 10 -f image2 10fps.h264_%03d.png

Edit/Update: Not quite sure why I originally gave a strange filename example (with a possibly made-up extension).

I have since found that -vsync 0 is simpler than -r 10 because it avoids needing to know the frame rate.

This is something like what I currently use:

mkdir stills
ffmpeg -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png

To extract only the key frames (which are likely to be of higher quality post-edit):

ffmpeg -skip_frame nokey -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png

Then use another program (where you can more precisely specify quality, subsampling and DCT method – e.g. GIMP) to convert the PNGs you want to JPEG.

It is possible to obtain slightly sharper images in JPEG format this way than is possible with -qmin 1 -q:v 1 and outputting as JPEG directly from ffmpeg.

How to use Spring Boot with MySQL database and JPA?

For Jpa based application: base package scan @EnableJpaRepositories(basePackages = "repository") You can try it once!!!
Project Structure

com
 +- stack
     +- app
     |   +- Application.java
     +- controller
     |   +- EmployeeController.java
     +- service
     |   +- EmployeeService.java
     +- repository
     |   +- EmployeeRepository.java
     +- model
     |   +- Employee.java
-pom.xml
dependencies: 
    mysql, lombok, data-jpa

application.properties

#Data source :
spring.datasource.url=jdbc:mysql://localhost:3306/employee?useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.generate-ddl=true
spring.datasource.driverClassName=com.mysql.jdbc.Driver

#Jpa/Hibernate :
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto = update

Employee.java

@Entity
@Table (name = "employee")
@Getter
@Setter
public class Employee {

    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY)
    private Long id;

    @Column (name = "first_name")
    private String firstName;
    @Column (name = "last_name")
    private String lastName;
    @Column (name = "email")
    private String email;
    @Column (name = "phone_number")
    private String phoneNumber;
    @Column (name = "emp_desg")
    private String desgination;
}

EmployeeRepository.java

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}

EmployeeController.java

@RestController
public class EmployeeController {

    @Autowired
    private EmployeeService empService;

    @GetMapping (value = "/employees")
    public List<Employee> getAllEmployee(){
        return empService.getAllEmployees();
    }

    @PostMapping (value = "/employee")
    public ResponseEntity<Employee> addEmp(@RequestBody Employee emp, HttpServletRequest 
                                         request) throws URISyntaxException {
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(new URI(request.getRequestURI() + "/" + emp.getId()));
        empService.saveEmployee(emp);
        return new ResponseEntity<Employee>(emp, headers, HttpStatus.CREATED);
    }

EmployeeService.java

public interface EmployeeService {
    public List<Employee> getAllEmployees();
    public Employee saveEmployee(Employee emp);
}

EmployeeServiceImpl.java

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeRepository empRepository;

    @Override
    public List<Employee> getAllEmployees() {
        return empRepository.findAll();
    }

    @Override
    public Employee saveEmployee(Employee emp) {
        return empRepository.save(emp);
    }
}

EmployeeApplication.java

@SpringBootApplication
@EnableJpaRepositories(basePackages = "repository")
public class EmployeeApplication {
    public static void main(String[] args) {
        SpringApplication.run(EmployeeApplication.class, args);
    }
}

Using querySelectorAll to retrieve direct children

The following solution is different to the ones proposed so far, and works for me.

The rationale is that you select all matching children first, and then filter out the ones which are not direct children. A child is a direct child if it does not have a matching parent with the same selector.

function queryDirectChildren(parent, selector) {
    const nodes = parent.querySelectorAll(selector);
    const filteredNodes = [].slice.call(nodes).filter(n => 
        n.parentNode.closest(selector) === parent.closest(selector)
    );
    return filteredNodes;
}

HTH!

How do I scroll a row of a table into view (element.scrollintoView) using jQuery?

I found a case (overflow div > table > tr > td) in which scrolling to the relative position of the tr does not work. Instead, I had to scroll the overflow container (div) using scrollTop to <tr>.offset().top - <table>.offset().top. Eg:

$('#container').scrollTop( $('#tr').offset().top - $('#td').offset().top )

Access nested dictionary items via a list of keys?

How about using recursive functions?

To get a value:

def getFromDict(dataDict, maplist):
    first, rest = maplist[0], maplist[1:]

    if rest: 
        # if `rest` is not empty, run the function recursively
        return getFromDict(dataDict[first], rest)
    else:
        return dataDict[first]

And to set a value:

def setInDict(dataDict, maplist, value):
    first, rest = maplist[0], maplist[1:]

    if rest:
        try:
            if not isinstance(dataDict[first], dict):
                # if the key is not a dict, then make it a dict
                dataDict[first] = {}
        except KeyError:
            # if key doesn't exist, create one
            dataDict[first] = {}

        setInDict(dataDict[first], rest, value)
    else:
        dataDict[first] = value

"Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo." when using GCC

I had the same issue when I tried to use git.

It is possible to install git without it. And I doubt that gcc on mac is truly dependent on XCode. And I don't want to use root to accept something unless I'm sure I need it.

I uninstalled XCode by navigating to the applications folder and dragging XCode to the trash.

Now my git commands work as usual. I'll re-install XCode if/when I truly need it.

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

I had the same problem, and resolved it. In my case it was error due to the non-proper format. Please check the first and last coordinates array in geometry coordinates they must be same then and only then it will work. Hope it may help you!

Using Spring RestTemplate in generic method with generic parameter

No, it is not a bug. It is a result of how the ParameterizedTypeReference hack works.

If you look at its implementation, it uses Class#getGenericSuperclass() which states

Returns the Type representing the direct superclass of the entity (class, interface, primitive type or void) represented by this Class.

If the superclass is a parameterized type, the Type object returned must accurately reflect the actual type parameters used in the source code.

So, if you use

new ParameterizedTypeReference<ResponseWrapper<MyClass>>() {}

it will accurately return a Type for ResponseWrapper<MyClass>.

If you use

new ParameterizedTypeReference<ResponseWrapper<T>>() {}

it will accurately return a Type for ResponseWrapper<T> because that is how it appears in the source code.

When Spring sees T, which is actually a TypeVariable object, it doesn't know the type to use, so it uses its default.

You cannot use ParameterizedTypeReference the way you are proposing, making it generic in the sense of accepting any type. Consider writing a Map with key Class mapped to a predefined ParameterizedTypeReference for that class.

You can subclass ParameterizedTypeReference and override its getType method to return an appropriately created ParameterizedType, as suggested by IonSpin.

How do I speed up the gwt compiler?

In the newer versions of GWT (starting either 2.3 or 2.4, i believe), you can also add

<collapse-all-properties />

to your gwt.xml for development purposes. That will tell the GWT compiler to create a single permutation which covers all locales and browsers. Therefore, you can still test in all browsers and languages, but are still only compiling a single permutation

Socket.io + Node.js Cross-Origin Request Blocked

You can try to set origins option on the server side to allow cross-origin requests:

io.set('origins', 'http://yourdomain.com:80');

Here http://yourdomain.com:80 is the origin you want to allow requests from.

You can read more about origins format here

Android error: Failed to install *.apk on device *: timeout

Try changing the ADB connection timeout. I think it defaults that to 5000ms and I changed mine to 10000ms to get rid of that problem.

If you are in Eclipse, you can do this by going through

Window -> Preferences -> Android -> DDMS -> ADB Connection Timeout (ms)

How do I create a MessageBox in C#?

Also you can use a MessageBox with OKCancel options, but it requires many codes. The if block is for OK, the else block is for Cancel. Here is the code:

if (MessageBox.Show("Are you sure you want to do this?", "Question", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
    MessageBox.Show("You pressed OK!");
}
else
{
    MessageBox.Show("You pressed Cancel!");
}

You can also use a MessageBox with YesNo options:

if (MessageBox.Show("Are you sure want to doing this?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
    MessageBox.Show("You are pressed Yes!");
}
else
{
    MessageBox.Show("You are pressed No!");
}

jQuery form validation on button click

You can also achieve other way using button tag

According new html5 attribute you also can add a form attribute like

<form id="formId">
    <input type="text" name="fname">
</form>

<button id="myButton" form='#formId'>My Awesome Button</button>

So the button will be attached to the form.

This should work with the validate() plugin of jQuery like :

var validator = $( "#formId" ).validate();
validator.element( "#myButton" );

It's working too with input tag

Source :

https://developer.mozilla.org/docs/Web/HTML/Element/Button

Use of contains in Java ArrayList<String>

You are right that it should work; perhaps you forgot to instantiate something. Does your code look something like this?

String rssFeedURL = "http://stackoverflow.com";
this.rssFeedURLS = new ArrayList<String>();
this.rssFeedURLS.add(rssFeedURL);
if(this.rssFeedURLs.contains(rssFeedURL)) {
// this code will execute
}

For reference, note that the following conditional will also execute if you append this code to the above:

String copyURL = new String(rssFeedURL);
if(this.rssFeedURLs.contains(copyURL)) {
// code will still execute because contains() checks equals()
}

Even though (rssFeedURL == copyURL) is false, rssFeedURL.equals(copyURL) is true. The contains method cares about the equals method.

Why declare unicode by string in python?

That doesn't set the format of the string; it sets the format of the file. Even with that header, "hello" is a byte string, not a Unicode string. To make it Unicode, you're going to have to use u"hello" everywhere. The header is just a hint of what format to use when reading the .py file.

Converting Array to List

where stateb is List'' bucket is a two dimensional array

statesb= IntStream.of(bucket[j-1]).boxed().collect(Collectors.toList());

with import java.util.stream.IntStream;

see https://examples.javacodegeeks.com/core-java/java8-convert-array-list-example/

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

VBA subs are no macros. A VBA sub can be a macro, but it is not a must.

The term "macro" is only used for recorded user actions. from these actions a code is generated and stored in a sub. This code is simple and do not provide powerful structures like loops, for example Do .. until, for .. next, while.. do, and others.

The more elegant way is, to design and write your own VBA code without using the macro features!

VBA is a object based and event oriented language. Subs, or bette call it "sub routines", are started by dedicated events. The event can be the pressing of a button or the opening of a workbook and many many other very specific events.

If you focus to VB6 and not to VBA, then you can state, that there is always a main-window or main form. This form is started if you start the compiled executable "xxxx.exe".

In VBA you have nothing like this, but you have a XLSM file wich is started by Excel. You can attach some code to the Workbook_Open event. This event is generated, if you open your desired excel file which is called a workbook. Inside the workbook you have worksheets.

It is useful to get more familiar with the so called object model of excel. The workbook has several events and methods. Also the worksheet has several events and methods.

In the object based model you have objects, that have events and methods. methods are action you can do with a object. events are things that can happen to an object. An objects can contain another objects, and so on. You can create new objects, like sheets or charts.

No module named serial

You must have the pyserial library installed. You do not need the serial library.Therefore, if the serial library is pre-installed, uninstall it. Install the pyserial libray. There are many methods of installing:-

  1. pip install pyserial
  2. Download zip from pyserial and save extracted library in Lib>>site-packages folder of Python.
  3. Download wheel and install wheel using command: pip install <wheelname>

Link: https://github.com/pyserial/pyserial/releases

After installing Pyserial, Navigate to the location where pyserial is installed. You will see a "setup.py" file. Open Power Shell or CMD in the same directory and run command "python setup.py install". Now you can use all functionalities of pyserial library without any error.

Adding a 'share by email' link to website

Easiest: http://www.addthis.com/

Best? Well. probably not, But If you don't want to design something bespoke this is the best there is...

Merge unequal dataframes and replace missing rows with 0

"all" option does not work anymore, The new parameter is;

x = pd.merge(df1, df2, how="outer")

How to send json data in POST request using C#

This works for me.

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new 

StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
                {
                    Username = "myusername",
                    Password = "password"
                });

    streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

What is the best algorithm for overriding GetHashCode?

.NET Standard 2.1 And Above

If you are using .NET Standard 2.1 or above, you can use the System.HashCode struct. There are two methods of using it:

HashCode.Combine

The Combine method can be used to create a hash code, given up to eight objects.

public override int GetHashCode() => HashCode.Combine(this.object1, this.object2);

HashCode.Add

The Add method helps you to deal with collections:

public override int GetHashCode()
{
    var hashCode = new HashCode();
    hashCode.Add(this.object1);
    foreach (var item in this.collection)
    {
        hashCode.Add(item);
    }
    return hashCode.ToHashCode();
}

GetHashCode Made Easy

You can read the full blog post 'GetHashCode Made Easy' for more details and comments.

Usage Example

public class SuperHero
{
    public int Age { get; set; }
    public string Name { get; set; }
    public List<string> Powers { get; set; }

    public override int GetHashCode() =>
        HashCode.Of(this.Name).And(this.Age).AndEach(this.Powers);
}

Implementation

public struct HashCode : IEquatable<HashCode>
{
    private const int EmptyCollectionPrimeNumber = 19;
    private readonly int value;

    private HashCode(int value) => this.value = value;

    public static implicit operator int(HashCode hashCode) => hashCode.value;

    public static bool operator ==(HashCode left, HashCode right) => left.Equals(right);

    public static bool operator !=(HashCode left, HashCode right) => !(left == right);

    public static HashCode Of<T>(T item) => new HashCode(GetHashCode(item));

    public static HashCode OfEach<T>(IEnumerable<T> items) =>
        items == null ? new HashCode(0) : new HashCode(GetHashCode(items, 0));

    public HashCode And<T>(T item) => 
        new HashCode(CombineHashCodes(this.value, GetHashCode(item)));

    public HashCode AndEach<T>(IEnumerable<T> items)
    {
        if (items == null)
        {
            return new HashCode(this.value);
        }

        return new HashCode(GetHashCode(items, this.value));
    }

    public bool Equals(HashCode other) => this.value.Equals(other.value);

    public override bool Equals(object obj)
    {
        if (obj is HashCode)
        {
            return this.Equals((HashCode)obj);
        }

        return false;
    }

    public override int GetHashCode() => this.value.GetHashCode();

    private static int CombineHashCodes(int h1, int h2)
    {
        unchecked
        {
            // Code copied from System.Tuple a good way to combine hashes.
            return ((h1 << 5) + h1) ^ h2;
        }
    }

    private static int GetHashCode<T>(T item) => item?.GetHashCode() ?? 0;

    private static int GetHashCode<T>(IEnumerable<T> items, int startHashCode)
    {
        var temp = startHashCode;

        var enumerator = items.GetEnumerator();
        if (enumerator.MoveNext())
        {
            temp = CombineHashCodes(temp, GetHashCode(enumerator.Current));

            while (enumerator.MoveNext())
            {
                temp = CombineHashCodes(temp, GetHashCode(enumerator.Current));
            }
        }
        else
        {
            temp = CombineHashCodes(temp, EmptyCollectionPrimeNumber);
        }

        return temp;
    }
}

What Makes a Good Algorithm?

Performance

The algorithm that calculates a hash code needs to be fast. A simple algorithm is usually going to be a faster one. One that does not allocate extra memory will also reduce need for garbage collection, which will in turn also improve performance.

Deterministic

The hashing algorithm needs to be deterministic i.e. given the same input it must always produce the same output.

Reduce Collisions

The algorithm that calculates a hash code needs to keep hash collisions to a minumum. A hash collision is a situation that occurs when two calls to GetHashCode on two different objects produce identical hash codes. Note that collisions are allowed (some have the misconceptions that they are not) but they should be kept to a minimum.

A good hash function should map the expected inputs as evenly as possible over its output range. It should have uniformity.

Prevent's DoS

In .NET Core each time you restart an application you will get different hash codes. This is a security feature to prevent Denial of Service attacks (DoS). For .NET Framework you should enable this feature by adding the following App.config file:

<?xml version ="1.0"?>  
<configuration>  
   <runtime>  
      <UseRandomizedStringHashAlgorithm enabled="1" />  
   </runtime>  
</configuration>

Because of this feature, hash codes should never be used outside of the application domain in which they were created, they should never be used as key fields in a collection and they should never be persisted.

Read more about this here.

Cryptographically Secure?

The algorithm does not have to be a Cryptographic hash function. Meaning it does not have to satisfy the following conditions:

  • It is infeasible to generate a message that yields a given hash value
  • It is infeasible to find two different messages with the same hash value
  • A small change to a message should change the hash value so extensively that the new hash value appears uncorrelated with the old hash value (avalanche effect).

Difference between 2 dates in SQLite

This answer is a little long-winded, and the documentation will not tell you this (because they assume you are storing your dates as UTC dates in the database), but the answer to this question depends largely on the timezone that your dates are stored in. You also don't use Date('now'), but use the julianday() function, to calculate both dates back against a common date, then subtract the difference of those results from each other.

If your dates are stored in UTC:

SELECT julianday('now') - julianday(DateCreated) FROM Payment;

This is what the top-ranked answer has, and is also in the documentation. It is only part of the picture, and a very simplistic answer, if you ask me.

If your dates are stored in local time, using the above code will make your answer WRONG by the number of hours your GMT offset is. If you are in the Eastern U.S. like me, which is GMT -5, your result will have 5 hours added onto it. And if you try making DateCreated conform to UTC because julianday('now') goes against a GMT date:

SELECT julianday('now') - julianday(DateCreated, 'utc') FROM Payment;

This has a bug where it will add an hour for a DateCreated that is during Daylight Savings Time (March-November). Say that "now" is at noon on a non-DST day, and you created something back in June (during DST) at noon, your result will give 1 hour apart, instead of 0 hours, for the hours portion. You'd have to write a function in your application's code that is displaying the result to modify the result and subtract an hour from DST dates. I did that, until I realized there's a better solution to that problem that I was having: SQLite vs. Oracle - Calculating date differences - hours

Instead, as was pointed out to me, for dates stored in local time, make both match to local time:

SELECT julianday('now', 'localtime') - julianday(DateCreated) FROM Payment;

Or append 'Z' to local time:

julianday(datetime('now', 'localtime')||'Z') - julianday(CREATED_DATE||'Z')

Both of these seem to compensate and do not add the extra hour for DST dates and do straight subtraction - so that item created at noon on a DST day, when checking at noon on a non-DST day, will not get an extra hour when performing the calculation.

And while I recognize most will say don't store dates in local time in your database, and to store them in UTC so you don't run into this, well not every application has a world-wide audience, and not every programmer wants to go through the conversion of EVERY date in their system to UTC and back again every time they do a GET or SET in the database and deal with figuring out if something is local or in UTC.

How to deep copy a list?

If you are not allowed to directly import modules you can define your own deepcopy function as -

def copyList(L):
if type(L[0]) != list:
    return [i for i in L]
else:
    return [copyList(L[i]) for i in range(len(L))]

It's working can be seen easily as -

>>> x = [[1,2,3],[3,4]]
>>> z = copyList(x)
>>> x
[[1, 2, 3], [3, 4]]
>>> z
[[1, 2, 3], [3, 4]]
>>> id(x)
2095053718720
>>> id(z)
2095053718528
>>> id(x[0])
2095058990144
>>> id(z[0])
2095058992192
>>>

QByteArray to QString

You can use QTextCodec to convert the bytearray to a string:

QString DataAsString = QTextCodec::codecForMib(1015)->toUnicode(Data);

(1015 is UTF-16, 1014 UTF-16LE, 1013 UTF-16BE, 106 UTF-8)

From your example we can see that the string "test" is encoded as "t\0 e\0 s\0 t\0 \0 \0" in your encoding, i.e. every ascii character is followed by a \0-byte, or resp. every ascii character is encoded as 2 bytes. The only unicode encoding in which ascii letters are encoded in this way, are UTF-16 or UCS-2 (which is a restricted version of UTF-16), so in your case the 1015 mib is needed (assuming your local endianess is the same as the input endianess).

How do you divide each element in a list by an int?

The idiomatic way would be to use list comprehension:

myList = [10,20,30,40,50,60,70,80,90]
myInt = 10
newList = [x / myInt for x in myList]

or, if you need to maintain the reference to the original list:

myList[:] = [x / myInt for x in myList]

Winforms issue - Error creating window handle

I got same error in my application.I am loading many controls in single page.In button click event i am clearing the controls.clearing the controls doesnot release the controls from memory.So dispose the controls from memory. I just commented controls.clear() method and include few lines of code to dispose the controls. Something like this

for each ctl as control in controlcollection

ctl.dispose()

Next

How to determine when a Git branch was created?

First, if you branch was created within gc.reflogexpire days (default 90 days, i.e. around 3 months), you can use git log -g <branch> or git reflog show <branch> to find first entry in reflog, which would be creation event, and looks something like below (for git log -g):

Reflog: <branch>@{<nn>} (C R Eator <[email protected]>)
Reflog message: branch: Created from <some other branch>

You would get who created a branch, how many operations ago, and from which branch (well, it might be just "Created from HEAD", which doesn't help much).

That is what MikeSep said in his answer.


Second, if you have branch for longer than gc.reflogexpire and you have run git gc (or it was run automatically), you would have to find common ancestor with the branch it was created from. Take a look at config file, perhaps there is branch.<branchname>.merge entry, which would tell you what branch this one is based on.

If you know that the branch in question was created off master branch (forking from master branch), for example, you can use the following command to see common ancestor:

git show $(git merge-base <branch> master)

You can also try git show-branch <branch> master, as an alternative.

This is what gbacon said in his response.

How do I check if a directory exists? "is_dir", "file_exists" or both?

I had the same doubt, but see the PHP docu:

https://www.php.net/manual/en/function.file-exists.php

https://www.php.net/manual/en/function.is-dir.php

You will see that is_dir() has both properties.

Return Values is_dir Returns TRUE if the filename exists and is a directory, FALSE otherwise.

How to add one column into existing SQL Table

The syntax you need is

ALTER TABLE Products ADD LastUpdate  varchar(200) NULL

This is a metadata only operation

Where do I configure log4j in a JUnit test class?

You may want to look into to Simple Logging Facade for Java (SLF4J). It is a facade that wraps around Log4j that doesn't require an initial setup call like Log4j. It is also fairly easy to switch out Log4j for Slf4j as the API differences are minimal.

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

Try this solution

PUT THESE PERMISSIONS IN MANIFEST

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

INTENT TO CAPTURE IMAGE

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                    startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                }

GET CAPTURED IMAGE IN ONACTIVITYRESULT

@Override
            protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
                    Bundle extras = data.getExtras();
                    Bitmap imageBitmap = (Bitmap) extras.get("data");
                    // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
                    Uri tempUri = getImageUri(getApplicationContext(), imageBitmap);
                    //DO SOMETHING WITH URI
                }
            } 

METHOD TO GET IMAGE URI

public Uri getImageUri(Context inContext, Bitmap inImage) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
        return Uri.parse(path);
    }

Get selected value of a dropdown's item using jQuery

I know this is a terribly old post and I should probably be flogged for this pitiful resurrection, but I thought I would share a couple of VERY helpful little JS snippets that I use throughout every application in my arsenal...

If typing out:

$("#selector option:selected").val() // or
$("#selector option:selected").text()

is getting old, try adding these little crumpets to your global *.js file:

function soval(a) {
    return $('option:selected', a).val();
}
function sotext(a) {
    return $('option:selected', a).text();
}

and just write soval("#selector"); or sotext("#selector"); instead! Get even fancier by combining the two and returning an object containing both the value and the text!

function so(a) {
    my.value = $('option:selected', a).val();
    my.text  = $('option:selected', a).text();
    return my;
}

It saves me a ton of precious time, especially on form-heavy applications!

Passing properties by reference in C#

If you want to get and set the property both, you can use this in C#7:

GetString(
    inputString,
    (() => client.WorkPhone, x => client.WorkPhone = x))

void GetString(string inValue, (Func<string> get, Action<string> set) outValue)
{
    if (!string.IsNullOrEmpty(outValue))
    {
        outValue.set(inValue);
    }
}

How to remove all debug logging calls before building the release version of an Android app?

All good answers, but when I was finished with my development I didn´t want to either use if statements around all the Log calls, nor did I want to use external tools.

So the solution I`m using is to replace the android.util.Log class with my own Log class:

public class Log {
    static final boolean LOG = BuildConfig.DEBUG;

    public static void i(String tag, String string) {
        if (LOG) android.util.Log.i(tag, string);
    }
    public static void e(String tag, String string) {
        if (LOG) android.util.Log.e(tag, string);
    }
    public static void d(String tag, String string) {
        if (LOG) android.util.Log.d(tag, string);
    }
    public static void v(String tag, String string) {
        if (LOG) android.util.Log.v(tag, string);
    }
    public static void w(String tag, String string) {
        if (LOG) android.util.Log.w(tag, string);
    }
}

The only thing I had to do in all the source files was to replace the import of android.util.Log with my own class.

How to print matched regex pattern using awk?

This is the very basic

awk '/pattern/{ print $0 }' file

ask awk to search for pattern using //, then print out the line, which by default is called a record, denoted by $0. At least read up the documentation.

If you only want to get print out the matched word.

awk '{for(i=1;i<=NF;i++){ if($i=="yyy"){print $i} } }' file

Can we pass model as a parameter in RedirectToAction?

i did find something like this, helps get rid of hardcoded tempdata tags

public class AccountController : Controller
{
    [HttpGet]
    public ActionResult Index(IndexPresentationModel model)
    {
        return View(model);
    }

    [HttpPost]
    public ActionResult Save(SaveUpdateModel model)
    {
        // save the information

        var presentationModel = new IndexPresentationModel();

        presentationModel.Message = model.Message;

        return this.RedirectToAction(c => c.Index(presentationModel));
    }
}

html <input type="text" /> onchange event not working

Use .on('input'... to monitor every change to an input (paste, keyup, etc) from jQuery 1.7 and above.

For static and dynamic inputs:

$(document).on('input', '.my-class', function(){
    alert('Input changed');
});

For static inputs only:

$('.my-class').on('input', function(){
    alert('Input changed');
});

JSFiddle with static/dynamic example: https://jsfiddle.net/op0zqrgy/7/

Dropdownlist validation in Asp.net Using Required field validator

Here use asp:CompareValidator, and compare the value to "select" option.

Use Operator="NotEqual" ValueToCompare="0" to prevent the user from submitting the "select".

<asp:CompareValidator ControlToValidate="ddlReportType" ID="CompareValidator1"
    ValidationGroup="g1" CssClass="errormesg" ErrorMessage="Please select a type"
    runat="server" Display="Dynamic" 
    Operator="NotEqual" ValueToCompare="0" Type="Integer" />

When you do above, if you select the "select " option from dropdown it will show the ErrorMessage.

SQL MAX of multiple columns?

If you're using MySQL, you can use

SELECT GREATEST(col1, col2 ...) FROM table

Redirecting a page using Javascript, like PHP's Header->Location

The PHP code is executed on the server, so your redirect is executed before the browser even sees the JavaScript.

You need to do the redirect in JavaScript too

$('.entry a:first').click(function()
{
    window.location.replace("http://www.google.com");
});

Apk location in New Android Studio

Location of apk in Android Studio:

AndroidStudioProjects/ProjectName/app/build/outputs/apk/app-debug-unaligned.apk

Vim multiline editing like in sublimetext?

Do yourself a favor by dropping the Windows compatibility layer.

The normal shortcut for entering Visual-Block mode is <C-v>.

Others have dealt with recording macros, here are a few other ideas:

Using only visual-block mode.

  1. Put the cursor on the second word:

    asd |a|sd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    
  2. Hit <C-v> to enter visual-block mode and expand your selection toward the bottom:

    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    
  3. Hit I"<Esc> to obtain:

    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    
  4. Put the cursor on the last char of the third word:

    asd "asd as|d| asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    
  5. Hit <C-v> to enter visual-block mode and expand your selection toward the bottom:

    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    
  6. Hit A"<Esc> to obtain:

    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    

With visual-block mode and Surround.vim.

  1. Put the cursor on the second word:

    asd |a|sd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    
  2. Hit <C-v> to enter visual-block mode and expand your selection toward the bottom and the right:

    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    
  3. Hit S" to surround your selection with ":

    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    

With visual-line mode and :normal.

  1. Hit V to select the whole line and expand it toward the bottom:

    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    
  2. Execute this command: :'<,'>norm ^wi"<C-v><Esc>eea"<CR> to obtain:

    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    
    • :norm[al] allows you to execute normal mode commands on a range of lines (the '<,'> part is added automatically by Vim and means "act on the selected area")

    • ^ puts the cursor on the first char of the line

    • w moves to the next word

    • i" inserts a " before the cursor

    • <C-v><Esc> is Vim's way to input a control character in this context, here it's <Esc> used to exit insert mode

    • ee moves to the end of the next word

    • a" appends a " after the cursor

    • <CR> executes the command

    Using Surround.vim, the command above becomes

    :'<,'>norm ^wvees"<CR>
    

How can I call a method in Objective-C?

[self score]; instead of @selector(score)

How to printf long long

First of all, %d is for a int

So %1.16lld makes no sense, because %d is an integer

That typedef you do, is also unnecessary, use the type straight ahead, makes a much more readable code.

What you want to use is the type double, for calculating pi and then using %f or %1.16f.

Comparing arrays for equality in C++

Right. In most, if not all implementations of C, the array identifier can be implicitly casted to a pointer to the first element (i.e. the first element's address). What you're doing here is comparing those addresses, which is obviously wrong.

Instead, you need to iterate over both arrays, checking each element against each other. If you get to the end of both without a failure, they're equal.

exporting multiple modules in react.js

When you

import App from './App.jsx';

That means it will import whatever you export default. You can rename App class inside App.jsx to whatever you want as long as you export default it will work but you can only have one export default.

So you only need to export default App and you don't need to export the rest.

If you still want to export the rest of the components, you will need named export.

https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export

How to add jQuery code into HTML Page

  1. Create a file for the jquery eg uploadfuntion.js.
  2. Save that file in the same folder as website or in subfolder.
  3. In head section of your html page paste: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

and then the reference to your script eg: <script src="uploadfuntion.js"> </script>

4.Lastly you should ensure there are elements that match the selectors in the code.

How do you make Git work with IntelliJ?

Literally, just restarted IntelliJ after it kept showing this "install git" message after I have pressed and installed git, and it disappeared, and git works

jQuery AJAX submit form

To avoid multiple formdata sends:

Don't forget to unbind submit event, before the form submited again, User can call sumbit function more than one time, maybe he forgot something, or was a validation error.

 $("#idForm").unbind().submit( function(e) {
  ....

How to grey out a button?

The most easy solution is to set color filter to the background image of a button as I saw here

You can do as follow:

if ('need to set button disable')
    button.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
else
    button.getBackground().setColorFilter(null);

Hope I helped someone...

How to randomize (or permute) a dataframe rowwise and columnwise?

Take a look at permatswap() in the vegan package. Here is an example maintaining both row and column totals, but you can relax that and fix only one of the row or column sums.

mat <- matrix(c(1,1,0,0,0,0,0,1,1,0,0,0,1,1,1,0,1,0,1,1), ncol = 5)
set.seed(4)
out <- permatswap(mat, times = 99, burnin = 20000, thin = 500, mtype = "prab")

This gives:

R> out$perm[[1]]
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    0    1    1    1
[2,]    0    1    0    1    0
[3,]    0    0    0    1    1
[4,]    1    0    0    0    1
R> out$perm[[2]]
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    0    1    1
[2,]    0    0    0    1    1
[3,]    1    0    0    1    0
[4,]    0    0    1    0    1

To explain the call:

out <- permatswap(mat, times = 99, burnin = 20000, thin = 500, mtype = "prab")
  1. times is the number of randomised matrices you want, here 99
  2. burnin is the number of swaps made before we start taking random samples. This allows the matrix from which we sample to be quite random before we start taking each of our randomised matrices
  3. thin says only take a random draw every thin swaps
  4. mtype = "prab" says treat the matrix as presence/absence, i.e. binary 0/1 data.

A couple of things to note, this doesn't guarantee that any column or row has been randomised, but if burnin is long enough there should be a good chance of that having happened. Also, you could draw more random matrices than you need and discard ones that don't match all your requirements.

Your requirement to have different numbers of changes per row, also isn't covered here. Again you could sample more matrices than you want and then discard the ones that don't meet this requirement also.

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

Sometimes, it can be caused by wrong naming for xml or resource file.

At least, for me, that problem was solved by changing name .

How to install npm peer dependencies automatically?

Install yarn an then run

yarn global add install-peerdeps

Clicking the back button twice to exit an activity

There is very simplest way among all these answers.

Simply write following code inside onBackPressed() method.

long back_pressed;

@Override
public void onBackPressed() {
    if (back_pressed + 1000 > System.currentTimeMillis()){
        super.onBackPressed();
    }
    else{
        Toast.makeText(getBaseContext(),
                "Press once again to exit!", Toast.LENGTH_SHORT)
                .show();
    }
    back_pressed = System.currentTimeMillis();
}

You need to define back_pressed object as long in activity.

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

First set delegate in viewDidLoad:

self.navigationController.interactivePopGestureRecognizer.delegate = self;

And then disable gesture when pushing:

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    [super pushViewController:viewController animated:animated];
    self.interactivePopGestureRecognizer.enabled = NO;
}

And enable in viewDidDisappear:

self.navigationController.interactivePopGestureRecognizer.enabled = YES;

Also, add UINavigationControllerDelegate to your view controller.

Use a.empty, a.bool(), a.item(), a.any() or a.all()

solution is easy:

replace

 mask = (50  < df['heart rate'] < 101 &
            140 < df['systolic blood pressure'] < 160 &
            90  < df['dyastolic blood pressure'] < 100 &
            35  < df['temperature'] < 39 &
            11  < df['respiratory rate'] < 19 &
            95  < df['pulse oximetry'] < 100
            , "excellent", "critical")

by

mask = ((50  < df['heart rate'] < 101) &
        (140 < df['systolic blood pressure'] < 160) &
        (90  < df['dyastolic blood pressure'] < 100) &
        (35  < df['temperature'] < 39) &
        (11  < df['respiratory rate'] < 19) &
        (95  < df['pulse oximetry'] < 100)
        , "excellent", "critical")

How to auto-size an iFrame?

I found the solution by @ShripadK most helpful, but it does not work, if there is more than one iframe. My fix is:

function autoResizeIFrame() {
  $('iframe').height(
    function() {
      return $(this).contents().find('body').height() + 20;
    }
  )
}

$('iframe').contents().find('body').css(
  {"min-height": "100", "overflow" : "hidden"});

setTimeout(autoResizeIFrame, 2000);
setTimeout(autoResizeIFrame, 10000);
  • $('iframe').height($('iframe').contents().find('body').height() + 20) would set the height of every frame to the same value, namely the height of the content of the first frame. So I am using jquery's height() with a function instead of a value. That way the individual heights are calculated
  • + 20 is a hack to work around iframe scrollbar problems. The number must be bigger than the size of a scrollbar. The hack can probably be avoided but disabling the scrollbars for the iframe.
  • I use setTimeout instead of setInterval(..., 1) to reduce CPU load in my case

How to export all collections in MongoDB?

Follow the steps below to create a mongodump from the server and import it another server/local machine which has a username and a password

1. mongodump -d dbname -o dumpname -u username -p password
2. scp -r user@remote:~/location/of/dumpname ./
3. mongorestore -d dbname dumpname/dbname/ -u username -p password

MSSQL Regular expression

As above the question was originally about MySQL

Use REGEXP, not LIKE:

SELECT * FROM `table` WHERE ([url] NOT REGEXP '^[-A-Za-z0-9/.]+$')

"unexpected token import" in Nodejs5 and babel?

  1. Install packages: babel-core, babel-polyfill, babel-preset-es2015
  2. Create .babelrc with contents: { "presets": ["es2015"] }
  3. Do not put import statement in your main entry file, use another file eg: app.js and your main entry file should required babel-core/register and babel-polyfill to make babel works separately at the first place before anything else. Then you can require app.js where import statement.

Example:

index.js

require('babel-core/register');
require('babel-polyfill');
require('./app');

app.js

import co from 'co';

It should works with node index.js.

What does %~dp0 mean, and how does it work?

Great example from Strawberry Perl's portable shell launcher:

set drive=%~dp0
set drivep=%drive%
if #%drive:~-1%# == #\# set drivep=%drive:~0,-1%

set PATH=%drivep%\perl\site\bin;%drivep%\perl\bin;%drivep%\c\bin;%PATH%

not sure what the negative 1's doing there myself, but it works a treat!

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

You can do this with CSS:

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

We're using max-width, because we want to make an exception to the CSS, when a screen is smaller than the 1026px. min-width would make the CSS rule count for all screens of 1026px width and larger.

Something to keep in mind is that @media queries are not supported on IE8 and lower.

jQuery DIV click, with anchors

If you return "false" from your function it'll stop the event bubbling, so only your first event handler will get triggered (ie. your anchor will not see the click).

$("div.clickable").click(
function()
{
    window.location = $(this).attr("url");
    return false;
});

See event.preventDefault() vs. return false for details on return false vs. preventDefault.

What is __init__.py for?

It facilitates importing other python files. When you placed this file in a directory (say stuff)containing other py files, then you can do something like import stuff.other.

root\
    stuff\
         other.py

    morestuff\
         another.py

Without this __init__.py inside the directory stuff, you couldn't import other.py, because Python doesn't know where the source code for stuff is and unable to recognize it as a package.

Null vs. False vs. 0 in PHP

Somebody can explain to me why 'NULL' is not just a string in a comparison instance?

$x = 0;
var_dump($x == 'NULL');  # TRUE   !!!WTF!!!

How can I have same rule for two locations in NGINX config?

Both the regex and included files are good methods, and I frequently use those. But another alternative is to use a "named location", which is a useful approach in many situations — especially more complicated ones. The official "If is Evil" page shows essentially the following as a good way to do things:

error_page 418 = @common_location;
location /first/location/ {
    return 418;
}
location /second/location/ {
    return 418;
}
location @common_location {
    # The common configuration...
}

There are advantages and disadvantages to these various approaches. One big advantage to a regex is that you can capture parts of the match and use them to modify the response. Of course, you can usually achieve similar results with the other approaches by either setting a variable in the original block or using map. The downside of the regex approach is that it can get unwieldy if you want to match a variety of locations, plus the low precedence of a regex might just not fit with how you want to match locations — not to mention that there are apparently performance impacts from regexes in some cases.

The main advantage of including files (as far as I can tell) is that it is a little more flexible about exactly what you can include — it doesn't have to be a full location block, for example. But it's also just subjectively a bit clunkier than named locations.

Also note that there is a related solution that you may be able to use in similar situations: nested locations. The idea is that you would start with a very general location, apply some configuration common to several of the possible matches, and then have separate nested locations for the different types of paths that you want to match. For example, it might be useful to do something like this:

location /specialpages/ {
    # some config
    location /specialpages/static/ {
        try_files $uri $uri/ =404;
    }
    location /specialpages/dynamic/ {
        proxy_pass http://127.0.0.1;
    }
}

How to extract text from a PDF?

Since today I know it: the best thing for text extraction from PDFs is TET, the text extraction toolkit. TET is part of the PDFlib.com family of products.

PDFlib.com is Thomas Merz's company. In case you don't recognize his name: Thomas Merz is the author of the "PostScript and PDF Bible".

TET's first incarnation is a library. That one can probably do everything Budda006 wanted, including positional information about every element on the page. Oh, and it can also extract images. It recombines images which are fragmented into pieces.

pdflib.com also offers another incarnation of this technology, the TET plugin for Acrobat. And the third incarnation is the PDFlib TET iFilter. This is a standalone tool for user desktops. Both these are free (as in beer) to use for private, non-commercial purposes.

And it's really powerful. Way better than Adobe's own text extraction. It extracted text for me where other tools (including Adobe's) do spit out garbage only.

I just tested the desktop standalone tool, and what they say on their webpage is true. It has a very good commandline. Some of my "problematic" PDF test files the tool handled to my full satisfaction.

This thing will from now on be my recommendation for every sophisticated and challenging PDF text extraction requirements.

TET is simply awesome. It detects tables. Inside tables, it identifies cells spanning multiple columns. It identifies table rows and contents of each table cell separately. It deals very well with hyphenations: it removes hyphens and restores complete words. It supports non-ASCII languages (including CJK, Arabic and Hebrew). When encountering ligatures, it restores the original characters...

Give it a try.

How do I fix "Expected to return a value at the end of arrow function" warning?

A map() creates an array, so a return is expected for all code paths (if/elses).

If you don't want an array or to return data, use forEach instead.

R Apply() function on specific dataframe columns

Using an example data.frame and example function (just +1 to all values)

A <- function(x) x + 1
wifi <- data.frame(replicate(9,1:4))
wifi

#  X1 X2 X3 X4 X5 X6 X7 X8 X9
#1  1  1  1  1  1  1  1  1  1
#2  2  2  2  2  2  2  2  2  2
#3  3  3  3  3  3  3  3  3  3
#4  4  4  4  4  4  4  4  4  4

data.frame(wifi[1:3], apply(wifi[4:9],2, A) )
#or
cbind(wifi[1:3], apply(wifi[4:9],2, A) )

#  X1 X2 X3 X4 X5 X6 X7 X8 X9
#1  1  1  1  2  2  2  2  2  2
#2  2  2  2  3  3  3  3  3  3
#3  3  3  3  4  4  4  4  4  4
#4  4  4  4  5  5  5  5  5  5

Or even:

data.frame(wifi[1:3], lapply(wifi[4:9], A) )
#or
cbind(wifi[1:3], lapply(wifi[4:9], A) )

#  X1 X2 X3 X4 X5 X6 X7 X8 X9
#1  1  1  1  2  2  2  2  2  2
#2  2  2  2  3  3  3  3  3  3
#3  3  3  3  4  4  4  4  4  4
#4  4  4  4  5  5  5  5  5  5

How to process each output line in a loop?

For those looking for a one-liner:

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

Prevent textbox autofill with previously entered values

Adding autocomplete="new-password" to the password field did the trick. Removed auto filling of both user name and password fields in Chrome.

<input type="password" name="whatever" autocomplete="new-password" />

"application blocked by security settings" prevent applets running using oracle SE 7 update 51 on firefox on Linux mint

You can also use Edit Site List and make it be an exception so that you can run it from the specific website.

Python: Ignore 'Incorrect padding' error when base64 decoding

Adding the padding is rather... fiddly. Here's the function I wrote with the help of the comments in this thread as well as the wiki page for base64 (it's surprisingly helpful) https://en.wikipedia.org/wiki/Base64#Padding.

import logging
import base64
def base64_decode(s):
    """Add missing padding to string and return the decoded base64 string."""
    log = logging.getLogger()
    s = str(s).strip()
    try:
        return base64.b64decode(s)
    except TypeError:
        padding = len(s) % 4
        if padding == 1:
            log.error("Invalid base64 string: {}".format(s))
            return ''
        elif padding == 2:
            s += b'=='
        elif padding == 3:
            s += b'='
        return base64.b64decode(s)

Windows git "warning: LF will be replaced by CRLF", is that warning tail backward?

git config --global core.autocrlf false works well for global settings.

But if you are using Visual Studio, might also need to modify .gitattributes for some type of projects (e.g c# class library application):

  • remove line * text=auto

Check for column name in a SqlDataReader object

The following is simple and worked for me:

 bool hasMyColumn = (reader.GetSchemaTable().Select("ColumnName = 'MyColumnName'").Count() == 1);

"Could not find a version that satisfies the requirement opencv-python"

As there is no proper wheel file in http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv?

Try this:(Worked in Anaconda Prompt or Pycharm)

pip install opencv-contrib-python

pip install opencv-python

"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3

Typical error on Windows because the default user directory is C:\user\<your_user>, so when you want to use this path as an string parameter into a Python function, you get a Unicode error, just because the \u is a Unicode escape. Any character not numeric after this produces an error.

To solve it, just double the backslashes: C:\\user\\<\your_user>...

Sending email in .NET through Gmail

This is to send email with attachement.. Simple and short..

source: http://coding-issues.blogspot.in/2012/11/sending-email-with-attachments-from-c.html

using System.Net;
using System.Net.Mail;

public void email_send()
{
    MailMessage mail = new MailMessage();
    SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
    mail.From = new MailAddress("your [email protected]");
    mail.To.Add("[email protected]");
    mail.Subject = "Test Mail - 1";
    mail.Body = "mail with attachment";

    System.Net.Mail.Attachment attachment;
    attachment = new System.Net.Mail.Attachment("c:/textfile.txt");
    mail.Attachments.Add(attachment);

    SmtpServer.Port = 587;
    SmtpServer.Credentials = new System.Net.NetworkCredential("your [email protected]", "your password");
    SmtpServer.EnableSsl = true;

    SmtpServer.Send(mail);

}

mysql_config not found when installing mysqldb python interface

I had this issues and solved if by adding a symlink to mysql_config.

I had installed mysql with homebrew and saw this in the output.

Error: The `brew link` step did not complete successfully

Depending on how you got mysql it will be in different places. In my case /usr/local/Cellar/mysql
Once you know where it is you should be able to ma a symbolic link to where python is looking for it. /usr/local/mysql

This worked for me.

ln -s /usr/local/Cellar/mysql/<< VERSION >>/bin/mysql_config   /usr/local/mysql/bin/mysql_config

How to check if a variable is both null and /or undefined in JavaScript

A variable cannot be both null and undefined at the same time. However, the direct answer to your question is:

if (variable != null)

One =, not two.

There are two special clauses in the "abstract equality comparison algorithm" in the JavaScript spec devoted to the case of one operand being null and the other being undefined, and the result is true for == and false for !=. Thus if the value of the variable is undefined, it's not != null, and if it's not null, it's obviously not != null.

Now, the case of an identifier not being defined at all, either as a var or let, as a function parameter, or as a property of the global context is different. A reference to such an identifier is treated as an error at runtime. You could attempt a reference and catch the error:

var isDefined = false;
try {
  (variable);
  isDefined = true;
}
catch (x) {}

I would personally consider that a questionable practice however. For global symbols that may or may be there based on the presence or absence of some other library, or some similar situation, you can test for a window property (in browser JavaScript):

var isJqueryAvailable = window.jQuery != null;

or

var isJqueryAvailable = "jQuery" in window;

How do I add a reference to the MySQL connector for .NET?

This is an older question, but I found it yesterday while struggling with getting the MySQL Connector reference working properly on examples I'd found on the web. I'm working with VS 2010 on Win7 64 bit but have to work with .NET 3.5.

As others have stated, you need to download the .Net & Mono versions (I don't know why this is true, but it's what I've found works). The link to the connectors is given above in the earlier answers.

  • Extract the connectors somewhere convenient.
  • Open the project in Visual Studio, then on the menu bar navigate to Solution Explorer (View > Solution Explorer), and choose Properties (first box on the far left of the toolbar. The Solution Explorer shows up in the top right pane for me, but YMMV).
  • In Properties, select References & locate the instance for mysql.data. It's likely to have a yellow bang on it (Yellow triangle with exclamation point in it). Remove it.
  • Then on the menu bar, navigate to Project > Add Reference... > Browse > point to where you downloaded the connectors. I have only been able to get the V2 version to work, but that may be a factor of my platform, not sure.
  • Clean & build your application. You should now be able to use the MySQL connectors to talk to your database.
  • You can also now downgrade your .NET instance if you need to (we're constrained to .NET 3.5, but mysql.data.dll wants 4.0 at the time of my writing this). On the menu bar, navigate to the properties of your project (Project > Properties). Choose the Application tab > Target framework > Choose which .NET framework you want to use. You have to build the application at least once before you can change the .NET framework. Once you built once the connector will no longer complain about the lower version of .NET.

filters on ng-model in an input

If you are doing complex, async input validation it might be worth it to abstract ng-model up one level as part of a custom class with its own validation methods.

https://plnkr.co/edit/gUnUjs0qHQwkq2vPZlpO?p=preview

html

<div>

  <label for="a">input a</label>
  <input 
    ng-class="{'is-valid': vm.store.a.isValid == true, 'is-invalid': vm.store.a.isValid == false}"
    ng-keyup="vm.store.a.validate(['isEmpty'])"
    ng-model="vm.store.a.model"
    placeholder="{{vm.store.a.isValid === false ? vm.store.a.warning : ''}}"
    id="a" />

  <label for="b">input b</label>
  <input 
    ng-class="{'is-valid': vm.store.b.isValid == true, 'is-invalid': vm.store.b.isValid == false}"
    ng-keyup="vm.store.b.validate(['isEmpty'])"
    ng-model="vm.store.b.model"
    placeholder="{{vm.store.b.isValid === false ? vm.store.b.warning : ''}}"
    id="b" />

</div>

code

(function() {

  const _ = window._;

  angular
    .module('app', [])
    .directive('componentLayout', layout)
    .controller('Layout', ['Validator', Layout])
    .factory('Validator', function() { return Validator; });

  /** Layout controller */

  function Layout(Validator) {
    this.store = {
      a: new Validator({title: 'input a'}),
      b: new Validator({title: 'input b'})
    };
  }

  /** layout directive */

  function layout() {
    return {
      restrict: 'EA',
      templateUrl: 'layout.html',
      controller: 'Layout',
      controllerAs: 'vm',
      bindToController: true
    };
  }

  /** Validator factory */  

  function Validator(config) {
    this.model = null;
    this.isValid = null;
    this.title = config.title;
  }

  Validator.prototype.isEmpty = function(checkName) {
    return new Promise((resolve, reject) => {
      if (/^\s+$/.test(this.model) || this.model.length === 0) {
        this.isValid = false;
        this.warning = `${this.title} cannot be empty`;
        reject(_.merge(this, {test: checkName}));
      }
      else {
        this.isValid = true;
        resolve(_.merge(this, {test: checkName}));
      }
    });
  };

  /**
   * @memberof Validator
   * @param {array} checks - array of strings, must match defined Validator class methods
   */

  Validator.prototype.validate = function(checks) {
    Promise
      .all(checks.map(check => this[check](check)))
      .then(res => { console.log('pass', res)  })
      .catch(e => { console.log('fail', e) })
  };

})();

How to cast DATETIME as a DATE in mysql?

Use DATE() function:

select * from follow_queue group by DATE(follow_date)

What's your favorite "programmer" cartoon?

This has made my year.

Some engineer out there has solved P=NP and it's locked up in an electric eggbeater calibration routine.  For every 0x5f375a86 we learn about, there are thousands we never see.

Some engineer out there has solved P=NP and it's locked up in an electric eggbeater calibration routine. For every 0x5f375a86 we learn about, there are thousands we never see.

Convert base64 string to ArrayBuffer

Just found base64-arraybuffer, a small npm package with incredibly high usage, 5M downloads last month (2017-08).

https://www.npmjs.com/package/base64-arraybuffer

For anyone looking for something of a best standard solution, this may be it.

size of NumPy array

Yes numpy has a size function, and shape and size are not quite the same.

Input

import numpy as np
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
arrData = np.array(data)

print(data)
print(arrData.size)
print(arrData.shape)

Output

[[1, 2, 3, 4], [5, 6, 7, 8]]

8 # size

(2, 4) # shape

Play a Sound with Python

Definitely use Pyglet for this. It's kind of a large package, but it is pure python with no extension modules. That will definitely be the easiest for deployment. It's also got great format and codec support.

import pyglet

music = pyglet.resource.media('music.mp3')
music.play()

pyglet.app.run()

Algorithm to find Largest prime factor of a number

JavaScript code:

'option strict';

function largestPrimeFactor(val, divisor = 2) { 
    let square = (val) => Math.pow(val, 2);

    while ((val % divisor) != 0 && square(divisor) <= val) {
        divisor++;
    }

    return square(divisor) <= val
        ? largestPrimeFactor(val / divisor, divisor)
        : val;
}

Usage Example:

let result = largestPrimeFactor(600851475143);

Here is an example of the code:

Populating a dictionary using for loops (python)

dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
        dicts[i] = values[i]
print(dicts)

alternatively

In [7]: dict(list(enumerate(values)))
Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}

CSS Selector that applies to elements with two classes

Chain both class selectors (without a space in between):

.foo.bar {
    /* Styles for element(s) with foo AND bar classes */
}

If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar in this case) instead, regardless of what other classes you list.

To illustrate how other browsers and IE6 interpret this, consider this CSS:

* {
    color: black;
}

.foo.bar {
    color: red;
}

Output on supported browsers is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Not selected, black text [3] -->

Output on IE6 is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Selected, red text [2] -->

Footnotes:

  • Supported browsers:
    1. Not selected as this element only has class foo.
    2. Selected as this element has both classes foo and bar.
    3. Not selected as this element only has class bar.

  • IE6:
    1. Not selected as this element doesn't have class bar.
    2. Selected as this element has class bar, regardless of any other classes listed.

How do I print bytes as hexadecimal?

If you want to use C++ streams rather than C functions, you can do the following:

int ar[] = { 20, 30, 40, 50, 60, 70, 80, 90 };
const int siz_ar = sizeof(ar) / sizeof(int);

for (int i = 0; i < siz_ar; ++i)
    cout << ar[i] << " ";
cout << endl;

for (int i = 0; i < siz_ar; ++i)
    cout << hex << setfill('0') << setw(2) << ar[i] << " ";
cout << endl;

Very simple.

Output:

20 30 40 50 60 70 80 90
14 1e 28 32 3c 46 50 5a 

Angular2 equivalent of $document.ready()

In order to use jQuery inside Angular only declare the $ as following: declare var $: any;

Change the Textbox height?

Try the following :)

        textBox1.Multiline = true;
        textBox1.Height = 100;
        textBox1.Width = 173;

How to install latest version of openssl Mac OS X El Capitan

To replace the old version with the new one, you need to change the link for it. Type that command to terminal.

brew link --force openssl

Check the version of openssl again. It should be changed.

Resize to fit image in div, and center horizontally and vertically

Only tested in Chrome 44.

Example: http://codepen.io/hugovk/pen/OVqBoq

HTML:

<div>
<img src="http://lorempixel.com/1600/900/">
</div>

CSS:

<style type="text/css">
img {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    max-width: 100%;
    max-height: 100%;
}
</style>

How to connect to a remote Git repository?

Like you said remote_repo_url is indeed the IP of the server, and yes it needs to be added on each PC, but it's easier to understand if you create the server first then ask each to clone it.

There's several ways to connect to the server, you can use ssh, http, or even a network drive, each has it's pros and cons. You can refer to the documentation about protocols and how to connect to the server

You can check the rest of chapter 4 for more detailed information, as it's talking about how to set up your own server

How to find what code is run by a button or element in Chrome using Developer Tools

This solution needs the jQuery's data method.

  1. Open Chrome's console (although any browser with jQuery loaded will work)
  2. Run $._data($(".example").get(0), "events")
  3. Drill down the output to find the desired event handler.
  4. Right-click on "handler" and select "Show function definition"
  5. The code will be shown in the Sources tab

$._data() is just accessing jQuery's data method. A more readable alternative could be jQuery._data().

Interesting point by this SO answer:

As of jQuery 1.8, the event data is no longer available from the "public API" for data. Read this jQuery blog post. You should now use this instead:

jQuery._data( elem, "events" ); elem should be an HTML Element, not a jQuery object, or selector.

Please note, that this is an internal, 'private' structure, and shouldn't be modified. Use this for debugging purposes only.

In older versions of jQuery, you might have to use the old method which is:

jQuery( elem ).data( "events" );

A version agnostic jQuery would be: (jQuery._data || jQuery.data)(elem, 'events');

Exporting PDF with jspdf not rendering CSS

jspdf does not work with css but it can work along with html2canvas. You can use jspdf along with html2canvas.

include these two files in script on your page :

<script type="text/javascript" src="html2canvas.js"></script>
  <script type="text/javascript" src="jspdf.min.js"></script>
  <script type="text/javascript">
  function genPDF()
  {
   html2canvas(document.body,{
   onrendered:function(canvas){

   var img=canvas.toDataURL("image/png");
   var doc = new jsPDF();
   doc.addImage(img,'JPEG',20,20);
   doc.save('test.pdf');
   }

   });

  }
  </script>

You need to download script files such as https://github.com/niklasvh/html2canvas/releases https://cdnjs.com/libraries/jspdf

make clickable button on page so that it will generate pdf and it will be seen same as that of original html page.

<a href="javascript:genPDF()">Download PDF</a>  

It will work perfectly.

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

This can also occur when using the wrong import (for example when using autoimport). let's take the MatTimePickerModule as an example. This will give an error message that is similar to the one described in the question:

import { NgxMatTimepickerModule } from '@angular-material-components/datetime-picker/lib/timepicker.module';

This should instead be

import { NgxMatTimepickerModule } from '@angular-material-components/datetime-picker';

"Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP

The problem is that PhpMyAdmin control user (usually: pma) password does not match the mysql user: pma (same user) password.

To fix it, 1. Set the password you want for user pma here:

"C:\xampp\phpMyAdmin\config.inc.php"

$cfg['Servers'][$i]['controlpass'] = 'your_new_phpmyadmin_pass';

(should be like on line 32)

Then go to mysql, login as root, go to: (I used phpmyadmin to go here)

Database: mysql »Table: user

Edit the user: pma

Select "Password" from the function list (left column) and set "your_new_phpmyadmin_pass" on the right column and hit go.

Restart mysql server.

Now the message should disappear.

Using a string variable as a variable name

You will be much happier using a dictionary instead:

my_data = {}
foo = "hello"
my_data[foo] = "goodbye"
assert my_data["hello"] == "goodbye"

javascript multiple OR conditions in IF statement

Each of the three conditions is evaluated independently[1]:

id != 1 // false
id != 2 // true
id != 3 // true

Then it evaluates false || true || true, which is true (a || b is true if either a or b is true). I think you want

id != 1 && id != 2 && id != 3

which is only true if the ID is not 1 AND it's not 2 AND it's not 3.

[1]: This is not strictly true, look up short-circuit evaluation. In reality, only the first two clauses are evaluated because that is all that is necessary to determine the truth value of the expression.

How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)

Add play-services-safetynet library in android build.gradle:

implementation 'com.google.android.gms:play-services-safetynet:+'

and add this code to your MainApplication.java:

@Override
  public void onCreate() {
    super.onCreate();
    upgradeSecurityProvider();
    SoLoader.init(this, /* native exopackage */ false);
  }

  private void upgradeSecurityProvider() {
    ProviderInstaller.installIfNeededAsync(this, new ProviderInstallListener() {
      @Override
      public void onProviderInstalled() {

      }

      @Override
      public void onProviderInstallFailed(int errorCode, Intent recoveryIntent) {
//        GooglePlayServicesUtil.showErrorNotification(errorCode, MainApplication.this);
        GoogleApiAvailability.getInstance().showErrorNotification(MainApplication.this, errorCode);
      }
    });
  }