Programs & Examples On #Sizetocontent

Enabling/installing GD extension? --without-gd

If You're using php5.6 and Ubuntu 18.04 Then run these two commands in your terminal your errors will be solved definitely.

sudo apt-get install php5.6-gd

then restart your apache server by this command.

 sudo service apache2 restart

Check if number is decimal

If you are working with form validation. Then in this case form send string. I used following code to check either form input is a decimal number or not. I hope this will work for you too.

function is_decimal($input = '') {

    $alphabets = str_split($input);
    $find = array('0','1','2','3','4','5','6','7','8','9','.'); // Please note: All intiger numbers are decimal. If you want to check numbers without point "." then you can remove '.' from array. 

    foreach ($alphabets as $key => $alphabet) {
        if (!in_array($alphabet, $find)) {
            return false;
        }
    }

    // Check if user has enter "." point more then once.
    if (substr_count($input, ".") > 1) {
        return false;
    }

    return true;
}

Copying files from one directory to another in Java

Apache commons FileUtils will be handy, if you want only to move files from the source to target directory rather than copy the whole directory, you can do:

for (File srcFile: srcDir.listFiles()) {
    if (srcFile.isDirectory()) {
        FileUtils.copyDirectoryToDirectory(srcFile, dstDir);
    } else {
        FileUtils.copyFileToDirectory(srcFile, dstDir);
    }
}

If you want to skip directories, you can do:

for (File srcFile: srcDir.listFiles()) {
    if (!srcFile.isDirectory()) {
        FileUtils.copyFileToDirectory(srcFile, dstDir);
    }
}

SELECT INTO a table variable in T-SQL

One reason to use SELECT INTO is that it allows you to use IDENTITY:

SELECT IDENTITY(INT,1,1) AS Id, name
INTO #MyTable 
FROM (SELECT name FROM AnotherTable) AS t

This would not work with a table variable, which is too bad...

apache and httpd running but I can't see my website

Did you restart the server after you changed the config file?

Can you telnet to the server from a different machine?

Can you telnet to the server from the server itself?

telnet <ip address> 80

telnet localhost 80

Select All Rows Using Entity Framework

Entity Framework has one beautiful thing for it, like :

var users = context.Users; 

This will select all rows in Table User, then you can use your .ToList() etc.


For newbies to Entity Framework, it is like :

PortalEntities context = new PortalEntities();
var users = context.Users;

This will select all rows in Table User

Parse date without timezone javascript

Date in javascript is just keeping it simple inside. so the date-time data is stored in UTC unix epoch (milliseconds or ms).

If you want to have a "fixed" time that doesn't change in whatever timezone you are on the earth, you can adjust the time in UTC to match your current local timezone and save it. And when retreiving it, in whatever your local timezone you are in, it will show the adjusted UTC time based on the one who saved it and the add the local timezone offset to get the "fixed" time.

To save date (in ms)

toUTC(datetime) {
  const myDate = (typeof datetime === 'number')
    ? new Date(datetime)
    : datetime;

  if (!myDate || (typeof myDate.getTime !== 'function')) {
    return 0;
  }

  const getUTC = myDate.getTime();
  const offset = myDate.getTimezoneOffset() * 60000; // It's in minutes so convert to ms
  return getUTC - offset; // UTC - OFFSET
}

To retreive/show date (in ms)

fromUTC(datetime) {
  const myDate = (typeof datetime === 'number')
    ? new Date(datetime)
    : datetime;

  if (!myDate || (typeof myDate.getTime !== 'function')) {
    return 0;
  }

  const getUTC = myDate.getTime();
  const offset = myDate.getTimezoneOffset() * 60000; // It's in minutes so convert to ms
  return getUTC + offset; // UTC + OFFSET
}

Then you can:

const saveTime = new Date(toUTC(Date.parse("2005-07-08T00:00:00+0000")));
// SEND TO DB....

// FROM DB...
const showTime = new Date(fromUTC(saveTime));

How to show all shared libraries used by executables in Linux?

On Linux I use:

lsof -P -T -p Application_PID

This works better than ldd when the executable uses a non default loader

How do I concatenate strings with variables in PowerShell?

You could use the PowerShell equivalent of String.Format - it's usually the easiest way to build up a string. Place {0}, {1}, etc. where you want the variables in the string, put a -f immediately after the string and then the list of variables separated by commas.

Get-ChildItem c:\code|%{'{0}\{1}\{2}.dll' -f $_.fullname,$buildconfig,$_.name}

(I've also taken the dash out of the $buildconfig variable name as I have seen that causes issues before too.)

How can I remove leading and trailing quotes in SQL Server?

You can use TRIM('"' FROM '"this "is" a test"') which returns: this "is" a test

python pandas convert index to datetime

It should work as expected. Try to run the following example.

import pandas as pd
import io

data = """value          
"2015-09-25 00:46"    71.925000
"2015-09-25 00:47"    71.625000
"2015-09-25 00:48"    71.333333
"2015-09-25 00:49"    64.571429
"2015-09-25 00:50"    72.285714"""

df = pd.read_table(io.StringIO(data), delim_whitespace=True)

# Converting the index as date
df.index = pd.to_datetime(df.index)

# Extracting hour & minute
df['A'] = df.index.hour
df['B'] = df.index.minute
df

#                          value  A   B
# 2015-09-25 00:46:00  71.925000  0  46
# 2015-09-25 00:47:00  71.625000  0  47
# 2015-09-25 00:48:00  71.333333  0  48
# 2015-09-25 00:49:00  64.571429  0  49
# 2015-09-25 00:50:00  72.285714  0  50

The most efficient way to implement an integer based power function pow(int, int)

My case is a little different, I'm trying to create a mask from a power, but I thought I'd share the solution I found anyway.

Obviously, it only works for powers of 2.

Mask1 = 1 << (Exponent - 1);
Mask2 = Mask1 - 1;
return Mask1 + Mask2;

How to find the Vagrant IP?

I've developed a small vagrant-address plugin for that. It's simple, cross-platform, cross-provider, and does not require scripting.

https://github.com/mkuzmin/vagrant-address

Which is best data type for phone number in MySQL and what should Java type mapping for it be?

you can use var-char,String,and int ,it depends on you, if you use only country code with mobile number than you can use int,if you use special formate for number than use String or var-char type, if you use var-char then must defile size of number and restrict from user.

Child with max-height: 100% overflows parent

_x000D_
_x000D_
.container {_x000D_
  background: blue;_x000D_
  padding: 10px;_x000D_
  max-height: 200px;_x000D_
  max-width: 200px;_x000D_
  float: left;_x000D_
  margin-right: 20px;_x000D_
}_x000D_
_x000D_
.img1 {_x000D_
  display: block;_x000D_
  max-height: 100%;_x000D_
  max-width: 100%;_x000D_
}_x000D_
_x000D_
.img2 {_x000D_
  display: block;_x000D_
  max-height: inherit;_x000D_
  max-width: inherit;_x000D_
}
_x000D_
<!-- example 1  -->_x000D_
<div class="container">_x000D_
  <img class='img1' src="http://via.placeholder.com/350x450" />_x000D_
</div>_x000D_
_x000D_
<!-- example 2  -->_x000D_
_x000D_
<div class="container">_x000D_
  <img class='img2' src="http://via.placeholder.com/350x450" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

I played around a little. On a larger image in firefox, I got a good result with using the inherit property value. Will this help you?

.container {
    background: blue;
    padding: 10px;
    max-height: 100px;
    max-width: 100px;
    text-align:center;
}

img {
    max-height: inherit;
    max-width: inherit;
}

How do I fix twitter-bootstrap on IE?

I had this problem recently. I made these settings change. And it worked for me. !

verify these settings

Python POST binary data

You can use unirest, It provides easy method to post request. `

import unirest
 
def callback(response):
 print "code:"+ str(response.code)
 print "******************"
 print "headers:"+ str(response.headers)
 print "******************"
 print "body:"+ str(response.body)
 print "******************"
 print "raw_body:"+ str(response.raw_body)
 
# consume async post request
def consumePOSTRequestASync():
 params = {'test1':'param1','test2':'param2'}
 
 # we need to pass a dummy variable which is open method
 # actually unirest does not provide variable to shift between
 # application-x-www-form-urlencoded and
 # multipart/form-data
  
 params['dummy'] = open('dummy.txt', 'r')
 url = 'http://httpbin.org/post'
 headers = {"Accept": "application/json"}
 # call get service with headers and params
 unirest.post(url, headers = headers,params = params, callback = callback)
 
 
# post async request multipart/form-data
consumePOSTRequestASync()

jQuery table sort

My vote! jquery.sortElements.js and simple jquery
Very simple, very easy, thanks nandhp...

            $('th').live('click', function(){

            var th = $(this), thIndex = th.index(), var table = $(this).parent().parent();

                switch($(this).attr('inverse')){
                case 'false': inverse = true; break;
                case 'true:': inverse = false; break;
                default: inverse = false; break;
                }
            th.attr('inverse',inverse)

            table.find('td').filter(function(){
                return $(this).index() === thIndex;
            }).sortElements(function(a, b){
                return $.text([a]) > $.text([b]) ?
                    inverse ? -1 : 1
                    : inverse ? 1 : -1;
            }, function(){
                // parentNode is the element we want to move
                return this.parentNode; 
            });
            inverse = !inverse;     
            });

Dei uma melhorada do código
One cod better! Function for All tables in all Th in all time... Look it!
DEMO

Find duplicates and delete all in notepad++

If it is possible to change the sequence of the lines you could do:

  1. sort line with Edit -> Line Operations -> Sort Lines Lexicographically ascending
  2. do a Find / Replace:
    • Find What: ^(.*\r?\n)\1+
    • Replace with: (Nothing, leave empty)
    • Check Regular Expression in the lower left
    • Click Replace All

How it works: The sorting puts the duplicates behind each other. The find matches a line ^(.*\r?\n) and captures the line in \1 then it continues and tries to find \1 one or more times (+) behind the first match. Such a block of duplicates (if it exists) is replaced with nothing.

The \r?\n should deal nicely with Windows and Unix lineendings.

How to update/upgrade a package using pip?

use this code in teminal :

python -m pip install --upgrade PAKAGE_NAME #instead of PAKAGE_NAME 

for example i want update pip pakage :

 python -m pip install --upgrade pip

more example :

python -m pip install --upgrade selenium
python -m pip install --upgrade requests
...

Asp.net 4.0 has not been registered

I repaired it using the Microsoft .NET Framework Repair Tool. After reloading my project a couple of times after that the problem went away.

How can I get the max (or min) value in a vector?

Assuming cloud is int cloud[10] you can do it like this: int *p = max_element(cloud, cloud + 10);

How to load data to hive from HDFS without removing the source file?

I found that, when you use EXTERNAL TABLE and LOCATION together, Hive creates table and initially no data will present (assuming your data location is different from the Hive 'LOCATION').

When you use 'LOAD DATA INPATH' command, the data get MOVED (instead of copy) from data location to location that you specified while creating Hive table.

If location is not given when you create Hive table, it uses internal Hive warehouse location and data will get moved from your source data location to internal Hive data warehouse location (i.e. /user/hive/warehouse/).

How to disable registration new users in Laravel

For Laravel 5.6+, paste the below methods in app\Http\Controller\Auth\RegisterController

/*
* Disabling registeration.
*
*/
public function register() 
{
    return redirect('/');
}

/*
* Disabling registeration.
*
*/
public function showRegistrationForm() 
{
    return redirect('/');
}

Now you're overriding those methods in RegistersUser trait, whenever you change your mind remove these methods. You may also comment the register links in welcome.blade.php and login.blade.php views.

Importing from a relative path in Python

Funny enough, a same problem I just met, and I get this work in following way:

combining with linux command ln , we can make thing a lot simper:

1. cd Proj/Client
2. ln -s ../Common ./

3. cd Proj/Server
4. ln -s ../Common ./

And, now if you want to import some_stuff from file: Proj/Common/Common.py into your file: Proj/Client/Client.py, just like this:

# in Proj/Client/Client.py
from Common.Common import some_stuff

And, the same applies to Proj/Server, Also works for setup.py process, a same question discussed here, hope it helps !

How to load my app from Eclipse to my Android phone instead of AVD

Check to see if the Andriod Device is installed on PC. See steps below. The 'Other device' will change to 'Andriod Device' once the USB drive is installed. The browse path should be \extras\google\usb_driver\ not the sub directories under it. Otherwise the installation will not find the package.

To install the Android USB driver on Windows 7 for the first time:

Connect your Android-powered device to your computer's USB port. Right-click on Computer from your desktop or Windows Explorer, and select Manage. Select Devices in the left pane. Locate and expand Other device in the right pane. Right-click the device name (such as Nexus S) and select Update Driver Software. This will launch the Hardware Update Wizard. Select Browse my computer for driver software and click Next. Click Browse and locate the USB driver folder. (The Google USB Driver is located in \extras\google\usb_driver.) Click Next to install the driver.

How can I quickly delete a line in VIM starting at the cursor position?

D or dd deletes and copies the line to the register. You can use Vx which only deletes the line and stays in the normal mode.

How to use Apple's new San Francisco font on a webpage

You can not use Apple System Font served directly from a database. It's against the License, but you can use this for Mac Systems higher than High Sierra

body 
{
  font-family: -apple-system, "Helvetica Neue", "Lucida Grande";
}

Or you can use this:

font-family: 'BlinkMacSystemFont';

Disable single warning error

Example:

#pragma warning(suppress:0000)  // (suppress one error in the next line)

This pragma is valid for C++ starting with Visual Studio 2005.
https://msdn.microsoft.com/en-us/library/2c8f766e(v=vs.80).aspx

The pragma is NOT valid for C# through Visual Studio 2005 through Visual Studio 2015.
Error: "Expected disable or restore".
(I guess they never got around to implementing suppress ...)
https://msdn.microsoft.com/en-us/library/441722ys(v=vs.140).aspx

C# needs a different format. It would look like this (but not work):

#pragma warning suppress 0642  // (suppress one error in the next line)

Instead of suppress, you have to disable and enable:

if (condition)
#pragma warning disable 0642
    ;  // Empty statement HERE provokes Warning: "Possible mistaken empty statement" (CS0642)
#pragma warning restore 0642
else

That is SO ugly, I think it is smarter to just re-style it:

if (condition)
{
    // Do nothing (because blah blah blah).
}
else

How to call external JavaScript function in HTML

In Layman terms, you need to include external js file in your HTML file & thereafter you could directly call your JS method written in an external js file from HTML page. Follow the code snippet for insight:-

caller.html

<script type="text/javascript" src="external.js"></script>
<input type="button" onclick="letMeCallYou()" value="run external javascript">

external.js

function letMeCallYou()
{
    alert("Bazinga!!!  you called letMeCallYou")
}

Result : enter image description here

Copying files from server to local computer using SSH

Your question is a bit confusing, but I am assuming - you are first doing 'ssh' to find out which files or rather specifically directories are there and then again on your local computer, you are trying to scp 'all' files in that directory to local path. you should simply do scp -r.

So here in your case it'd be something like

local> scp -r [email protected]:/path/to/dir local/path 

If youare using some other executable that provides 'scp like functionality', refer to it's manual for recursively copying files.

Automatically add all files in a folder to a target using CMake?

So Why not use powershell to create the list of source files for you. Take a look at this script

param (
    [Parameter(Mandatory=$True)]
    [string]$root 
)

if (-not (Test-Path  -Path $root)) {    
throw "Error directory does not exist"
}

#get the full path of the root
$rootDir = get-item -Path $root
$fp=$rootDir.FullName;


$files = Get-ChildItem -Path $root -Recurse -File | 
         Where-Object { ".cpp",".cxx",".cc",".h" -contains $_.Extension} | 
         Foreach {$_.FullName.replace("${fp}\","").replace("\","/")}

$CMakeExpr = "set(SOURCES "

foreach($file in $files){

    $CMakeExpr+= """$file"" " ;
}
$CMakeExpr+=")"
return $CMakeExpr;

Suppose you have a folder with this structure

C:\Workspace\A
--a.cpp
C:\Workspace\B 
--b.cpp

Now save this file as "generateSourceList.ps1" for example, and run the script as

~>./generateSourceList.ps1 -root "C:\Workspace" > out.txt

out.txt file will contain

set(SOURCE "A/a.cpp" "B/b.cpp")

Is it ok to scrape data from Google results?

Google will eventually block your IP when you exceed a certain amount of requests.

How do you do block comments in YAML?

An alternative approach:

If

  • your YAML structure has well defined fields to be used by your app
  • AND you may freely add additional fields that won't mess up with your app

then

  • at any level you may add a new block text field named like "Description" or "Comment" or "Notes" or whatever

Example:

Instead of

# This comment
# is too long

use

Description: >
  This comment
  is too long

or

Comment: >
    This comment is also too long
    and newlines survive from parsing!

More advantages:

  1. If the comments become large and complex and have a repeating pattern, you may promote them from plain text blocks to objects
  2. Your app may -in the future- read or update those comments

Trying to get PyCharm to work, keep getting "No Python interpreter selected"

Your problem probably is that you haven't installed python. Meaning that, if you are using Windows, you have not downloaded the installer for Windows, that you can find on the official Python website.

In case you have, chances are that PyCharm cannot find your Python installation because its not in the default location, which is usually C:\Python27 or C:\Python33 (for me at least).

So, if you have installed Python and it still gives this error, then there can be two things that have happened:

  1. You use a virtualenv and that virtualenv has been deleted or the filepath changed. In this case, you will have to find proceed to the next part of this answer.
  2. Your python installation is not in its default place, in which case you will need to find its location, and locate the python.exe file.

Once you have located the necessary binaries, you will need to tell PyCharm were to look:

  1. Open your settings dialogue CTRL + ALT + S
  2. Then you will need to type in interpreter in the search box:

    enter image description here

  3. As you can see above, you will need to go to Project Interpreter and then go to Python Interpreter. The location has been selected for you in the above image.

  4. To the side you will see a couple of options as icons, click the big + icon, then click on local, because your interpreter is on this computer.

  5. This will open up a dialogue box. Make sure to select the python.exe file of that directory, do not give pycharm the whole directory. It just wants the interpreter.

How to encode a URL in Swift

XCODE 8, SWIFT 3.0

From grokswift

Creating URLs from strings is a minefield for bugs. Just miss a single / or accidentally URL encode the ? in a query and your API call will fail and your app won’t have any data to display (or even crash if you didn’t anticipate that possibility). Since iOS 8 there’s a better way to build URLs using NSURLComponents and NSURLQueryItems.

func createURLWithComponents() -> URL? {
    var urlComponents = URLComponents()
    urlComponents.scheme = "http"
    urlComponents.host = "maps.googleapis.com"
    urlComponents.path = "/maps/api/geocode/json"

    let addressQuery = URLQueryItem(name: "address", value: "American Tourister, Abids Road, Bogulkunta, Hyderabad, Andhra Pradesh, India")
    urlComponents.queryItems = [addressQuery]

    return urlComponents.url
}

Below is the code to access url using guard statement.

guard let url = createURLWithComponents() else {
            print("invalid URL")
            return nil
      }
      print(url)

Output:

http://maps.googleapis.com/maps/api/geocode/json?address=American%20Tourister,%20Abids%20Road,%20Bogulkunta,%20Hyderabad,%20Andhra%20Pradesh,%20India

Read More: Building URLs With NSURLComponents and NSURLQueryItems

Get full query string in C# ASP.NET

This should work fine for you.

Write this code in the Page_Load event of the page.

string ID = Request.QueryString["id"].ToString();
Response.Redirect("http://www.example.com/rendernews.php?id=" + ID);

Add days to JavaScript Date

These answers seem confusing to me, I prefer:

var ms = new Date().getTime() + 86400000;
var tomorrow = new Date(ms);

getTime() gives us milliseconds since 1970, and 86400000 is the number of milliseconds in a day. Hence, ms contains milliseconds for the desired date.

Using the millisecond constructor gives the desired date object.

break/exit script

Perhaps you just want to stop executing a long script at some point. ie. like you want to hard code an exit() in C or Python.

print("this is the last message")
stop()
print("you should not see this")

String, StringBuffer, and StringBuilder

In java, String is immutable. Being immutable we mean that once a String is created, we can not change its value. StringBuffer is mutable. Once a StringBuffer object is created, we just append the content to the value of object instead of creating a new object. StringBuilder is similar to StringBuffer but it is not thread-safe. Methods of StingBuilder are not synchronized but in comparison to other Strings, the Stringbuilder runs fastest. You can learn difference between String, StringBuilder and StringBuffer by implementing them.

Adding the "Clear" Button to an iPhone UITextField

You can also set this directly from Interface Builder under the Attributes Inspector.

enter image description here

Taken from XCode 5.1

"git checkout <commit id>" is changing branch to "no branch"

Is that commit in the other branch? Git checkout <commitid> will just switch over to the other branch if the commit has happened in the other branch. You will want to merge the changes to your first branch if you want the code there.

Hash function that produces short hashes?

You could use an existing hash algorithm that produces something short, like MD5 (128 bits) or SHA1 (160). Then you can shorten that further by XORing sections of the digest with other sections. This will increase the chance of collisions, but not as bad as simply truncating the digest.

Also, you could include the length of the original data as part of the result to make it more unique. For example, XORing the first half of an MD5 digest with the second half would result in 64 bits. Add 32 bits for the length of the data (or lower if you know that length will always fit into fewer bits). That would result in a 96-bit (12-byte) result that you could then turn into a 24-character hex string. Alternately, you could use base 64 encoding to make it even shorter.

Round number to nearest integer

Use round(x, y). It will round up your number up to your desired decimal place.

For example:

>>> round(32.268907563, 3)
32.269

Server Error in '/' Application. ASP.NET

Try removing the contents of the <compilers> tag in the web.config file. Depending on who you're hosting with, some don't allow the compiler in production.

Your application is trying to compile when it is called and their servers won't allow it.

How to match "any character" in regular expression?

[^] should match any character, including newline. [^CHARS] matches all characters except for those in CHARS. If CHARS is empty, it matches all characters.

JavaScript example:

/a[^]*Z/.test("abcxyz \0\r\n\t012789ABCXYZ") // Returns ‘true’.

Format Date/Time in XAML in Silverlight

You can use StringFormat in Silverlight 4 to provide a custom formatting of the value you bind to.

Dates

The date formatting has a huge range of options.

For the DateTime of “April 17, 2004, 1:52:45 PM”

You can either use a set of standard formats (standard formats)…

StringFormat=f : “Saturday, April 17, 2004 1:52 PM”
StringFormat=g : “4/17/2004 1:52 PM”
StringFormat=m : “April 17”
StringFormat=y : “April, 2004”
StringFormat=t : “1:52 PM”
StringFormat=u : “2004-04-17 13:52:45Z”
StringFormat=o : “2004-04-17T13:52:45.0000000”

… or you can create your own date formatting using letters (custom formats)

StringFormat=’MM/dd/yy’ : “04/17/04”
StringFormat=’MMMM dd, yyyy g’ : “April 17, 2004 A.D.”
StringFormat=’hh:mm:ss.fff tt’ : “01:52:45.000 PM”

accepting HTTPS connections with self-signed certificates

Simplest way for create SSL certificate

Open Firefox (I suppose it's also possible with Chrome, but it's easier for me with FF)

Visit your development site with a self-signed SSL certificate.

Click on the certificate (next to the site name)

Click on "More information"

Click on "View certificate"

Click on "Details"

Click on "Export..."

Choose "X.509 Certificate whith chain (PEM)", select the folder and name to save it and click "Save"

Go to command line, to the directory where you downloaded the pem file and execute "openssl x509 -inform PEM -outform DM -in .pem -out .crt"

Copy the .crt file to the root of the /sdcard folder inside your Android device Inside your Android device, Settings > Security > Install from storage.

It should detect the certificate and let you add it to the device Browse to your development site.

The first time it should ask you to confirm the security exception. That's all.

The certificate should work with any browser installed on your Android (Browser, Chrome, Opera, Dolphin...)

Remember that if you're serving your static files from a different domain (we all are page speed bitches) you also need to add the certificate for that domain.

How Does Modulus Divison Work

Easier when your number after the decimal (0.xxx) is short. Then all you need to do is multiply that number with the number after the division.

Ex: 32 % 12 = 8

You do 32/12=2.666666667 Then you throw the 2 away, and focus on the 0.666666667 0.666666667*12=8 <-- That's your answer.

(again, only easy when the number after the decimal is short)

What is meaning of negative dbm in signal strength?

I think it is confusing to think of it in terms of negative numbers. Since it is a logarithm think of the negative values the same way you think of powers of ten. 10^3 = 1000 while 10^-3 = 0.001.

With this in mind and using the formulas from S Lists's answer (and assuming our base power is 1mW in all these cases) we can build a little table:

|--------|-------------------|
| P(dBm) |        P(mW)      |
|--------|-------------------|
|    50  |  100000           |    
|    40  |   10000           |    strong transmitter
|    30  |    1000           |             ^  
|    20  |     100           |             |
|    10  |      10           |             |
|     0  |       1           |
|   -10  |       0.1         |
|   -20  |       0.01        |
|   -30  |       0.001       |
|   -40  |       0.0001      |
|   -50  |       0.00001     |             |
|   -60  |       0.000001    |             |
|   -70  |       0.0000001   |             v
|   -80  |       0.00000001  |    sensitive receiver
|   -90  |       0.000000001 |
|--------|-------------------|

When I think of it like this I find that it's easier to see that the more negative the dBm value then the farther to the right of the decimal the actual power value is.

When it comes to mobile networks, it not so much that they aren't powerful enough, rather it is that they are more sensitive. When you see receivers specs with dBm far into the negative values, then what you are seeing is more sensitive equipment.

Normally you would want your transmitter to be powerful (further in to the positives) and your receiver to be sensitive (further in to the negatives).

How best to include other scripts?

I tend to make my scripts all be relative to one another. That way I can use dirname:

#!/bin/sh

my_dir="$(dirname "$0")"

"$my_dir/other_script.sh"

Can .NET load and parse a properties file equivalent to Java Properties class?

Yeah there's no built in classes to do this that I'm aware of.

But that shouldn't really be an issue should it? It looks easy enough to parse just by storing the result of Stream.ReadToEnd() in a string, splitting based on new lines and then splitting each record on the = character. What you'd be left with is a bunch of key value pairs which you can easily toss into a dictionary.

Here's an example that might work for you:

public static Dictionary<string, string> GetProperties(string path)
{
    string fileData = "";
    using (StreamReader sr = new StreamReader(path))
    {
        fileData = sr.ReadToEnd().Replace("\r", "");
    }
    Dictionary<string, string> Properties = new Dictionary<string, string>();
    string[] kvp;
    string[] records = fileData.Split("\n".ToCharArray());
    foreach (string record in records)
    {
        kvp = record.Split("=".ToCharArray());
        Properties.Add(kvp[0], kvp[1]);
    }
    return Properties;
}

Here's an example of how to use it:

Dictionary<string,string> Properties = GetProperties("data.txt");
Console.WriteLine("Hello: " + Properties["Hello"]);
Console.ReadKey();

How do I change the figure size with subplots?

Alternatively, create a figure() object using the figsize argument and then use add_subplot to add your subplots. E.g.

import matplotlib.pyplot as plt
import numpy as np

f = plt.figure(figsize=(10,3))
ax = f.add_subplot(121)
ax2 = f.add_subplot(122)
x = np.linspace(0,4,1000)
ax.plot(x, np.sin(x))
ax2.plot(x, np.cos(x), 'r:')

Simple Example

Benefits of this method are that the syntax is closer to calls of subplot() instead of subplots(). E.g. subplots doesn't seem to support using a GridSpec for controlling the spacing of the subplots, but both subplot() and add_subplot() do.

How to specify a multi-line shell variable?

Thanks to dimo414's answer to a similar question, this shows how his great solution works, and shows that you can have quotes and variables in the text easily as well:

example output

$ ./test.sh

The text from the example function is:
  Welcome dev: Would you "like" to know how many 'files' there are in /tmp?

  There are "      38" files in /tmp, according to the "wc" command

test.sh

#!/bin/bash

function text1()
{
  COUNT=$(\ls /tmp | wc -l)
cat <<EOF

  $1 Would you "like" to know how many 'files' there are in /tmp?

  There are "$COUNT" files in /tmp, according to the "wc" command

EOF
}

function main()
{
  OUT=$(text1 "Welcome dev:")
  echo "The text from the example function is: $OUT"
}

main

Free Barcode API for .NET

There is a "3 of 9" control on CodeProject: Barcode .NET Control

Pandas: Convert Timestamp to datetime.date

Assume time column is in timestamp integer msec format

1 day = 86400000 ms

Here you go:

day_divider = 86400000

df['time'] = df['time'].values.astype(dtype='datetime64[ms]') # for msec format

df['time'] = (df['time']/day_divider).values.astype(dtype='datetime64[D]') # for day format

Different between parseInt() and valueOf() in java?

Integer.valueOf(s)

is similar to

new Integer(Integer.parseInt(s))

The difference is valueOf() returns an Integer, and parseInt() returns an int (a primitive type). Also note that valueOf() can return a cached Integer instance, which can cause confusing results where the result of == tests seem intermittently correct. Before autoboxing there could be a difference in convenience, after java 1.5 it doesn't really matter.

Moreover, Integer.parseInt(s) can take primitive datatype as well.

How to close Browser Tab After Submitting a Form?

You can try this methods

window.open(location, '_self').close();

Error in spring application context schema

What I did with spring-data-jpa-1.3 was adding a version to xsd and lowered it to 1.2. Then the error message disappears. Like this

<beans
        xmlns="http://www.springframework.org/schema/beans"
        ...
        xmlns:jpa="http://www.springframework.org/schema/data/jpa"
        xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    ...
    http://www.springframework.org/schema/data/jpa
    http://www.springframework.org/schema/data/jpa/spring-jpa-1.2.xsd">

Seems like it was fixed for for 1.2 but then appears again in 1.3.

How can I conditionally require form inputs with AngularJS?

if you want put a input required if other is written:

   <input type='text'
   name='name'
   ng-model='person.name'/>

   <input type='text'
   ng-model='person.lastname'             
   ng-required='person.name' />  

Regards.

When creating a service with sc.exe how to pass in context parameters?

I couldn't handle the issue with your proposals, at the end with the x86 folder it only worked in power shell (windows server 2012) using environment variables:

{sc.exe create svnserve binpath= "${env:programfiles(x86)}/subversion/bin/svnserve.exe --service -r C:/svnrepositories/"   displayname= "Subversion Server" depend= Tcpip start= auto}

Python name 'os' is not defined

Just add:

import os

in the beginning, before:

from settings import PROJECT_ROOT

This will import the python's module os, which apparently is used later in the code of your module without being imported.

How can I set a DateTimePicker control to a specific date?

Also, we can assign the Value to the Control in Designer Class (i.e. FormName.Designer.cs).

DateTimePicker1.Value = DateTime.Now;

This way you always get Current Date...

Jquery select change not firing

For me perfectly fork this code.

$('#dom_object_id').on('change paste keyup', function(){
    console.log($("#dom_object_id").val().length)
});

Key event for .on() function is "paste" to get changes dynamically

Inline SVG in CSS

Yes, it is possible. Try this:

body { background-image: 
        url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><linearGradient id='gradient'><stop offset='10%' stop-color='%23F00'/><stop offset='90%' stop-color='%23fcc'/> </linearGradient><rect fill='url(%23gradient)' x='0' y='0' width='100%' height='100%'/></svg>");
      }

(Note that the SVG content needs to be url-escaped for this to work, e.g. # gets replaced with %23.)

This works in IE 9 (which supports SVG). Data-URLs work in older versions of IE too (with limitations), but they don’t natively support SVG.

The import org.junit cannot be resolved

you need to add Junit dependency in pom.xml file, it means you need to update with latest version.

<dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency> 

Convert NVARCHAR to DATETIME in SQL Server 2008

What you exactly wan't to do ?. To change Datatype of column you can simple use alter command as

ALTER TABLE table_name ALTER COLUMN LoginDate DateTime;

But remember there should valid Date only in this column however data-type is nvarchar.

If you wan't to convert data type while fetching data then you can use CONVERT function as,

CONVERT(data_type(length),expression,style)

eg:

SELECT CONVERT(DateTime, loginDate, 6)

This will return 29 AUG 13. For details about CONVERT function you can visit ,

http://www.w3schools.com/sql/func_convert.asp.

Remember, Always use DataTime data type for DateTime column.

Thank You

How to set <iframe src="..."> without causing `unsafe value` exception?

This one works for me.

import { Component,Input,OnInit} from '@angular/core';
import {DomSanitizer,SafeResourceUrl,} from '@angular/platform-browser';

@Component({
    moduleId: module.id,
    selector: 'player',
    templateUrl: './player.component.html',
    styleUrls:['./player.component.scss'],
    
})
export class PlayerComponent implements OnInit{
    @Input()
    id:string; 
    url: SafeResourceUrl;
    constructor (public sanitizer:DomSanitizer) {
    }
    ngOnInit() {
        this.url = this.sanitizer.bypassSecurityTrustResourceUrl(this.id);      
    }
}

How to get RegistrationID using GCM in android

Use this code to get Registration ID using GCM

String regId = "", msg = "";

public void getRegisterationID() {

    new AsyncTask() {
        @Override
        protected Object doInBackground(Object...params) {

            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(Login.this);
                }
                regId = gcm.register(YOUR_SENDER_ID);
                Log.d("in async task", regId);

                // try
                msg = "Device registered, registration ID=" + regId;

            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();
            }
            return msg;
        }
    }.execute(null, null, null);
 }

and don't forget to write permissions in manifest...
I hope it helps!

Get the last item in an array

This method will not mess with your prototype. It also guards against 0 length arrays, along with null/undefined arrays. You can even override the default value if the returned default value might match an item in your array.

_x000D_
_x000D_
const items = [1,2,3]_x000D_
const noItems = []_x000D_
_x000D_
/**_x000D_
 * Returns the last item in an array._x000D_
 * If the array is null, undefined, or empty, the default value is returned._x000D_
 */_x000D_
function arrayLast (arrayOrNull, defVal = undefined) {_x000D_
  if (!arrayOrNull || arrayOrNull.length === 0) {_x000D_
    return defVal_x000D_
  }_x000D_
  return arrayOrNull[arrayOrNull.length - 1]_x000D_
}_x000D_
_x000D_
console.log(arrayLast(items))_x000D_
console.log(arrayLast(noItems))_x000D_
console.log(arrayLast(null))_x000D_
_x000D_
console.log(arrayLast(items, 'someDefault'))_x000D_
console.log(arrayLast(noItems, 'someDefault'))_x000D_
console.log(arrayLast(null, 'someDefault'))
_x000D_
_x000D_
_x000D_

Oracle 'Partition By' and 'Row_Number' keyword

PARTITION BY segregate sets, this enables you to be able to work(ROW_NUMBER(),COUNT(),SUM(),etc) on related set independently.

In your query, the related set comprised of rows with similar cdt.country_code, cdt.account, cdt.currency. When you partition on those columns and you apply ROW_NUMBER on them. Those other columns on those combination/set will receive sequential number from ROW_NUMBER

But that query is funny, if your partition by some unique data and you put a row_number on it, it will just produce same number. It's like you do an ORDER BY on a partition that is guaranteed to be unique. Example, think of GUID as unique combination of cdt.country_code, cdt.account, cdt.currency

newid() produces GUID, so what shall you expect by this expression?

select
   hi,ho,
   row_number() over(partition by newid() order by hi,ho)
from tbl;

...Right, all the partitioned(none was partitioned, every row is partitioned in their own row) rows' row_numbers are all set to 1

Basically, you should partition on non-unique columns. ORDER BY on OVER needed the PARTITION BY to have a non-unique combination, otherwise all row_numbers will become 1

An example, this is your data:

create table tbl(hi varchar, ho varchar);

insert into tbl values
('A','X'),
('A','Y'),
('A','Z'),
('B','W'),
('B','W'),
('C','L'),
('C','L');

Then this is analogous to your query:

select
   hi,ho,
   row_number() over(partition by hi,ho order by hi,ho)
from tbl;

What will be the output of that?

HI  HO  COLUMN_2
A   X   1
A   Y   1
A   Z   1
B   W   1
B   W   2
C   L   1
C   L   2

You see thee combination of HI HO? The first three rows has unique combination, hence they are set to 1, the B rows has same W, hence different ROW_NUMBERS, likewise with HI C rows.

Now, why is the ORDER BY needed there? If the previous developer merely want to put a row_number on similar data (e.g. HI B, all data are B-W, B-W), he can just do this:

select
   hi,ho,
   row_number() over(partition by hi,ho)
from tbl;

But alas, Oracle(and Sql Server too) doesn't allow partition with no ORDER BY; whereas in Postgresql, ORDER BY on PARTITION is optional: http://www.sqlfiddle.com/#!1/27821/1

select
   hi,ho,
   row_number() over(partition by hi,ho)
from tbl;

Your ORDER BY on your partition look a bit redundant, not because of the previous developer's fault, some database just don't allow PARTITION with no ORDER BY, he might not able find a good candidate column to sort on. If both PARTITION BY columns and ORDER BY columns are the same just remove the ORDER BY, but since some database don't allow it, you can just do this:

SELECT cdt.*,
        ROW_NUMBER ()
        OVER (PARTITION BY cdt.country_code, cdt.account, cdt.currency
              ORDER BY newid())
           seq_no
   FROM CUSTOMER_DETAILS cdt

You cannot find a good column to use for sorting similar data? You might as well sort on random, the partitioned data have the same values anyway. You can use GUID for example(you use newid() for SQL Server). So that has the same output made by previous developer, it's unfortunate that some database doesn't allow PARTITION with no ORDER BY

Though really, it eludes me and I cannot find a good reason to put a number on the same combinations (B-W, B-W in example above). It's giving the impression of database having redundant data. Somehow reminded me of this: How to get one unique record from the same list of records from table? No Unique constraint in the table

It really looks arcane seeing a PARTITION BY with same combination of columns with ORDER BY, can not easily infer the code's intent.

Live test: http://www.sqlfiddle.com/#!3/27821/6


But as dbaseman have noticed also, it's useless to partition and order on same columns.

You have a set of data like this:

create table tbl(hi varchar, ho varchar);

insert into tbl values
('A','X'),
('A','X'),
('A','X'),
('B','Y'),
('B','Y'),
('C','Z'),
('C','Z');

Then you PARTITION BY hi,ho; and then you ORDER BY hi,ho. There's no sense numbering similar data :-) http://www.sqlfiddle.com/#!3/29ab8/3

select
   hi,ho,
   row_number() over(partition by hi,ho order by hi,ho) as nr
from tbl;

Output:

HI  HO  ROW_QUERY_A
A   X   1
A   X   2
A   X   3
B   Y   1
B   Y   2
C   Z   1
C   Z   2

See? Why need to put row numbers on same combination? What you will analyze on triple A,X, on double B,Y, on double C,Z? :-)


You just need to use PARTITION on non-unique column, then you sort on non-unique column(s)'s unique-ing column. Example will make it more clear:

create table tbl(hi varchar, ho varchar);

insert into tbl values
('A','D'),
('A','E'),
('A','F'),
('B','F'),
('B','E'),
('C','E'),
('C','D');

select
   hi,ho,
   row_number() over(partition by hi order by ho) as nr
from tbl;

PARTITION BY hi operates on non unique column, then on each partitioned column, you order on its unique column(ho), ORDER BY ho

Output:

HI  HO  NR
A   D   1
A   E   2
A   F   3
B   E   1
B   F   2
C   D   1
C   E   2

That data set makes more sense

Live test: http://www.sqlfiddle.com/#!3/d0b44/1

And this is similar to your query with same columns on both PARTITION BY and ORDER BY:

select
   hi,ho,
   row_number() over(partition by hi,ho order by hi,ho) as nr
from tbl;

And this is the ouput:

HI  HO  NR
A   D   1
A   E   1
A   F   1
B   E   1
B   F   1
C   D   1
C   E   1

See? no sense?

Live test: http://www.sqlfiddle.com/#!3/d0b44/3


Finally this might be the right query:

SELECT cdt.*,
     ROW_NUMBER ()
     OVER (PARTITION BY cdt.country_code, cdt.account -- removed: cdt.currency
           ORDER BY 
               -- removed: cdt.country_code, cdt.account, 
               cdt.currency) -- keep
        seq_no
FROM CUSTOMER_DETAILS cdt

Python datetime strptime() and strftime(): how to preserve the timezone information

Unfortunately, strptime() can only handle the timezone configured by your OS, and then only as a time offset, really. From the documentation:

Support for the %Z directive is based on the values contained in tzname and whether daylight is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones).

strftime() doesn't officially support %z.

You are stuck with python-dateutil to support timezone parsing, I am afraid.

Enter key press behaves like a Tab in Javascript

Many answers here uses e.keyCode and e.which that are deprecated.

Instead you should use e.key === 'Enter'.

Documentation: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

  • I'm sorry but I can't test these snippets just now. Will come back later after testing it.

With HTML:

<body onkeypress="if(event.key==='Enter' && event.target.form){focusNextElement(event); return false;}">

With jQuery:

$(window).on('keypress', function (ev)
{
    if (ev.key === "Enter" && ev.currentTarget.form) focusNextElement(ev)
}

And with Vanilla JS:

document.addEventListener('keypress', function (ev) {
    if (ev.key === "Enter" && ev.currentTarget.form) focusNextElement(ev);
});

You can take focusNextElement() function from here: https://stackoverflow.com/a/35173443/3356679

Create listview in fragment android

Instead:

public class PhotosFragment extends Fragment

You can use:

public class PhotosFragment extends ListFragment

It change the methods

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ArrayList<ListviewContactItem> listContact = GetlistContact();
        setAdapter(new ListviewContactAdapter(getActivity(), listContact));
    }

onActivityCreated is void and you didn't need to return a view like in onCreateView

You can see an example here

What is the difference between window, screen, and document in Javascript?

The window is the first thing that gets loaded into the browser. This window object has the majority of the properties like length, innerWidth, innerHeight, name, if it has been closed, its parents, and more.

The document object is your html, aspx, php, or other document that will be loaded into the browser. The document actually gets loaded inside the window object and has properties available to it like title, URL, cookie, etc. What does this really mean? That means if you want to access a property for the window it is window.property, if it is document it is window.document.property which is also available in short as document.property.

How to set the id attribute of a HTML element dynamically with angularjs (1.x)?

If you use this syntax:

<div ng-attr-id="{{ 'object-' + myScopeObject.index }}"></div>

Angular will render something like:

 <div ng-id="object-1"></div>

However this syntax:

<div id="{{ 'object-' + $index }}"></div>

will generate something like:

<div id="object-1"></div>

How do I pass a string into subprocess.Popen (using the stdin argument)?

On Python 3.7+ do this:

my_data = "whatever you want\nshould match this f"
subprocess.run(["grep", "f"], text=True, input=my_data)

and you'll probably want to add capture_output=True to get the output of running the command as a string.

On older versions of Python, replace text=True with universal_newlines=True:

subprocess.run(["grep", "f"], universal_newlines=True, input=my_data)

Using msbuild to execute a File System Publish Profile

Found the answer here: http://www.digitallycreated.net/Blog/59/locally-publishing-a-vs2010-asp.net-web-application-using-msbuild

Visual Studio 2010 has great new Web Application Project publishing features that allow you to easy publish your web app project with a click of a button. Behind the scenes the Web.config transformation and package building is done by a massive MSBuild script that’s imported into your project file (found at: C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets). Unfortunately, the script is hugely complicated, messy and undocumented (other then some oft-badly spelled and mostly useless comments in the file). A big flowchart of that file and some documentation about how to hook into it would be nice, but seems to be sadly lacking (or at least I can’t find it).

Unfortunately, this means performing publishing via the command line is much more opaque than it needs to be. I was surprised by the lack of documentation in this area, because these days many shops use a continuous integration server and some even do automated deployment (which the VS2010 publishing features could help a lot with), so I would have thought that enabling this (easily!) would be have been a fairly main requirement for the feature.

Anyway, after digging through the Microsoft.Web.Publishing.targets file for hours and banging my head against the trial and error wall, I’ve managed to figure out how Visual Studio seems to perform its magic one click “Publish to File System” and “Build Deployment Package” features. I’ll be getting into a bit of MSBuild scripting, so if you’re not familiar with MSBuild I suggest you check out this crash course MSDN page.

Publish to File System

The VS2010 Publish To File System Dialog Publish to File System took me a while to nut out because I expected some sensible use of MSBuild to be occurring. Instead, VS2010 does something quite weird: it calls on MSBuild to perform a sort of half-deploy that prepares the web app’s files in your project’s obj folder, then it seems to do a manual copy of those files (ie. outside of MSBuild) into your target publish folder. This is really whack behaviour because MSBuild is designed to copy files around (and other build-related things), so it’d make sense if the whole process was just one MSBuild target that VS2010 called on, not a target then a manual copy.

This means that doing this via MSBuild on the command-line isn’t as simple as invoking your project file with a particular target and setting some properties. You’ll need to do what VS2010 ought to have done: create a target yourself that performs the half-deploy then copies the results to the target folder. To edit your project file, right click on the project in VS2010 and click Unload Project, then right click again and click Edit. Scroll down until you find the Import element that imports the web application targets (Microsoft.WebApplication.targets; this file itself imports the Microsoft.Web.Publishing.targets file mentioned earlier). Underneath this line we’ll add our new target, called PublishToFileSystem:

<Target Name="PublishToFileSystem"
        DependsOnTargets="PipelinePreDeployCopyAllFilesToOneFolder">
    <Error Condition="'$(PublishDestination)'==''"
           Text="The PublishDestination property must be set to the intended publishing destination." />
    <MakeDir Condition="!Exists($(PublishDestination))"
             Directories="$(PublishDestination)" />

    <ItemGroup>
        <PublishFiles Include="$(_PackageTempDir)\**\*.*" />
    </ItemGroup>

    <Copy SourceFiles="@(PublishFiles)"
          DestinationFiles="@(PublishFiles->'$(PublishDestination)\%(RecursiveDir)%(Filename)%(Extension)')"
          SkipUnchangedFiles="True" />
</Target>

This target depends on the PipelinePreDeployCopyAllFilesToOneFolder target, which is what VS2010 calls before it does its manual copy. Some digging around in Microsoft.Web.Publishing.targets shows that calling this target causes the project files to be placed into the directory specified by the property _PackageTempDir.

The first task we call in our target is the Error task, upon which we’ve placed a condition that ensures that the task only happens if the PublishDestination property hasn’t been set. This will catch you and error out the build in case you’ve forgotten to specify the PublishDestination property. We then call the MakeDir task to create that PublishDestination directory if it doesn’t already exist.

We then define an Item called PublishFiles that represents all the files found under the _PackageTempDir folder. The Copy task is then called which copies all those files to the Publish Destination folder. The DestinationFiles attribute on the Copy element is a bit complex; it performs a transform of the items and converts their paths to new paths rooted at the PublishDestination folder (check out Well-Known Item Metadata to see what those %()s mean).

To call this target from the command-line we can now simply perform this command (obviously changing the project file name and properties to suit you):

msbuild Website.csproj "/p:Platform=AnyCPU;Configuration=Release;PublishDestination=F:\Temp\Publish" /t:PublishToFileSystem

How to check if a socket is connected/disconnected in C#?

The best way is simply to have your client send a PING every X seconds, and for the server to assume it is disconnected after not having received one for a while.

I encountered the same issue as you when using sockets, and this was the only way I could do it. The socket.connected property was never correct.

In the end though, I switched to using WCF because it was far more reliable than sockets.

CSS fixed width in a span

The <span> tag will need to be set to display:block as it is an inline element and will ignore width.

so:

<style type="text/css"> span { width: 50px; display: block; } </style>

and then:

<li><span>&nbsp;</span>something</li>
<li><span>AND</span>something else</li>

How can I check if a view is visible or not in Android?

If the image is part of the layout it might be "View.VISIBLE" but that doesn't mean it's within the confines of the visible screen. If that's what you're after; this will work:

Rect scrollBounds = new Rect();
scrollView.getHitRect(scrollBounds);
if (imageView.getLocalVisibleRect(scrollBounds)) {
    // imageView is within the visible window
} else {
    // imageView is not within the visible window
}

Manage toolbar's navigation and back button from fragment in android

The easiest solution I found was to simply put that in your fragment :

androidx.appcompat.widget.Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            NavController navController = Navigation.findNavController(getActivity(), 
R.id.nav_host_fragment);
            navController.navigate(R.id.action_position_to_destination);
        }
    });

Personnaly I wanted to go to another page but of course you can replace the 2 lines in the onClick method by the action you want to perform.

Pandas DataFrame concat vs append

I have implemented a tiny benchmark (please find the code on Gist) to evaluate the pandas' concat and append. I updated the code snippet and the results after the comment by ssk08 - thanks alot!

The benchmark ran on a Mac OS X 10.13 system with Python 3.6.2 and pandas 0.20.3.

+--------+---------------------------------+---------------------------------+
|        | ignore_index=False              | ignore_index=True               |
+--------+---------------------------------+---------------------------------+
| size   | append | concat | append/concat | append | concat | append/concat |
+--------+--------+--------+---------------+--------+--------+---------------+
| small  | 0.4635 | 0.4891 | 94.77 %       | 0.4056 | 0.3314 | 122.39 %      |
+--------+--------+--------+---------------+--------+--------+---------------+
| medium | 0.5532 | 0.6617 | 83.60 %       | 0.3605 | 0.3521 | 102.37 %      |
+--------+--------+--------+---------------+--------+--------+---------------+
| large  | 0.9558 | 0.9442 | 101.22 %      | 0.6670 | 0.6749 | 98.84 %       |
+--------+--------+--------+---------------+--------+--------+---------------+

Using ignore_index=False append is slightly faster, with ignore_index=True concat is slightly faster.

tl;dr No significant difference between concat and append.

What does MVW stand for?

Having said, I'd rather see developers build kick-ass apps that are well-designed and follow separation of concerns, than see them waste time arguing about MV* nonsense. And for this reason, I hereby declare AngularJS to be MVW framework - Model-View-Whatever. Where Whatever stands for "whatever works for you".

Credits : AngularJS Post - Igor Minar

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

The other answers are excellent and I just want to provide a straight forward answer to this. Just limiting to jQuery asynchronous calls

All ajax calls (including the $.get or $.post or $.ajax) are asynchronous.

Considering your example

var outerScopeVar;  //line 1
$.post('loldog', function(response) {  //line 2
    outerScopeVar = response;
});
alert(outerScopeVar);  //line 3

The code execution starts from line 1, declares the variable and triggers and asynchronous call on line 2, (i.e., the post request) and it continues its execution from line 3, without waiting for the post request to complete its execution.

Lets say that the post request takes 10 seconds to complete, the value of outerScopeVar will only be set after those 10 seconds.

To try out,

var outerScopeVar; //line 1
$.post('loldog', function(response) {  //line 2, takes 10 seconds to complete
    outerScopeVar = response;
});
alert("Lets wait for some time here! Waiting is fun");  //line 3
alert(outerScopeVar);  //line 4

Now when you execute this, you would get an alert on line 3. Now wait for some time until you are sure the post request has returned some value. Then when you click OK, on the alert box, next alert would print the expected value, because you waited for it.

In real life scenario, the code becomes,

var outerScopeVar;
$.post('loldog', function(response) {
    outerScopeVar = response;
    alert(outerScopeVar);
});

All the code that depends on the asynchronous calls, is moved inside the asynchronous block, or by waiting on the asynchronous calls.

Best way to compare dates in Android

Update: The Joda-Time library is now in maintenance-mode, and recommends migrating to the java.time framework that succeeds it. See the Answer by Ole V.V..


Joda-Time

The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Use either Joda-Time or the new java.time package in Java 8.

LocalDate

If you want date-only without time-of-day, then use the LocalDate class.

Time Zone

Getting the current date depends on the time zone. A new date rolls over in Paris before Montréal. Specify the desired time zone rather than depend on the JVM's default.

Example in Joda-Time 2.3.

DateTimeFormat formatter = DateTimeFormat.forPattern( "d/M/yyyy" );
LocalDate localDate = formatter.parseLocalDate( "1/1/1990" );
boolean outdated = LocalDate.now( DateTimeZone.UTC ).isAfter( localDate );

Remove duplicates from a dataframe in PySpark

It is not an import problem. You simply call .dropDuplicates() on a wrong object. While class of sqlContext.createDataFrame(rdd1, ...) is pyspark.sql.dataframe.DataFrame, after you apply .collect() it is a plain Python list, and lists don't provide dropDuplicates method. What you want is something like this:

 (df1 = sqlContext
     .createDataFrame(rdd1, ['column1', 'column2', 'column3', 'column4'])
     .dropDuplicates())

 df1.collect()

What is the difference between ELF files and bin files?

some resources:

  1. ELF for the ARM architecture
    http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf
  2. ELF from wiki
    http://en.wikipedia.org/wiki/Executable_and_Linkable_Format

ELF format is generally the default output of compiling. if you use GNU tool chains, you can translate it to binary format by using objcopy, such as:

  arm-elf-objcopy -O binary [elf-input-file] [binary-output-file]

or using fromELF utility(built in most IDEs such as ADS though):

 fromelf -bin -o [binary-output-file] [elf-input-file]

In PANDAS, how to get the index of a known value?

I think this may help you , both index and columns of the values.

value you are looking for is not duplicated:

poz=matrix[matrix==minv].dropna(axis=1,how='all').dropna(how='all')
value=poz.iloc[0,0]
index=poz.index.item()
column=poz.columns.item()

you can get its index and column

duplicated:

matrix=pd.DataFrame([[1,1],[1,np.NAN]],index=['q','g'],columns=['f','h'])
matrix
Out[83]: 
   f    h
q  1  1.0
g  1  NaN
poz=matrix[matrix==minv].dropna(axis=1,how='all').dropna(how='all')
index=poz.stack().index.tolist()
index
Out[87]: [('q', 'f'), ('q', 'h'), ('g', 'f')]

you will get a list

calculate the mean for each column of a matrix in R

In case you have NA's:

sapply(data, mean, na.rm = T)      # Returns a vector (with names)   
lapply(data, mean, na.rm = T)      # Returns a list  

Remember that "mean" needs numeric data. If you have mixed class data, then use:

numdata<-data[sapply(data, is.numeric)]  
sapply(numdata, mean, na.rm = T)  # Returns a vector
lapply(numdata, mean, na.rm = T)  # Returns a list  

Regular expression for only characters a-z, A-Z

/^[a-zA-Z]+$/ 

Off the top of my head.

Edit:

Or if you don't like the weird looking literal syntax you can do it like this

new RegExp("^[a-zA-Z]+$");

Call child method from parent

You can apply that logic very easily using your child component as a react custom hook.

How to implement it?

  • Your child returns a function.

  • Your child returns a JSON: {function, HTML, or other values} as the example.

In the example doesn't make sense to apply this logic but it is easy to see:

_x000D_
_x000D_
const {useState} = React;

//Parent
const Parent = () => {
  //custome hook
  const child = useChild();

  return (
    <div>
      {child.display}          
      <button onClick={child.alert}>
        Parent call child
      </button>
      {child.btn}
    </div>
  );
};

//Child
const useChild = () => {

  const [clickCount, setClick] = React.useState(0);
  
  {/* child button*/} 
  const btn = (
    <button
      onClick={() => {
        setClick(clickCount + 1);
      }}
    >
      Click me
    </button>
  );

  return {
    btn: btn,
    //function called from parent 
    alert: () => {
      alert("You clicked " + clickCount + " times");
    },
    display: <h1>{clickCount}</h1>
  };
};

const rootElement = document.getElementById("root");
ReactDOM.render(<Parent />, rootElement);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
_x000D_
_x000D_
_x000D_

Lists: Count vs Count()

Count() is an extension method introduced by LINQ while the Count property is part of the List itself (derived from ICollection). Internally though, LINQ checks if your IEnumerable implements ICollection and if it does it uses the Count property. So at the end of the day, there's no difference which one you use for a List.

To prove my point further, here's the code from Reflector for Enumerable.Count()

public static int Count<TSource>(this IEnumerable<TSource> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    ICollection<TSource> is2 = source as ICollection<TSource>;
    if (is2 != null)
    {
        return is2.Count;
    }
    int num = 0;
    using (IEnumerator<TSource> enumerator = source.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            num++;
        }
    }
    return num;
}

Postgres: clear entire database before re-creating / re-populating from bash script

To dump:

pg_dump -Fc mydb > db.dump

To restore:

pg_restore --verbose --clean --no-acl --no-owner -h localhost -U myuser -d my_db db/latest.dump

Linux command to translate DomainName to IP

You can use:

nslookup www.example.com

Script to Change Row Color when a cell changes text

user2532030's answer is the correct and most simple answer.

I just want to add, that in the case, where the value of the determining cell is not suitable for a RegEx-match, I found the following syntax to work the same, only with numerical values, relations et.c.:

[Custom formula is]
=$B$2:$B = "Complete"
Range: A2:Z1000

If column 2 of any row (row 2 in script, but the leading $ means, this could be any row) textually equals "Complete", do X for the Range of the entire sheet (excluding header row (i.e. starting from A2 instead of A1)).

But obviously, this method allows also for numerical operations (even though this does not apply for op's question), like:

=$B$2:$B > $C$2:$C

So, do stuff, if the value of col B in any row is higher than col C value.

One last thing: Most likely, this applies only to me, but I was stupid enough to repeatedly forget to choose Custom formula is in the drop-down, leaving it at Text contains. Obviously, this won't float...

Check if table exists in SQL Server

IF EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE 
TABLE_CATALOG = 'Database Name' and
TABLE_NAME = 'Table Name' and 
TABLE_SCHEMA = 'Schema Name') -- Database and Schema name in where statement can be deleted

BEGIN
--TABLE EXISTS
END

ELSE BEGIN
--TABLE DOES NOT EXISTS
END

JSON formatter in C#?

All credits are to Frank Tzanabetis. However this is the shortest direct example, that also survives in case of empty string or broken original JSON string:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

    ...
    try
    {
        return JToken.Parse(jsonString).ToString(Formatting.Indented);
    }
    catch
    {
        return jsonString;

generate a random number between 1 and 10 in c

Generating a single random number in a program is problematic. Random number generators are only "random" in the sense that repeated invocations produce numbers from a given probability distribution.

Seeding the RNG won't help, especially if you just seed it from a low-resolution timer. You'll just get numbers that are a hash function of the time, and if you call the program often, they may not change often. You might improve a little bit by using srand(time(NULL) + getpid()) (_getpid() on Windows), but that still won't be random.

The ONLY way to get numbers that are random across multiple invocations of a program is to get them from outside the program. That means using a system service such as /dev/random (Linux) or CryptGenRandom() (Windows), or from a service like random.org.

How to set image in imageview in android?

1> You can add image from layout itself:

<ImageView
                android:id="@+id/iv_your_image"
                android:layout_width="wrap_content"
                android:layout_height="25dp"
                android:background="@mipmap/your_image"
                android:padding="2dp" />

OR

2> Programmatically in java class:

ImageView ivYouImage= (ImageView)findViewById(R.id.iv_your_image);
        ivYouImage.setImageResource(R.mipmap.ic_changeImage);

OR for fragments:

View rowView= inflater.inflate(R.layout.your_layout, null, true);

ImageView ivYouImage= (ImageView) rowView.findViewById(R.id.iv_your_image);
        ivYouImage.setImageResource(R.mipmap.ic_changeImage);

Color Tint UIButton Image

For Xamarin.iOS (C#):

UIButton messagesButton = new UIButton(UIButtonType.Custom);
UIImage icon = UIImage.FromBundle("Images/icon.png");
messagesButton.SetImage(icon.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), UIControlState.Normal);
messagesButton.TintColor = UIColor.White;
messagesButton.Frame = new RectangleF(0, 0, 25, 25);

How to get selected value from Dropdown list in JavaScript

According to Html5 specs you should use -- element.options[e.selectedIndex].text

e.g. if you have select box like below :

<select id="selectbox1">
    <option value="1">First</option>
    <option value="2" selected="selected">Second</option>
    <option value="3">Third</option>
</select>
<br/>
<button onClick="GetItemValue('selectbox1');">Get Item</button>

you can get value using following script :

<script>
 function GetItemValue(q) {
   var e = document.getElementById(q);
   var selValue = e.options[e.selectedIndex].text ;
   alert("Selected Value: "+selValue);
 }
</script>

Tried and tested.

Regex Letters, Numbers, Dashes, and Underscores

Just escape the dashes to prevent them from being interpreted (I don't think underscore needs escaping, but it can't hurt). You don't say which regex you are using.

([A-Za-z0-9\-\_]+)

Get records with max value for each group of grouped SQL results

Improving axiac's solution to avoid selecting multiple rows per group while also allowing for use of indexes

SELECT o.*
FROM `Persons` o 
  LEFT JOIN `Persons` b 
      ON o.Group = b.Group AND o.Age < b.Age
  LEFT JOIN `Persons` c 
      ON o.Group = c.Group AND o.Age = c.Age and o.id < c.id
WHERE b.Age is NULL and c.id is null

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

For things to compile via command line I needed to include the maven repo in BOTH buildscript and allprojects.

root build.gradle:

buildscript {
    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha2'
        ...
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }
    }
}

It's needed in the buildscript block to find the AGP, and in allprojects block to find android.arch and com.android.databinding packages (and others)

UPDATE: It looks like the new repo is just called google() but I still needed to declare it in both places.

Oracle SqlPlus - saving output in a file but don't show on screen

Try This:

sqlplus -s ${ORA_CONN_STR} <<EOF >/dev/null

how to call a method in another Activity from Activity

You should not create an instance of the activity class. It is wrong. Activity has ui and lifecycle and activity is started by startActivity(intent)

You can use startActivityForResult or you can pass the values from one activity to another using intents and do what is required. But it depends on what you intend to do in the method.

Java get String CompareTo as a comparator object

Also, if you want case-insensitive comparison, in recent versions of Java the String class contains a public static final field called CASE_INSENSITIVE_ORDER which is of type Comparator<String>, as I just recently found out. So, you can get your job done using String.CASE_INSENSITIVE_ORDER.

Get IP address of visitors using Flask for Python

Actually, what you will find is that when simply getting the following will get you the server's address:

request.remote_addr

If you want the clients IP address, then use the following:

request.environ['REMOTE_ADDR']

Function to check if a string is a date

If your heart is set on using regEx then txt2re.com is always a good resource:

<?php

  $txt='2012-06-14 01:46:28';
  $re1='((?:2|1)\\d{3}(?:-|\\/)(?:(?:0[1-9])|(?:1[0-2]))(?:-|\\/)(?:(?:0[1-9])|(?:[1-2][0-9])|(?:3[0-1]))(?:T|\\s)(?:(?:[0-1][0-9])|(?:2[0-3])):(?:[0-5][0-9]):(?:[0-5][0-9]))';    # Time Stamp 1

  if ($c=preg_match_all ("/".$re1."/is", $txt, $matches))
  {
      $timestamp1=$matches[1][0];
      print "($timestamp1) \n";
  }

?>

How would I get a cron job to run every 30 minutes?

Try this:

0,30 * * * * your command goes here

According to the official Mac OS X crontab(5) manpage, the / syntax is supported. Thus, to figure out why it wasn't working for you, you'll need to look at the logs for cron. In those logs, you should find a clear failure message.

Note: Mac OS X appears to use Vixie Cron, the same as Linux and the BSDs.

What are the differences between .gitignore and .gitkeep?

.gitignore

is a text file comprising a list of files in your directory that git will ignore or not add/update in the repository.

.gitkeep

Since Git removes or doesn't add empty directories to a repository, .gitkeep is sort of a hack (I don't think it's officially named as a part of Git) to keep empty directories in the repository.

Just do a touch /path/to/emptydirectory/.gitkeep to add the file, and Git will now be able to maintain this directory in the repository.

Dynamically create checkbox with JQuery from text input

<div id="cblist">
    <input type="checkbox" value="first checkbox" id="cb1" /> <label for="cb1">first checkbox</label>
</div>

<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />

<script type="text/javascript">
$(document).ready(function() {
    $('#btnSave').click(function() {
        addCheckbox($('#txtName').val());
    });
});

function addCheckbox(name) {
   var container = $('#cblist');
   var inputs = container.find('input');
   var id = inputs.length+1;

   $('<input />', { type: 'checkbox', id: 'cb'+id, value: name }).appendTo(container);
   $('<label />', { 'for': 'cb'+id, text: name }).appendTo(container);
}
</script>

Two inline-block, width 50% elements wrap to second line

inline and inline-block elements are affected by whitespace in the HTML.

The simplest way to fix your problem is to remove the whitespace between </div> and <div id="col2">, see: http://jsfiddle.net/XCDsu/15/

There are other possible solutions, see: bikeshedding CSS3 property alternative?

MongoDB: Is it possible to make a case-insensitive query?

The best method is in your language of choice, when creating a model wrapper for your objects, have your save() method iterate through a set of fields that you will be searching on that are also indexed; those set of fields should have lowercase counterparts that are then used for searching.

Every time the object is saved again, the lowercase properties are then checked and updated with any changes to the main properties. This will make it so you can search efficiently, but hide the extra work needed to update the lc fields each time.

The lower case fields could be a key:value object store or just the field name with a prefixed lc_. I use the second one to simplify querying (deep object querying can be confusing at times).

Note: you want to index the lc_ fields, not the main fields they are based off of.

How to insert multiple rows from array using CodeIgniter framework?

Well, you don't want to execute 1000 query calls, but doing this is fine:

$stmt= array( 'array of statements' );
$query= 'INSERT INTO yourtable (col1,col2,col3) VALUES ';
foreach( $stmt AS $k => $v ) {
  $query.= '(' .$v. ')'; // NOTE: you'll have to change to suit
  if ( $k !== sizeof($stmt)-1 ) $query.= ', ';
}
$r= mysql_query($query);

Depending on your data source, populating the array might be as easy as opening a file and dumping the contents into an array via file().

How can I completely remove TFS Bindings

In visual studio 2015,

  1. Unbind the solution and project by File->Source Control->Advanced->Change Source Control
  2. Remove the cache in C:\Users\<user>\AppData\Local\Microsoft\Team Foundation\6.0

Android: show soft keyboard automatically when focus is on an EditText

Take a look at this discussion which handles manually hiding and showing the IME. However, my feeling is that if a focused EditText is not bringing the IME up it is because you are calling AlertDialog.show() in your OnCreate() or some other method which is evoked before the screen is actually presented. Moving it to OnPostResume() should fix it in that case I believe.

Extract the last substring from a cell

Try this function in Excel:

Public Shared Function SPLITTEXT(Text As String, SplitAt As String, ReturnZeroBasedIndex As Integer) As String
        Dim s() As String = Split(Text, SplitAt)
        If ReturnZeroBasedIndex <= s.Count - 1 Then
            Return s(ReturnZeroBasedIndex)
        Else
            Return ""
        End If
    End Function

You use it like this:

First Name (A1) | Last Name (A2)

Value in cell A1 = Michael Zomparelli

I want the last name in column A2.

=SPLITTEXT(A1, " ", 1)

The last param is the zero-based index you want to return. So if you split on the space char then index 0 = Michael and index 1 = Zomparelli

The above function is a .Net function, but can easily be converted to VBA.

Get selected text from a drop-down list (select box) using jQuery

Use:

('#yourdropdownid').find(':selected').text();

How do I get the App version and build number using Swift?

For Swift 2.0

//First get the nsObject by defining as an optional anyObject

let nsObject: AnyObject? = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"]
let version = nsObject as! String

How do I find the location of Python module sources?

The sys.path list contains the list of directories which will be searched for modules at runtime:

python -v
>>> import sys
>>> sys.path
['', '/usr/local/lib/python25.zip', '/usr/local/lib/python2.5', ... ]

Change background image opacity

Nowadays, it is possible to do it simply with CSS property "background-blend-mode".

<div id="content">Only one div needed</div>

div#content {
    background-image: url(my_image.png);
    background-color: rgba(255,255,255,0.6);
    background-blend-mode: lighten;
    /* You may add things like width, height, background-size... */
}

It will blend the background-color (which is white, 0.6 opacity) into the background image. Learn more here (W3S).

What does (function($) {})(jQuery); mean?

Firstly, a code block that looks like (function(){})() is merely a function that is executed in place. Let's break it down a little.

1. (
2.    function(){}
3. )
4. ()

Line 2 is a plain function, wrapped in parenthesis to tell the runtime to return the function to the parent scope, once it's returned the function is executed using line 4, maybe reading through these steps will help

1. function(){ .. }
2. (1)
3. 2()

You can see that 1 is the declaration, 2 is returning the function and 3 is just executing the function.

An example of how it would be used.

(function(doc){

   doc.location = '/';

})(document);//This is passed into the function above

As for the other questions about the plugins:

Type 1: This is not a actually a plugin, it's an object passed as a function, as plugins tend to be functions.

Type 2: This is again not a plugin as it does not extend the $.fn object. It's just an extenstion of the jQuery core, although the outcome is the same. This is if you want to add traversing functions such as toArray and so on.

Type 3: This is the best method to add a plugin, the extended prototype of jQuery takes an object holding your plugin name and function and adds it to the plugin library for you.

Functional, Declarative, and Imperative Programming

I think that your taxonomy is incorrect. There are two opposite types imperative and declarative. Functional is just a subtype of declarative. BTW, wikipedia states the same fact.

Adding Table rows Dynamically in Android

You can use an inflater with TableRow:

for (int i = 0; i < months; i++) {
    
    View view = getLayoutInflater ().inflate (R.layout.list_month_data, null, false);
        
    TextView textView = view.findViewById (R.id.title);
    
    textView.setText ("Text");
        
    tableLayout.addView (view);
    
}

Layout:

<TableRow
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_centerInParent="true"
    android:gravity="center_horizontal"
    android:paddingTop="15dp"
    android:paddingRight="15dp"
    android:paddingLeft="15dp"
    android:paddingBottom="10dp"
    >
    
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:gravity="center"
        />
    
</TableRow>

Using UPDATE in stored procedure with optional parameters

UPDATE tbl_ClientNotes 
SET ordering=@ordering, title=@title, content=@content 
WHERE id=@id 
AND @ordering IS NOT NULL
AND @title IS NOT NULL
AND @content IS NOT NULL

Or if you meant you only want to update individual columns you would use the post above mine. I read it as do not update if any values are null

How to get json key and value in javascript?

It looks like data not contains what you think it contains - check it.

_x000D_
_x000D_
let data={"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"};_x000D_
_x000D_
console.log( data["jobtitel"] );_x000D_
console.log( data.jobtitel );
_x000D_
_x000D_
_x000D_

getting the ng-object selected with ng-change

Instead of setting the ng-model to item.size.code, how about setting it to size:

<select ng-options="size as size.name for size in sizes" 
   ng-model="item" ng-change="update()"></select>

Then in your update() method, $scope.item will be set to the currently selected item.

And whatever code needed item.size.code, can get that property via $scope.item.code.

Fiddle.

Update based on more info in comments:

Use some other $scope property for your select ng-model then:

<select ng-options="size as size.name for size in sizes" 
   ng-model="selectedItem" ng-change="update()"></select>

Controller:

$scope.update = function() {
   $scope.item.size.code = $scope.selectedItem.code
   // use $scope.selectedItem.code and $scope.selectedItem.name here
   // for other stuff ...
}

ERROR 1396 (HY000): Operation CREATE USER failed for 'jack'@'localhost'

I had also faced the same issue, after few searches, I found a solution that worked for me.I hope it will help you. As you have already created users, now try to do a FLUSH PRIVILEGES on your Mysql console. This issue is already in MySql bug post.You can also check this one.Now after flushing, you can create a new user. follow below Steps:

Step-1: Open terminal Ctrl+Alt+T
Step-2: mysql -u root -p  , it will ask for your MySQL password.

Now you can able to see Mysql console.

Step-3: CREATE USER 'username'@'host' IDENTIFIED by 'PASSWORD';

Instead of username you can put username you want. If you are running Mysql on your local machine, then type "localhost" instead of the host, otherwise give your server name you want to access.

Ex: CREATE USER smruti@localhost IDENTIFIED by 'hello';

Now new user is created. If you want to give all access then type

GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';

Now you can quit the MySQL by typing \q.Now once again login through

mysql -u newusername -p , then press Enter. You can see everything.

Hope this helps.

ERROR: Cannot open source file " "

Let Unreal do the job. Close all, Right click your Project File (.uproject),
"Generate VisualStudio Project Files".

Get final URL after curl is redirected

The parameters -L (--location) and -I (--head) still doing unnecessary HEAD-request to the location-url.

If you are sure that you will have no more than one redirect, it is better to disable follow location and use a curl-variable %{redirect_url}.

This code do only one HEAD-request to the specified URL and takes redirect_url from location-header:

curl --head --silent --write-out "%{redirect_url}\n" --output /dev/null "https://""goo.gl/QeJeQ4"

Speed test

all_videos_link.txt - 50 links of goo.gl+bit.ly which redirect to youtube

1. With follow location

time while read -r line; do
    curl -kIsL -w "%{url_effective}\n" -o /dev/null  $line
done < all_videos_link.txt

Results:

real    1m40.832s
user    0m9.266s
sys     0m15.375s

2. Without follow location

time while read -r line; do
    curl -kIs -w "%{redirect_url}\n" -o /dev/null  $line
done < all_videos_link.txt

Results:

real    0m51.037s
user    0m5.297s
sys     0m8.094s

For each row return the column name of the largest value

A simple for loop can also be handy:

> df<-data.frame(V1=c(2,8,1),V2=c(7,3,5),V3=c(9,6,4))
> df
  V1 V2 V3
1  2  7  9
2  8  3  6
3  1  5  4
> df2<-data.frame()
> for (i in 1:nrow(df)){
+   df2[i,1]<-colnames(df[which.max(df[i,])])
+ }
> df2
  V1
1 V3
2 V1
3 V2

How to write Unicode characters to the console?

I found some elegant solution on MSDN

System.Console.Write('\uXXXX') //XXXX is hex Unicode for character

This simple program writes ? right on the screen.

using System;

public class Test
{
    public static void Main()
    {
        Console.Write('\u2103'); //? character code
    }
}

AttributeError: 'module' object has no attribute 'model'

I realized that by looking at the stack trace it was trying to load my own script in place of another module called the same way,i.e., my script was called random.py and when a module i used was trying to import the "random" package, it was loading my script causing a circular reference and so i renamed it and deleted a .pyc file it had created from the working folder and things worked just fine.

Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

To use arrow functions with function.prototype.call, I made a helper function on the object prototype:

  // Using
  // @func = function() {use this here} or This => {use This here}
  using(func) {
    return func.call(this, this);
  }

usage

  var obj = {f:3, a:2}
  .using(This => This.f + This.a) // 5

Edit

You don't NEED a helper. You could do:

var obj = {f:3, a:2}
(This => This.f + This.a).call(undefined, obj); // 5

How to make a div with no content have a width?

Either use padding , height or &nbsp for width to take effect with empty div

EDIT:

Non zero min-height also works great

Verilog: How to instantiate a module

Be sure to check out verilog-mode and especially verilog-auto. http://www.veripool.org/wiki/verilog-mode/ It is a verilog mode for emacs, but plugins exist for vi(m?) for example.

An instantiation can be automated with AUTOINST. The comment is expanded with M-x verilog-auto and can afterwards be manually edited.

subcomponent subcomponent_instance_name(/*AUTOINST*/);

Expanded

subcomponent subcomponent_instance_name (/*AUTOINST*/
  //Inputs
  .clk,         (clk)           
  .rst_n,       (rst_n)
  .data_rx      (data_rx_1[9:0]),
  //Outputs
  .data_tx      (data_tx[9:0])
);

Implicit wires can be automated with /*AUTOWIRE*/. Check the link for further information.

What is the meaning of CTOR?

It's just shorthand for "constructor" - and it's what the constructor is called in IL, too. For example, open up Reflector and look at a type and you'll see members called .ctor for the various constructors.

How to validate an Email in PHP?

This is old post but I will share one my solution because noone mention here one problem before.

New email address can contain UTF-8 characters or special domain names like .live, .news etc.

Also I find that some email address can be on Cyrilic and on all cases standard regex or filter_var() will fail.

That's why I made an solution for it:

function valid_email($email) 
{
    if(is_array($email) || is_numeric($email) || is_bool($email) || is_float($email) || is_file($email) || is_dir($email) || is_int($email))
        return false;
    else
    {
        $email=trim(strtolower($email));
        if(filter_var($email, FILTER_VALIDATE_EMAIL)!==false) return $email;
        else
        {
            $pattern = '/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD';
            return (preg_match($pattern, $email) === 1) ? $email : false;
        }
    }
}

This function work perfectly for all cases and email formats.

Unit testing private methods in C#

Extract private method to another class, test on that class; read more about SRP principle (Single Responsibility Principle)

It seem that you need extract to the private method to another class; in this should be public. Instead of trying to test on the private method, you should test public method of this another class.

We has the following scenario:

Class A
+ outputFile: Stream
- _someLogic(arg1, arg2) 

We need to test the logic of _someLogic; but it seem that Class A take more role than it need(violate the SRP principle); just refactor into two classes

Class A1
    + A1(logicHandler: A2) # take A2 for handle logic
    + outputFile: Stream
Class A2
    + someLogic(arg1, arg2) 

In this way someLogic could be test on A2; in A1 just create some fake A2 then inject to constructor to test that A2 is called to the function named someLogic.

What is the "Upgrade-Insecure-Requests" HTTP header?

Short answer: it's closely related to the Content-Security-Policy: upgrade-insecure-requests response header, indicating that the browser supports it (and in fact prefers it).

It took me 30mins of Googling, but I finally found it buried in the W3 spec.

The confusion comes because the header in the spec was HTTPS: 1, and this is how Chromium implemented it, but after this broke lots of websites that were poorly coded (particularly WordPress and WooCommerce) the Chromium team apologized:

"I apologize for the breakage; I apparently underestimated the impact based on the feedback during dev and beta."
— Mike West, in Chrome Issue 501842

Their fix was to rename it to Upgrade-Insecure-Requests: 1, and the spec has since been updated to match.

Anyway, here is the explanation from the W3 spec (as it appeared at the time)...

The HTTPS HTTP request header field sends a signal to the server expressing the client’s preference for an encrypted and authenticated response, and that it can successfully handle the upgrade-insecure-requests directive in order to make that preference as seamless as possible to provide.

...

When a server encounters this preference in an HTTP request’s headers, it SHOULD redirect the user to a potentially secure representation of the resource being requested.

When a server encounters this preference in an HTTPS request’s headers, it SHOULD include a Strict-Transport-Security header in the response if the request’s host is HSTS-safe or conditionally HSTS-safe [RFC6797].

Alter column, add default constraint

you can wrap reserved words in square brackets to avoid these kinds of errors:

dbo.TableName.[Date]

How do I remove whitespace from the end of a string in Python?

>>> "    xyz     ".rstrip()
'    xyz'

There is more about rstrip in the documentation.

How to implement HorizontalScrollView like Gallery?

I implemented something similar with Horizontal Variable ListView The only drawback is, it works only with Android 2.3 and later.

Using this library is as simple as implementing a ListView with a corresponding Adapter. The library also provides an example

How do I discard unstaged changes in Git?

Just use:

git stash -k -u

This will stash unstaged changes and untracked files (new files) and keep staged files.

It's better than reset/checkout/clean, because you might want them back later (by git stash pop). Keeping them in the stash is better than discarding them.

Difference between filter and filter_by in SQLAlchemy

filter_by uses keyword arguments, whereas filter allows pythonic filtering arguments like filter(User.name=="john")

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

For mine, Resetting content and settings of Simulator works. To reset the simulator follow the steps:

iOS Simulator -> Reset Content and Settings -> Press Reset (on the warning which will come)

How to cancel a local git commit

Use --soft instead of --hard flag:

git reset --soft HEAD^

How do the post increment (i++) and pre increment (++i) operators work in Java?

Pre-increment means that the variable is incremented BEFORE it's evaluated in the expression. Post-increment means that the variable is incremented AFTER it has been evaluated for use in the expression.

Therefore, look carefully and you'll see that all three assignments are arithmetically equivalent.

Change directory in Node.js command prompt

  1. Open file nodevars.bat
  2. Just add your path to the end, "%HOMEDRIVE%%HOMEPATH% /file1/file2/file3
  3. Save file nodevars.bat

This work even with Swedish words

Couldn't connect to server 127.0.0.1:27017

Try running mongod before mongo.

sudo /usr/sbin/mongod on my opensuse

This solved my problem,

Finding the next available id in MySQL

If this is used in conjunction for INSERTING a new record you could use something like this.

(You've stated in your comments that the id is auto incrementing and the other table needs the next ID + 1)

INSERT INTO TABLE2 (id, field1, field2, field3, etc) 
VALUES(
   SELECT (MAX(id) + 1), field1, field2, field3, etc FROM TABLE1
   WHERE condition_here_if_needed
)

This is pseudocode but you get the idea

Is there a Google Voice API?

There is a C# Google Voice API... there is limited documentation, however the download has an application that 'works' using the API that is included:

https://sourceforge.net/projects/gvoicedotnet/

Simple dynamic breadcrumb

Here is a great simple dynamic breadcrumb (tweak as needed):

    <?php 
    $docroot = "/zen/index5.php";
    $path =($_SERVER['REQUEST_URI']);
    $names = explode("/", $path); 
    $trimnames = array_slice($names, 1, -1);
    $length = count($trimnames)-1;
    $fixme = array(".php","-","myname");
    $fixes = array(""," ","My<strong>Name</strong>");
    echo '<div id="breadwrap"><ol id="breadcrumb">';
    $url = "";
    for ($i = 0; $i <= $length;$i++){
    $url .= $trimnames[$i]."/";
        if($i>0 && $i!=$length){
            echo '<li><a href="/'.$url.'">'.ucfirst(str_replace($fixme,$fixes,$trimnames[$i]) . ' ').'</a></li>';
    }
    elseif ($i == $length){
        echo '<li class="current">'.ucfirst(str_replace($fixme,$fixes,$trimnames[$i]) . ' ').'</li>';       
    }
    else{
        echo $trimnames[$i]='<li><a href='.$docroot.' id="bread-home"><span>&nbsp;</span></a></li>';
    }
}
echo '</ol>';
?>

Extract names of objects from list

Making a small tweak to the inside function and using lapply on an index instead of the actual list itself gets this doing what you want

x <- c("yes", "no", "maybe", "no", "no", "yes")
y <- c("red", "blue", "green", "green", "orange")
list.xy <- list(x=x, y=y)

WORD.C <- function(WORDS){
  require(wordcloud)

  L2 <- lapply(WORDS, function(x) as.data.frame(table(x), stringsAsFactors = FALSE))

  # Takes a dataframe and the text you want to display
  FUN <- function(X, text){
    windows() 
    wordcloud(X[, 1], X[, 2], min.freq=1)
    mtext(text, 3, padj=-4.5, col="red")  #what I'm trying that isn't working
  }

  # Now creates the sequence 1,...,length(L2)
  # Loops over that and then create an anonymous function
  # to send in the information you want to use.
  lapply(seq_along(L2), function(i){FUN(L2[[i]], names(L2)[i])})

  # Since you asked about loops
  # you could use i in seq_along(L2) 
  # instead of 1:length(L2) if you wanted to
  #for(i in 1:length(L2)){
  #  FUN(L2[[i]], names(L2)[i])
  #}
}

WORD.C(list.xy)

Get the element with the highest occurrence in an array

function mode(){
  var input = $("input").val().split(",");
  var mode = [];
  var m = [];
  var p = [];
    for(var x = 0;x< input.length;x++){
      if(m.indexOf(input[x])==-1){
        m[m.length]=input[x];
    }}
  for(var x = 0; x< m.length;x++){
    p[x]=0;
    for(var y = 0; y<input.length;y++){
      if(input[y]==m[x]){
      p[x]++; 
 }}}
 for(var x = 0;x< p.length;x++){
   if(p[x] ==(Math.max.apply(null, p))){
     mode.push(m[x]);
 }} 
$("#output").text(mode);}

SQL Server : check if variable is Empty or NULL for WHERE clause

If you can use some dynamic query, you can use LEN . It will give false on both empty and null string. By this way you can implement the option parameter.

ALTER PROCEDURE [dbo].[psProducts] 
(@SearchType varchar(50))
AS
BEGIN
    SET NOCOUNT ON;

DECLARE @Query nvarchar(max) = N'
    SELECT 
        P.[ProductId],
        P.[ProductName],
        P.[ProductPrice],
        P.[Type]
    FROM [Product] P'
    -- if @Searchtype is not null then use the where clause
    SET @Query = CASE WHEN LEN(@SearchType) > 0 THEN @Query + ' WHERE p.[Type] = ' + ''''+ @SearchType + '''' ELSE @Query END   

    EXECUTE sp_executesql @Query
    PRINT @Query
END

What does the term "canonical form" or "canonical representation" in Java mean?

Wikipedia points to the term Canonicalization.

A process for converting data that has more than one possible representation into a "standard" canonical representation. This can be done to compare different representations for equivalence, to count the number of distinct data structures, to improve the efficiency of various algorithms by eliminating repeated calculations, or to make it possible to impose a meaningful sorting order.

The Unicode example made the most sense to me:

Variable-length encodings in the Unicode standard, in particular UTF-8, have more than one possible encoding for most common characters. This makes string validation more complicated, since every possible encoding of each string character must be considered. A software implementation which does not consider all character encodings runs the risk of accepting strings considered invalid in the application design, which could cause bugs or allow attacks. The solution is to allow a single encoding for each character. Canonicalization is then the process of translating every string character to its single allowed encoding. An alternative is for software to determine whether a string is canonicalized, and then reject it if it is not. In this case, in a client/server context, the canonicalization would be the responsibility of the client.

In summary, a standard form of representation for data. From this form you can then convert to any representation you may need.

How to update column value in laravel

You may try this:

Page::where('id', $id)->update(array('image' => 'asdasd'));

There are other ways too but no need to use Page::find($id); in this case. But if you use find() then you may try it like this:

$page = Page::find($id);

// Make sure you've got the Page model
if($page) {
    $page->image = 'imagepath';
    $page->save();
}

Also you may use:

$page = Page::findOrFail($id);

So, it'll throw an exception if the model with that id was not found.

Change HTML email body font type and size in VBA

FYI I did a little research as well and if the name of the font-family you want to apply contains spaces (as an example I take Gill Alt One MT Light), you should write it this way :

strbody= "<BODY style=" & Chr(34) & "font-family:Gill Alt One MT Light" & Chr(34) & ">" & YOUR_TEXT & "</BODY>"

How to sort in mongoose?

This is what i did, it works fine.

User.find({name:'Thava'}, null, {sort: { name : 1 }})

PHP - iterate on string characters

For those who are looking for the fastest way to iterate over strings in php, Ive prepared a benchmark testing.
The first method in which you access string characters directly by specifying its position in brackets and treating string like an array:

$string = "a sample string for testing";
$char = $string[4] // equals to m

I myself thought the latter is the fastest method, but I was wrong.
As with the second method (which is used in the accepted answer):

$string = "a sample string for testing";
$string = str_split($string);
$char = $string[4] // equals to m

This method is going to be faster cause we are using a real array and not assuming one to be an array.

Calling the last line of each of the above methods for 1000000 times lead to these benchmarking results:

Using string[i]
0.24960017204285 Seconds

Using str_split
0.18720006942749 Seconds

Which means the second method is way faster.

Autoreload of modules in IPython

As mentioned above, you need the autoreload extension. If you want it to automatically start every time you launch ipython, you need to add it to the ipython_config.py startup file:

It may be necessary to generate one first:

ipython profile create

Then include these lines in ~/.ipython/profile_default/ipython_config.py:

c.InteractiveShellApp.exec_lines = []
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')

As well as an optional warning in case you need to take advantage of compiled Python code in .pyc files:

c.InteractiveShellApp.exec_lines.append('print "Warning: disable autoreload in ipython_config.py to improve performance." ')

edit: the above works with version 0.12.1 and 0.13

How do you properly return multiple values from a Promise?

Simply make an object and extract arguments from that object.

let checkIfNumbersAddToTen = function (a, b) {
return new Promise(function (resolve, reject) {
 let c = parseInt(a)+parseInt(b);
 let promiseResolution = {
     c:c,
     d : c+c,
     x : 'RandomString'
 };
 if(c===10){
     resolve(promiseResolution);
 }else {
     reject('Not 10');
 }
});
};

Pull arguments from promiseResolution.

checkIfNumbersAddToTen(5,5).then(function (arguments) {
console.log('c:'+arguments.c);
console.log('d:'+arguments.d);
console.log('x:'+arguments.x);
},function (failure) {
console.log(failure);
});

How to convert a date String to a Date or Calendar object?

In brief:

DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
try {
  Date date = formatter.parse("01/29/02");
} catch (ParseException e) {
  e.printStackTrace();
}

See SimpleDateFormat javadoc for more.

And to turn it into a Calendar, do:

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);

How to write to a file in Scala?

Here's an example of writing some lines to a file using scalaz-stream.

import scalaz._
import scalaz.stream._

def writeLinesToFile(lines: Seq[String], file: String): Task[Unit] =
  Process(lines: _*)              // Process that enumerates the lines
    .flatMap(Process(_, "\n"))    // Add a newline after each line
    .pipe(text.utf8Encode)        // Encode as UTF-8
    .to(io.fileChunkW(fileName))  // Buffered write to the file
    .runLog[Task, Unit]           // Get this computation as a Task
    .map(_ => ())                 // Discard the result

writeLinesToFile(Seq("one", "two"), "file.txt").run

ActiveRecord: size vs count

I recommended using the size function.

class Customer < ActiveRecord::Base
  has_many :customer_activities
end

class CustomerActivity < ActiveRecord::Base
  belongs_to :customer, counter_cache: true
end

Consider these two models. The customer has many customer activities.

If you use a :counter_cache on a has_many association, size will use the cached count directly, and not make an extra query at all.

Consider one example: in my database, one customer has 20,000 customer activities and I try to count the number of records of customer activities of that customer with each of count, length and size method. here below the benchmark report of all these methods.

            user     system      total        real
Count:     0.000000   0.000000   0.000000 (  0.006105)
Size:      0.010000   0.000000   0.010000 (  0.003797)
Length:    0.030000   0.000000   0.030000 (  0.026481)

so I found that using :counter_cache Size is the best option to calculate the number of records.

How to Animate Addition or Removal of Android ListView Rows

Have you considered animating a sweep to the right? You could do something like drawing a progressively larger white bar across the top of the list item, then removing it from the list. The other cells would still jerk into place, but it'd better than nothing.

Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"

For others who may run across this - it can also occur if someone carelessly leaves trailing spaces from a php include file. Example:

 <?php 
    require_once('mylib.php');
    session_start();
 ?>

In the case above, if the mylib.php has blank spaces after its closing ?> tag, this will cause an error. This obviously can get annoying if you've included/required many files. Luckily the error tells you which file is offending.

HTH

When to use EntityManager.find() vs EntityManager.getReference() with JPA

I disagree with the selected answer, and as davidxxx correctly pointed out, getReference does not provide such behaviour of dynamic updations without select. I asked a question concerning the validity of this answer, see here - cannot update without issuing select on using setter after getReference() of hibernate JPA.

I quite honestly haven't seen anybody who's actually used that functionality. ANYWHERE. And i don't understand why it's so upvoted.

Now first of all, no matter what you call on a hibernate proxy object, a setter or a getter, an SQL is fired and the object is loaded.

But then i thought, so what if JPA getReference() proxy doesn't provide that functionality. I can just write my own proxy.

Now, we can all argue that selects on primary keys are as fast as a query can get and it's not really something to go to great lengths to avoid. But for those of us who can't handle it due to one reason or another, below is an implementation of such a proxy. But before i you see the implementation, see it's usage and how simple it is to use.

USAGE

Order example = ProxyHandler.getReference(Order.class, 3);
example.setType("ABCD");
example.setCost(10);
PersistenceService.save(example);

And this would fire the following query -

UPDATE Order SET type = 'ABCD' and cost = 10 WHERE id = 3;

and even if you want to insert, you can still do PersistenceService.save(new Order("a", 2)); and it would fire an insert as it should.

IMPLEMENTATION

Add this to your pom.xml -

<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.10</version>
</dependency>

Make this class to create dynamic proxy -

@SuppressWarnings("unchecked")
public class ProxyHandler {

public static <T> T getReference(Class<T> classType, Object id) {
    if (!classType.isAnnotationPresent(Entity.class)) {
        throw new ProxyInstantiationException("This is not an entity!");
    }

    try {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(classType);
        enhancer.setCallback(new ProxyMethodInterceptor(classType, id));
        enhancer.setInterfaces((new Class<?>[]{EnhancedProxy.class}));
        return (T) enhancer.create();
    } catch (Exception e) {
        throw new ProxyInstantiationException("Error creating proxy, cause :" + e.getCause());
    }
}

Make an interface with all the methods -

public interface EnhancedProxy {
    public String getJPQLUpdate();
    public HashMap<String, Object> getModifiedFields();
}

Now, make an interceptor which will allow you to implement these methods on your proxy -

import com.anil.app.exception.ProxyInstantiationException;
import javafx.util.Pair;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import javax.persistence.Id;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
/**
* @author Anil Kumar
*/
public class ProxyMethodInterceptor implements MethodInterceptor, EnhancedProxy {

private Object target;
private Object proxy;
private Class classType;
private Pair<String, Object> primaryKey;
private static HashSet<String> enhancedMethods;

ProxyMethodInterceptor(Class classType, Object id) throws IllegalAccessException, InstantiationException {
    this.classType = classType;
    this.target = classType.newInstance();
    this.primaryKey = new Pair<>(getPrimaryKeyField().getName(), id);
}

static {
    enhancedMethods = new HashSet<>();
    for (Method method : EnhancedProxy.class.getDeclaredMethods()) {
        enhancedMethods.add(method.getName());
    }
}

@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
    //intercept enhanced methods
    if (enhancedMethods.contains(method.getName())) {
        this.proxy = obj;
        return method.invoke(this, args);
    }
    //else invoke super class method
    else
        return proxy.invokeSuper(obj, args);
}

@Override
public HashMap<String, Object> getModifiedFields() {
    HashMap<String, Object> modifiedFields = new HashMap<>();
    try {
        for (Field field : classType.getDeclaredFields()) {

            field.setAccessible(true);

            Object initialValue = field.get(target);
            Object finalValue = field.get(proxy);

            //put if modified
            if (!Objects.equals(initialValue, finalValue)) {
                modifiedFields.put(field.getName(), finalValue);
            }
        }
    } catch (Exception e) {
        return null;
    }
    return modifiedFields;
}

@Override
public String getJPQLUpdate() {
    HashMap<String, Object> modifiedFields = getModifiedFields();
    if (modifiedFields == null || modifiedFields.isEmpty()) {
        return null;
    }
    StringBuilder fieldsToSet = new StringBuilder();
    for (String field : modifiedFields.keySet()) {
        fieldsToSet.append(field).append(" = :").append(field).append(" and ");
    }
    fieldsToSet.setLength(fieldsToSet.length() - 4);
    return "UPDATE "
            + classType.getSimpleName()
            + " SET "
            + fieldsToSet
            + "WHERE "
            + primaryKey.getKey() + " = " + primaryKey.getValue();
}

private Field getPrimaryKeyField() throws ProxyInstantiationException {
    for (Field field : classType.getDeclaredFields()) {
        field.setAccessible(true);
        if (field.isAnnotationPresent(Id.class))
            return field;
    }
    throw new ProxyInstantiationException("Entity class doesn't have a primary key!");
}
}

And the exception class -

public class ProxyInstantiationException extends RuntimeException {
public ProxyInstantiationException(String message) {
    super(message);
}

A service to save using this proxy -

@Service
public class PersistenceService {

@PersistenceContext
private EntityManager em;

@Transactional
private void save(Object entity) {
    // update entity for proxies
    if (entity instanceof EnhancedProxy) {
        EnhancedProxy proxy = (EnhancedProxy) entity;
        Query updateQuery = em.createQuery(proxy.getJPQLUpdate());
        for (Entry<String, Object> entry : proxy.getModifiedFields().entrySet()) {
            updateQuery.setParameter(entry.getKey(), entry.getValue());
        }
        updateQuery.executeUpdate();
    // insert otherwise
    } else {
        em.persist(entity);
    }

}
}

Create a remote branch on GitHub

Before creating a new branch always the best practice is to have the latest of repo in your local machine. Follow these steps for error free branch creation.

 1. $ git branch (check which branches exist and which one is currently active (prefixed with *). This helps you avoid creating duplicate/confusing branch name)
 2. $ git branch <new_branch> (creates new branch)
 3. $ git checkout new_branch
 4. $ git add . (After making changes in the current branch)
 5. $ git commit -m "type commit msg here"
 6. $ git checkout master (switch to master branch so that merging with new_branch can be done)
 7. $ git merge new_branch (starts merging)
 8. $ git push origin master (push to the remote server)

I referred this blog and I found it to be a cleaner approach.

How to beautifully update a JPA entity in Spring Data?

In Spring Data you simply define an update query if you have the ID

  @Repository
  public interface CustomerRepository extends JpaRepository<Customer , Long> {

     @Query("update Customer c set c.name = :name WHERE c.id = :customerId")
     void setCustomerName(@Param("customerId") Long id, @Param("name") String name);

  }

Some solutions claim to use Spring data and do JPA oldschool (even in a manner with lost updates) instead.

Angular2 - Radio Button Binding

Angular 8 Radio Listing Example:

Source Link

enter image description here

JSON Response

    [
            {
                "moduleId": 1,
                "moduleName": "Employee",
                "subModules":[
                    {
                        "subModuleId": 1,
                        "subModuleName": "Add Employee",
                        "selectedRightType": 1,
                    },{
                        "subModuleId": 2,
                        "subModuleName": "Update Employee",
                        "selectedRightType": 2,
                    },{
                        "subModuleId": 3,
                        "subModuleName": "Delete Employee",
                        "selectedRightType": 3,
                    }
                ]
            },  
            {
                "moduleId": 2,
                "moduleName": "Company",
                "subModules":[
                    {
                        "subModuleId": 4,
                        "subModuleName": "Add Company",
                        "selectedRightType": 1,
                    },{
                        "subModuleId": 5,
                        "subModuleName": "Update Company",
                        "selectedRightType": 2,
                    },{
                        "subModuleId": 6,
                        "subModuleName": "Delete Company",
                        "selectedRightType": 3,
                    }
                ]
            },  
            {
                "moduleId": 3,
                "moduleName": "Tasks",
                "subModules":[
                    {
                        "subModuleId": 7,
                        "subModuleName": "Add Task",
                        "selectedRightType": 1,
                    },{
                        "subModuleId": 8,
                        "subModuleName": "Update Task",
                        "selectedRightType": 2,
                    },{
                        "subModuleId": 9,
                        "subModuleName": "Delete Task",
                        "selectedRightType": 3,
                    }
                ]
            }
    ]

HTML Template

        <div *ngFor="let module of modules_object">
            <div>{{module.moduleName}}</div>
            <table width="100%">

                <thead>
                    <tr>
                        <th>Submodule</th>
                        <th>
                            <input type="radio" name="{{module.moduleName}}_head_radio" [(ngModel)]="module.selHeader" (change)="selAllColumn(module)" [value]="1"> Read Only
                        </th>
                        <th>
                            <input type="radio" name="{{module.moduleName}}_head_radio" [(ngModel)]="module.selHeader" (change)="selAllColumn(module)" [value]="2"> Read Write
                        </th>
                        <th>
                            <input type="radio" name="{{module.moduleName}}_head_radio" [(ngModel)]="module.selHeader" (change)="selAllColumn(module)" [value]="3"> No Access
                        </th>
                    </tr>
                </thead>

                <tbody>
                    <tr *ngFor="let sm of module.subModules">
                        <td>{{sm.subModuleName}}</td>
                        <td>
                            <input type="radio" [checked]="sm.selectedRightType == '1'" [(ngModel)]="sm.selectedRightType" name="{{sm.subModuleId}}_radio" [value]="1"> 
                        </td>
                        <td class="cl-left">
                            <input type="radio" [checked]="sm.selectedRightType == '2'" [(ngModel)]="sm.selectedRightType" name="{{sm.subModuleId}}_radio" [value]="2"> 
                        </td>
                        <td class="cl-left">
                            <input type="radio" [checked]="sm.selectedRightType == '3'" [(ngModel)]="sm.selectedRightType" name="{{sm.subModuleId}}_radio" [value]="3"> 
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

"This SqlTransaction has completed; it is no longer usable."... configuration error?

Had the exact same problem and just could not find the right solution. Hope this helps somebody.

I have an .NET Core 3.1 WebApi with EF Core. Upon receiving multiple calls at the same time, the applications was trying to add and save changes to the database at the same time.

In my case the problem was that the table that the data would be saved in did not have a primary key set.

Somehow EF Core missed when the migration was ran from the application that the ID in the model was supposed to be a primary key.

I found the problem by opening the SQL Profiler and seeing that all transactions was successfully submitted to the database (from the application) but only one new row was created. The profiler also showed that some type of deadlock was happening but I couldn't see much more in the trace logs of the profiler. On further inspection I noticed that the primary key identifier was missing on the column "Id".

The exceptions I got from my application was:

This SqlTransaction has completed; it is no longer usable.

and/or

An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseSqlServer' call.

Return row number(s) for a particular value in a column in a dataframe

Use which(mydata_2$height_chad1 == 2585)

Short example

df <- data.frame(x = c(1,1,2,3,4,5,6,3),
                 y = c(5,4,6,7,8,3,2,4))
df
  x y
1 1 5
2 1 4
3 2 6
4 3 7
5 4 8
6 5 3
7 6 2
8 3 4

which(df$x == 3)
[1] 4 8

length(which(df$x == 3))
[1] 2

count(df, vars = "x")
  x freq
1 1    2
2 2    1
3 3    2
4 4    1
5 5    1
6 6    1

df[which(df$x == 3),]
  x y
4 3 7
8 3 4

As Matt Weller pointed out, you can use the length function. The count function in plyr can be used to return the count of each unique column value.

How to display a list inline using Twitter's Bootstrap

I couldn't find anything specific within the bootstrap.css file. So, I added the css to a custom css file.

.inline li {
    display: inline;
}

How can I search Git branches for a file or directory?

git ls-tree might help. To search across all existing branches:

for branch in `git for-each-ref --format="%(refname)" refs/heads`; do
  echo $branch :; git ls-tree -r --name-only $branch | grep '<foo>'
done

The advantage of this is that you can also search with regular expressions for the file name.

Twitter Bootstrap Datepicker within modal window

Wrap your datapicker JavaScript code inside

function pageLoad() {}

fill an array in C#

Say you want to fill with number 13.

int[] myarr = Enumerable.Range(0, 10).Select(n => 13).ToArray();

or

List<int> myarr = Enumerable.Range(0,10).Select(n => 13).ToList();

if you prefer a list.

Trouble using ROW_NUMBER() OVER (PARTITION BY ...)

A bit involved. Easiest would be to refer to this SQL Fiddle I created for you that produces the exact result. There are ways you can improve it for performance or other considerations, but this should hopefully at least be clearer than some alternatives.

The gist is, you get a canonical ranking of your data first, then use that to segment the data into groups, then find an end date for each group, then eliminate any intermediate rows. ROW_NUMBER() and CROSS APPLY help a lot in doing it readably.


EDIT 2019:

The SQL Fiddle does in fact seem to be broken, for some reason, but it appears to be a problem on the SQL Fiddle site. Here's a complete version, tested just now on SQL Server 2016:

CREATE TABLE Source
(
  EmployeeID int,
  DateStarted date,
  DepartmentID int
)

INSERT INTO Source
VALUES
(10001,'2013-01-01',001),
(10001,'2013-09-09',001),
(10001,'2013-12-01',002),
(10001,'2014-05-01',002),
(10001,'2014-10-01',001),
(10001,'2014-12-01',001)


SELECT *, 
  ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS EntryRank,
  newid() as GroupKey,
  CAST(NULL AS date) AS EndDate
INTO #RankedData
FROM Source
;

UPDATE #RankedData
SET GroupKey = beginDate.GroupKey
FROM #RankedData sup
  CROSS APPLY 
  (
    SELECT TOP 1 GroupKey
    FROM #RankedData sub 
    WHERE sub.EmployeeID = sup.EmployeeID AND
      sub.DepartmentID = sup.DepartmentID AND
      NOT EXISTS 
        (
          SELECT * 
          FROM #RankedData bot 
          WHERE bot.EmployeeID = sup.EmployeeID AND
            bot.EntryRank BETWEEN sub.EntryRank AND sup.EntryRank AND
            bot.DepartmentID <> sup.DepartmentID
        )
      ORDER BY DateStarted ASC
    ) beginDate (GroupKey);

UPDATE #RankedData
SET EndDate = nextGroup.DateStarted
FROM #RankedData sup
  CROSS APPLY 
  (
    SELECT TOP 1 DateStarted
    FROM #RankedData sub
    WHERE sub.EmployeeID = sup.EmployeeID AND
      sub.DepartmentID <> sup.DepartmentID AND
      sub.EntryRank > sup.EntryRank
    ORDER BY EntryRank ASC
  ) nextGroup (DateStarted);

SELECT * FROM 
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY GroupKey ORDER BY EntryRank ASC) AS GroupRank FROM #RankedData
) FinalRanking
WHERE GroupRank = 1
ORDER BY EntryRank;

DROP TABLE #RankedData
DROP TABLE Source

Drag and drop a DLL to the GAC ("assembly") in windows server 2008 .net 4.0

if you have neccessary .net framework installed. Ex ; .Net 4.0 or .Net 3.5, then you can just copy Gacutil.exe from any of the machine and to the new machine.

1) Open CMD as adminstrator in new server.
2) Traverse to the folder where you copied the Gacutil.exe. For eg - C:\program files.(in my case).
3) Type the below in the cmd prompt and install.

C:\Program Files\gacutil.exe /I dllname

How to refresh a Page using react-route Link

To refresh page you don't need react-router, simple js:

window.location.reload();

To re-render view in React component, you can just fire update with props/state.

reading text file with utf-8 encoding using java

You need to specify the encoding of the InputStreamReader using the Charset parameter.

Charset inputCharset = Charset.forName("ISO-8859-1");
InputStreamReader isr = new InputStreamReader(fis, inputCharset));

This is work for me. i hope to help you.

how to count the spaces in a java string?

public static void main(String[] args) {
    String str = "Honey   dfd    tEch Solution";
    String[] arr = str.split(" ");
    System.out.println(arr.length);
    int count = 0;
    for (int i = 0; i < arr.length; i++) {
        if (!arr[i].trim().isEmpty()) {
            System.out.println(arr[i]);
            count++;
        }
    }
    System.out.println(count);
}

HTML5 canvas ctx.fillText won't do line breaks?

Here's a version of Colin's wrapText() that also supports vertically centered text with context.textBaseline = 'middle':

var wrapText = function (context, text, x, y, maxWidth, lineHeight) {
    var paragraphs = text.split("\n");
    var textLines = [];

    // Loop through paragraphs
    for (var p = 0; p < paragraphs.length; p++) {
        var line = "";
        var words = paragraphs[p].split(" ");
        // Loop through words
        for (var w = 0; w < words.length; w++) {
            var testLine = line + words[w] + " ";
            var metrics = context.measureText(testLine);
            var testWidth = metrics.width;
            // Make a line break if line is too long
            if (testWidth > maxWidth) {
                textLines.push(line.trim());
                line = words[w] + " ";
            }
            else {
                line = testLine;
            }
        }
        textLines.push(line.trim());
    }

    // Move text up if centered vertically
    if (context.textBaseline === 'middle')
        y = y - ((textLines.length-1) * lineHeight) / 2;

    // Render text on canvas
    for (var tl = 0; tl < textLines.length; tl++) {
        context.fillText(textLines[tl], x, y);
        y += lineHeight;
    }
};

Logging with Retrofit 2

The following set of code is working without any problems for me

Gradle

// Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'

RetrofitClient

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);

OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(logging)
        .build();

retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build();

One can also verify the results by going into Profiler Tab at bottom of Android Studio, then clicking + sign to Start A New Session, and then select the desired spike in "Network". There you can get everything, but it is cumbersome and slow. Please see image below.

enter image description here

Is there any "font smoothing" in Google Chrome?

I had the same problem, and I found the solution in this post of Sam Goddard,

The solution if to defined the call to the font twice. First as it is recommended, to be used for all the browsers, and after a particular call only for Chrome with a special media query:

@font-face {
  font-family: 'chunk-webfont';
  src: url('../../includes/fonts/chunk-webfont.eot');
  src: url('../../includes/fonts/chunk-webfont.eot?#iefix') format('eot'),
  url('../../includes/fonts/chunk-webfont.woff') format('woff'),
  url('../../includes/fonts/chunk-webfont.ttf') format('truetype'),
  url('../../includes/fonts/chunk-webfont.svg') format('svg');
  font-weight: normal;
  font-style: normal;
}

@media screen and (-webkit-min-device-pixel-ratio:0) {
  @font-face {
    font-family: 'chunk-webfont';
    src: url('../../includes/fonts/chunk-webfont.svg') format('svg');
  }
}

enter image description here

With this method the font will render good in all browsers. The only negative point that I found is that the font file is also downloaded twice.

You can find an spanish version of this article in my page

In android how to set navigation drawer header image and name programmatically in class file?

I know this is an old post but i am sure that this might help someone down the road.

You can simply get the headerView element of the Navigation view by doing this:

 NavigationView mView = ( NavigationView ) findViewById( R.id.nav_view );

 if( mView != null ){
     LinearLayout mParent = ( LinearLayout ) mView.getHeaderView( 0 );

     if( mParent != null ){
        // Set your values to the image and text view by declaring and setting as you need to here. 
     }
 }

I hope that this helps someone.

Installing PDO driver on MySQL Linux server

At first install necessary PDO parts by running the command

`sudo apt-get install php*-mysql` 

where * is a version name of php like 5.6, 7.0, 7.1, 7.2

After installation you need to mention these two statements

extension=pdo.so
extension=pdo_mysql.so

in your .ini file (uncomment if it is already there) and restart server by command

sudo service apache2 restart

How do I grab an INI value within a shell script?

When I use a password in base64, I put the separator ":" because the base64 string may has "=". For example (I use ksh):

> echo "Abc123" | base64
QWJjMTIzCg==

In parameters.ini put the line pass:QWJjMTIzCg==, and finally:

> PASS=`awk -F":" '/pass/ {print $2 }' parameters.ini | base64 --decode`
> echo "$PASS"
Abc123

If the line has spaces like "pass : QWJjMTIzCg== " add | tr -d ' ' to trim them:

> PASS=`awk -F":" '/pass/ {print $2 }' parameters.ini | tr -d ' ' | base64 --decode`
> echo "[$PASS]"
[Abc123]

Transport endpoint is not connected

I have exactly the same problem. I haven't found a solution anywhere, but I have been able to fix it without rebooting by simply unmounting and remounting the mountpoint.

For your system the commands would be:

fusermount -uz /data
mount /data

The -z forces the unmount, which solved the need to reboot for me. You may need to do this as sudo depending on your setup. You may encounter the below error if the command does not have the required elevated permissions:

fusermount: entry for /data not found in /etc/mtab

I'm using Ubuntu 14.04 LTS, with the current version of mhddfs.

html - table row like a link

You can't wrap a <td> element with an <a> tag, but you can accomplish similar functionality by using the onclick event to call a function. An example is found here, something like this function:

<script type="text/javascript">
function DoNav(url)
{
   document.location.href = url;
}
</script>

And add it to your table like this:

<tr onclick="DoNav('http://stackoverflow.com/')"><td></td></tr>

How do you append rows to a table using jQuery?

I'm assuming you want to add this row to the <tbody> element, and simply using append() on the <table> will insert the <tr> outside the <tbody>, with perhaps undesirable results.

$('a').click(function() {
   $('#myTable tbody').append('<tr class="child"><td>blahblah</td></tr>');
});

EDIT: Here is the complete source code, and it does indeed work: (Note the $(document).ready(function(){});, which was not present before.

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('a').click(function() {
       $('#myTable tbody').append('<tr class="child"><td>blahblah</td></tr>');
    });
});
</script>
<title></title>
</head>
<body>
<a href="javascript:void(0);">Link</a>
<table id="myTable">
  <tbody>
    <tr>
      <td>test</td>
    </tr>
  </tbody>
</table>
</body>
</html>

Fastest way to reset every value of std::vector<int> to 0

If it's just a vector of integers, I'd first try:

memset(&my_vector[0], 0, my_vector.size() * sizeof my_vector[0]);

It's not very C++, so I'm sure someone will provide the proper way of doing this. :)

Define global variable with webpack

Use DefinePlugin.

The DefinePlugin allows you to create global constants which can be configured at compile time.

new webpack.DefinePlugin(definitions)

Example:

plugins: [
  new webpack.DefinePlugin({
    PRODUCTION: JSON.stringify(true)
  })
  //...
]

Usage:

console.log(`Environment is in production: ${PRODUCTION}`);

Why am I getting error for apple-touch-icon-precomposed.png

An alternative solution is to simply add a route to your routes.rb

It basically catches the Apple request and renders a 404 back to the client. This way your log files aren't cluttered.

# routes.rb at the near-end
match '/:png', via: :get, controller: 'application', action: 'apple_touch_not_found', png: /apple-touch-icon.*\.png/

then add a method 'apple_touch_not_found' to your application_controller.rb

# application_controller.rb
def apple_touch_not_found
  render  plain: 'apple-touch icons not found', status: 404
end