Programs & Examples On #Gnu toolchain

RecyclerView - How to smooth scroll to top of item on a certain position?

This is an extension function I wrote in Kotlin to use with the RecyclerView (based on @Paul Woitaschek answer):

fun RecyclerView.smoothSnapToPosition(position: Int, snapMode: Int = LinearSmoothScroller.SNAP_TO_START) {
  val smoothScroller = object : LinearSmoothScroller(this.context) {
    override fun getVerticalSnapPreference(): Int = snapMode
    override fun getHorizontalSnapPreference(): Int = snapMode
  }
  smoothScroller.targetPosition = position
  layoutManager?.startSmoothScroll(smoothScroller)
}

Use it like this:

myRecyclerView.smoothSnapToPosition(itemPosition)

How to execute mongo commands through shell scripts?

There is an official documentation page about this as well.

Examples from that page include:

mongo server:27017/dbname --quiet my_commands.js
mongo test --eval "printjson(db.getCollectionNames())"

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

I got frustrated too. My need was very straightforward. All I wanted was the ARGB color from the resources, so I wrote a simple static method.

protected static int getARGBColor(Context c, int resId)
        throws Resources.NotFoundException {

    TypedValue color = new TypedValue();
    try {
        c.getResources().getValue(resId, color, true);
    }
    catch (Resources.NotFoundException e) {
        throw(new Resources.NotFoundException(
                  String.format("Failed to find color for resourse id 0x%08x",
                                resId)));
    }
    if (color.type != TYPE_INT_COLOR_ARGB8) {
        throw(new Resources.NotFoundException(
                  String.format(
                      "Resourse id 0x%08x is of type 0x%02d. Expected TYPE_INT_COLOR_ARGB8",
                      resId, color.type))
        );
    }
    return color.data;
}

How can I disable the Maven Javadoc plugin from the command line?

For newbie Powershell users it is important to know that '.' is a syntactic element of Powershell, so the switch has to be enclosed in double quotes:

mvn clean install "-Dmaven.javadoc.skip=true"

How can I grep for a string that begins with a dash/hyphen?

grep -- -X
grep \\-X
grep '\-X'
grep "\-X"
grep -e -X
grep [-]X

RunAs A different user when debugging in Visual Studio

This works (I feel so idiotic):

C:\Windows\System32\cmd.exe /C runas /savecred /user:OtherUser DebugTarget.Exe

The above command will ask for your password everytime, so for less frustration, you can use /savecred. You get asked only once. (but works only for Home Edition and Starter, I think)

ADB error: cannot connect to daemon

Make sure that Kies is installed, but not running.

On your phone make sure you have USB Debugging mode enabled.

If still not successful, disable any Antivirus software.

How can I use numpy.correlate to do autocorrelation?

An alternative to numpy.correlate is available in statsmodels.tsa.stattools.acf(). This yields a continuously decreasing autocorrelation function like the one described by OP. Implementing it is fairly simple:

from statsmodels.tsa import stattools
# x = 1-D array
# Yield normalized autocorrelation function of number lags
autocorr = stattools.acf( x )

# Get autocorrelation coefficient at lag = 1
autocorr_coeff = autocorr[1]

The default behavior is to stop at 40 nlags, but this can be adjusted with the nlag= option for your specific application. There is a citation at the bottom of the page for the statistics behind the function.

Combine multiple JavaScript files into one JS file

Copy this script to notepad and save as .vbs file. Drag&Drop .js files on this script.

ps. This will work only on windows.

set objArgs = Wscript.Arguments
set objFso = CreateObject("Scripting.FileSystemObject")
content = ""

'Iterate through all the arguments passed
for i = 0 to objArgs.count  
    on error resume next
    'Try and treat the argument like a folder
    Set folder = objFso.GetFolder(objArgs(i))
    'If we get an error, we know it is a file
    if err.number <> 0 then
        'This is not a folder, treat as file
        content = content & ReadFile(objArgs(i))
    else
        'No error? This is a folder, process accordingly
        for each file in folder.Files
            content = content & ReadFile(file.path)
        next
    end if
    on error goto 0
next

'Get system Temp folder path
set tempFolderPath = objFso.GetSpecialFolder(2)
'Generate a random filename to use for a temporary file
strTempFileName = objFso.GetTempName
'Create temporary file in Temp folder
set objTempFile = tempFolderPath.CreateTextFile(strTempFileName)
'Write content from JavaScript files to temporary file
objTempFile.WriteLine(content)
objTempFile.Close

'Open temporary file in Notepad
set objShell = CreateObject("WScript.Shell")
objShell.Run("Notepad.exe " & tempFolderPath & "\" & strTempFileName)


function ReadFile(strFilePath)
    'If file path ends with ".js", we know it is JavaScript file
    if Right(strFilePath, 3) = ".js" then       
        set objFile = objFso.OpenTextFile(strFilePath, 1, false)
        'Read entire contents of a JavaScript file and returns it as a string
        ReadFile = objFile.ReadAll & vbNewLine
        objFile.Close
    else
        'Return empty string
        ReadFile = ""
    end if  
end function

Select From all tables - MySQL

Improve to @inno answer

delimiter //

DROP PROCEDURE IF EXISTS get_product;  
CREATE PROCEDURE get_product()
BEGIN
   DECLARE i VARCHAR(100); 
   DECLARE cur1 CURSOR FOR SELECT DISTINCT table_name FROM information_schema.columns WHERE COLUMN_NAME IN ('Product');
   OPEN cur1;

   read_loop: LOOP
       FETCH cur1 INTO i;
    
       SELECT i; -- printing table name
    
       SET @s = CONCAT('select * from ', i, ' where Product like %XYZ%'); 
       PREPARE stmt1 FROM @s;
       EXECUTE stmt1;
       DEALLOCATE PREPARE stmt1;

   END LOOP read_loop;

   CLOSE cur1;
END//

delimiter ;

call get_product();

Conditional Replace Pandas

np.where function works as follows:

df['X'] = np.where(df['Y']>=50, 'yes', 'no')

In your case you would want:

import numpy as np
df['my_channel'] = np.where(df.my_channel > 20000, 0, df.my_channel)

C++ create string of text and variables

See also boost::format:

#include <boost/format.hpp>

std::string var = (boost::format("somtext %s sometext %s") % somevar % somevar).str();

Why do you create a View in a database?

Think of it as refactoring your database schema.

Rename multiple files by replacing a particular pattern in the filenames using a shell script

this example, I am assuming that all your image files begin with "IMG" and you want to replace "IMG" with "VACATION"

solution : first identified all jpg files and then replace keyword

find . -name '*jpg' -exec bash -c 'echo mv $0 ${0/IMG/VACATION}' {} \; 

AngularJS 1.2 $injector:modulerr

One more thing to add to the list as this is the first result that comes up with a google search of 'Error: [$injector:modulerr] angular':

If you have a mismatch between your app name in your 'index'html' and in your main javascript app definition this can also generate this error.

For example if your HTML looks like this:

    </head>
    <body ng-app="myWebSite">

        <!-- My Web Site -->
        <p>About my web site...</p>

        etc ...

And your JavaScript looks like this (i.e has a typo on app name - myWebCite instead of myWebSite):

/** Main AngularJS Web Application */ 
var app = angular.module('myWebCite', [ 'ngRoute' ]); 

/** Configure the Routes */ 
app.config(['$routeProvider', function ($routeProvider) { 
  etc ...

then the 'Error:[$injector:modulerr] angular' error will be generated also.

Variably modified array at file scope

If you're going to use the preprocessor anyway, as per the other answers, then you can make the compiler determine the value of NUM_TYPES automagically:

#define NUM_TYPES (sizeof types / sizeof types[0])
static int types[] = { 
  1,
  2, 
  3, 
  4 };

XML to CSV Using XSLT

Found an XML transform stylesheet here (wayback machine link, site itself is in german)

The stylesheet added here could be helpful:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="iso-8859-1"/>

<xsl:strip-space elements="*" />

<xsl:template match="/*/child::*">
<xsl:for-each select="child::*">
<xsl:if test="position() != last()">"<xsl:value-of select="normalize-space(.)"/>",    </xsl:if>
<xsl:if test="position()  = last()">"<xsl:value-of select="normalize-space(.)"/>"<xsl:text>&#xD;</xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Perhaps you want to remove the quotes inside the xsl:if tags so it doesn't put your values into quotes, depending on where you want to use the CSV file.

What exactly does the "u" do? "git push -u origin master" vs "git push origin master"

All necessary git bash commands to push and pull into Github:

git status 
git pull
git add filefullpath

git commit -m "comments for checkin file" 
git push origin branch/master
git remote -v 
git log -2 

If you want to edit a file then:

edit filename.* 

To see all branches and their commits:

git show-branch

Oracle's default date format is YYYY-MM-DD, WHY?

I'm not an Oracle user (well, lately anyhow), BUT...

In most databases (and in precise language), a date doesn't include a time. Having a date doesn't imply that you are denoting a specific second on that date. Generally if you want a time as well as a date, that's called a timestamp.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

I also faced the above error. I used Eclipse.

After followed the below solution, it works fine for me.

Solution is,

  1. Right click project "pom.xml" in eclipse and select Maven Install.
  2. Right click on the project -> Maven -> Update Project.
  3. Refresh

hash keys / values as array

Here are implementations from phpjs.org:

This is not my code, I'm just pointing you to a useful resource.

ASP.NET MVC - passing parameters to the controller

public ActionResult ViewNextItem(int? id) makes the id integer a nullable type, no need for string<->int conversions.

Place input box at the center of div

You can just use either of the following approaches:

_x000D_
_x000D_
.center-block {
  margin: auto;
  display: block;
}
_x000D_
<div>
  <input class="center-block">
</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
.parent {
  display: grid;
  place-items: center;
}
_x000D_
<div class="parent">
  <input>
</div>
_x000D_
_x000D_
_x000D_

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

React Native Error: ENOSPC: System limit for number of file watchers reached

Linux uses the inotify package to observe filesystem events, individual files or directories.

Since React / Angular hot-reloads and recompiles files on save it needs to keep track of all project's files. Increasing the inotify watch limit should hide the warning messages.

You could try editing

# insert the new value into the system config
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

# check that the new value was applied
cat /proc/sys/fs/inotify/max_user_watches

# config variable name (not runnable)
fs.inotify.max_user_watches=524288

Word wrapping in phpstorm

For Word Wrapping in Php Storm 2019.1.3 Just follow below steps:

from top nagivation menu

View -> Active Editor -> Soft-Wrap

that's it so simple.

Rename specific column(s) in pandas

A much faster implementation would be to use list-comprehension if you need to rename a single column.

df.columns = ['log(gdp)' if x=='gdp' else x for x in df.columns]

If the need arises to rename multiple columns, either use conditional expressions like:

df.columns = ['log(gdp)' if x=='gdp' else 'cap_mod' if x=='cap' else x for x in df.columns]

Or, construct a mapping using a dictionary and perform the list-comprehension with it's get operation by setting default value as the old name:

col_dict = {'gdp': 'log(gdp)', 'cap': 'cap_mod'}   ## key?old name, value?new name

df.columns = [col_dict.get(x, x) for x in df.columns]

Timings:

%%timeit
df.rename(columns={'gdp':'log(gdp)'}, inplace=True)
10000 loops, best of 3: 168 µs per loop

%%timeit
df.columns = ['log(gdp)' if x=='gdp' else x for x in df.columns]
10000 loops, best of 3: 58.5 µs per loop

An existing connection was forcibly closed by the remote host

Had the same bug. Actually worked in case the traffic was sent using some proxy (fiddler in my case). Updated .NET framework from 4.5.2 to >=4.6 and now everything works fine. The actual request was:
new WebClient().DownloadData("URL");
The exception was:

SocketException: An existing connection was forcibly closed by the remote host

Determine which element the mouse pointer is on top of in JavaScript

elementFromPoint() gets only the first element in DOM tree. This is mostly not enough for developers needs. To get more than one element at e.g. the current mouse pointer position, this is the function you need:

document.elementsFromPoint(x, y) . // Mind the 's' in elements

This returns an array of all element objects under the given point. Just pass the mouse X and Y values to this function.

More information is here: DocumentOrShadowRoot.elementsFromPoint()

For very old browsers which are not supported, you may use this answer as a fallback.

Python speed testing - Time Difference - milliseconds

Arrow: Better dates & times for Python

import arrow
start_time = arrow.utcnow()
end_time = arrow.utcnow()
(end_time - start_time).total_seconds()  # senconds
(end_time - start_time).total_seconds() * 1000  # milliseconds

SoapUI "failed to load url" error when loading WSDL

I have had similar problems and worked around them by saving the WSDL locally. Don't forget to save any XSD files as well. You may need to edit the WSDL to specify an appropriate location for XSDs.

How to manage a redirect request after a jQuery Ajax call

I have a simple solution that works for me, no server code change needed...just add a tsp of nutmeg...

$(document).ready(function ()
{
    $(document).ajaxSend(
    function(event,request,settings)
    {
        var intercepted_success = settings.success;
        settings.success = function( a, b, c ) 
        {  
            if( request.responseText.indexOf( "<html>" ) > -1 )
                window.location = window.location;
            else
                intercepted_success( a, b, c );
        };
    });
});

I check the presence of html tag, but you can change the indexOf to search for whatever unique string exists in your login page...

How to make a jquery function call after "X" seconds

You can just use the normal setTimeout method in JavaScript.

ie...

setTimeout( function(){ 
    // Do something after 1 second 
  }  , 1000 );

In your example, you might want to use showStickySuccessToast directly.

Unresolved external symbol on static class members

in my case, I declared one static variable in .h file, like

//myClass.h
class myClass
{
static int m_nMyVar;
static void myFunc();
}

and in myClass.cpp, I tried to use this m_nMyVar. It got LINK error like:

error LNK2001: unresolved external symbol "public: static class... The link error related cpp file looks like:

//myClass.cpp
void myClass::myFunc()
{
myClass::m_nMyVar = 123; //I tried to use this m_nMyVar here and got link error
}

So I add below code on the top of myClass.cpp

//myClass.cpp
int myClass::m_nMyVar; //it seems redefine m_nMyVar, but it works well
void myClass::myFunc()
{
myClass::m_nMyVar = 123; //I tried to use this m_nMyVar here and got link error
}

then LNK2001 is gone.

Preprocessor check if multiple defines are not defined

#if !defined(MANUF) || !defined(SERIAL) || !defined(MODEL)

Pass user defined environment variable to tomcat

You should use System property instead of environment variable for this case. Edit your tomcat scripts for JAVA_OPTS and add property like:

-DAPP_MASTER_PASSWORD=foo

and in your code, write

System.getProperty("APP_MASTER_PASSWORD");

You can do this in Eclipse as well, instead of JAVA_OPTS, copy the line in VM parameters inside run configurations.

Twitter Bootstrap: Print content of modal window

I would suggest you try this jQuery plugin print element

It can let you just print the element you selected.

How can I debug a .BAT script?

rem out the @ECHO OFF and call your batch file redirectin ALL output to a log file..

c:> yourbatch.bat (optional parameters) > yourlogfile.txt 2>&1

found at http://www.robvanderwoude.com/battech_debugging.php

IT WORKS!! don't forget the 2>&1...

WIZ

Are PostgreSQL column names case-sensitive?

To quote the documentation:

Key words and unquoted identifiers are case insensitive. Therefore:

UPDATE MY_TABLE SET A = 5;

can equivalently be written as:

uPDaTE my_TabLE SeT a = 5;

You could also write it using quoted identifiers:

UPDATE "my_table" SET "a" = 5;

Quoting an identifier makes it case-sensitive, whereas unquoted names are always folded to lower case (unlike the SQL standard where unquoted names are folded to upper case). For example, the identifiers FOO, foo, and "foo" are considered the same by PostgreSQL, but "Foo" and "FOO" are different from these three and each other.

If you want to write portable applications you are advised to always quote a particular name or never quote it.

When do you use Git rebase instead of Git merge?

Before merge/rebase:

A <- B <- C    [master]
^
 \
  D <- E       [branch]

After git merge master:

A <- B <- C
^         ^
 \         \
  D <- E <- F

After git rebase master:

A <- B <- C <- D' <- E'

(A, B, C, D, E and F are commits)

This example and much more well illustrated information about Git can be found in Git The Basics Tutorial.

How do I enable/disable log levels in Android?

There is a tiny drop-in replacement for the standard android Log class - https://github.com/zserge/log

Basically all you have to do is to replace imports from android.util.Log to trikita.log.Log. Then in your Application.onCreate() or in some static initalizer check for the BuilConfig.DEBUG or any other flag and use Log.level(Log.D) or Log.level(Log.E) to change the minimal log level. You can use Log.useLog(false) to disable logging at all.

How to kill a child process after a given timeout in Bash?

Assuming you have (or can easily make) a pid file for tracking the child's pid, you could then create a script that checks the modtime of the pid file and kills/respawns the process as needed. Then just put the script in crontab to run at approximately the period you need.

Let me know if you need more details. If that doesn't sound like it'd suit your needs, what about upstart?

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

A simple fix for this is to install the Google Cast extension. If you don't have a Chromecast, or don't want to use the extension, no problem; just don't use the extension.

Wait Until File Is Completely Written

I would like to add an answer here, because this worked for me. I used time delays, while loops, everything I could think of.

I had the Windows Explorer window of the output folder open. I closed it, and everything worked like a charm.

I hope this helps someone.

In Javascript, how to conditionally add a member to an object?

i prefere, using code this it, you can run this code

const three = {
  three: 3
}

// you can active this code, if you use object `three is null`
//const three = {}

const number = {
  one: 1,
  two: 2,
  ...(!!three && three),
  four: 4
}

console.log(number);

Npm Please try using this command again as root/administrator

I solve it running as administrator cmd. Cleaning the cache npm cache clean -f And then try to install the package again

How to navigate through textfields (Next / Done Buttons)

After you exit from one text field, you call [otherTextField becomeFirstResponder] and the next field gets focus.

This can actually be a tricky problem to deal with since often you'll also want to scroll the screen or otherwise adjust the position of the text field so it's easy to see when editing. Just make sure to do a lot of testing with coming into and out of the text fields in different ways and also leaving early (always give the user an option to dismiss the keyboard instead of going to the next field, usually with "Done" in the nav bar)

how to set auto increment column with sql developer

You can make auto increment in SQL Modeler. In column properties window Click : General then Tick the box of Auto Increment. After that the auto increment window will be enabled for you.

Python:Efficient way to check if dictionary is empty or not

Just check the dictionary:

d = {'hello':'world'}
if d:
  print 'not empty'
else:
  print 'empty'

d = {}
if d:
  print 'not empty'
else:
  print 'empty'

Why should a Java class implement comparable?

Most of the examples above show how to reuse an existing comparable object in the compareTo function. If you would like to implement your own compareTo when you want to compare two objects of the same class, say an AirlineTicket object that you would like to sort by price(less is ranked first), followed by number of stopover (again, less is ranked first), you would do the following:

class AirlineTicket implements Comparable<Cost>
{
    public double cost;
    public int stopovers;
    public AirlineTicket(double cost, int stopovers)
    {
        this.cost = cost; this.stopovers = stopovers ;
    }

    public int compareTo(Cost o)
    {
        if(this.cost != o.cost)
          return Double.compare(this.cost, o.cost); //sorting in ascending order. 
        if(this.stopovers != o.stopovers)
          return this.stopovers - o.stopovers; //again, ascending but swap the two if you want descending
        return 0;            
    }
}

How to add elements to an empty array in PHP?

Both array_push and the method you described will work.

$customArray = array();
$customArray[] = 20;
$customArray[] = 21;

Above is correct, but below one is for further understanding

$customArray = array();
for($i=0;$i<=12;$i++){
    $cart[] = $i;  
}
echo "<pre>";
print_r($customArray);
echo "</pre>";

Copy Notepad++ text with formatting?

Select the text.

Right Click.

Plugin Commands -> Copy Text with Syntax Highlighting

Paste it into Word or whatever.

Pandas: Subtracting two date columns and the result being an integer

You can use datetime module to help here. Also, as a side note, a simple date subtraction should work as below:

import datetime as dt
import numpy as np
import pandas as pd

#Assume we have df_test:
In [222]: df_test
Out[222]: 
   first_date second_date
0  2016-01-31  2015-11-19
1  2016-02-29  2015-11-20
2  2016-03-31  2015-11-21
3  2016-04-30  2015-11-22
4  2016-05-31  2015-11-23
5  2016-06-30  2015-11-24
6         NaT  2015-11-25
7         NaT  2015-11-26
8  2016-01-31  2015-11-27
9         NaT  2015-11-28
10        NaT  2015-11-29
11        NaT  2015-11-30
12 2016-04-30  2015-12-01
13        NaT  2015-12-02
14        NaT  2015-12-03
15 2016-04-30  2015-12-04
16        NaT  2015-12-05
17        NaT  2015-12-06

In [223]: df_test['Difference'] = df_test['first_date'] - df_test['second_date'] 

In [224]: df_test
Out[224]: 
   first_date second_date  Difference
0  2016-01-31  2015-11-19     73 days
1  2016-02-29  2015-11-20    101 days
2  2016-03-31  2015-11-21    131 days
3  2016-04-30  2015-11-22    160 days
4  2016-05-31  2015-11-23    190 days
5  2016-06-30  2015-11-24    219 days
6         NaT  2015-11-25         NaT
7         NaT  2015-11-26         NaT
8  2016-01-31  2015-11-27     65 days
9         NaT  2015-11-28         NaT
10        NaT  2015-11-29         NaT
11        NaT  2015-11-30         NaT
12 2016-04-30  2015-12-01    151 days
13        NaT  2015-12-02         NaT
14        NaT  2015-12-03         NaT
15 2016-04-30  2015-12-04    148 days
16        NaT  2015-12-05         NaT
17        NaT  2015-12-06         NaT

Now, change type to datetime.timedelta, and then use the .days method on valid timedelta objects.

In [226]: df_test['Diffference'] = df_test['Difference'].astype(dt.timedelta).map(lambda x: np.nan if pd.isnull(x) else x.days)

In [227]: df_test
Out[227]: 
   first_date second_date  Difference  Diffference
0  2016-01-31  2015-11-19     73 days           73
1  2016-02-29  2015-11-20    101 days          101
2  2016-03-31  2015-11-21    131 days          131
3  2016-04-30  2015-11-22    160 days          160
4  2016-05-31  2015-11-23    190 days          190
5  2016-06-30  2015-11-24    219 days          219
6         NaT  2015-11-25         NaT          NaN
7         NaT  2015-11-26         NaT          NaN
8  2016-01-31  2015-11-27     65 days           65
9         NaT  2015-11-28         NaT          NaN
10        NaT  2015-11-29         NaT          NaN
11        NaT  2015-11-30         NaT          NaN
12 2016-04-30  2015-12-01    151 days          151
13        NaT  2015-12-02         NaT          NaN
14        NaT  2015-12-03         NaT          NaN
15 2016-04-30  2015-12-04    148 days          148
16        NaT  2015-12-05         NaT          NaN
17        NaT  2015-12-06         NaT          NaN

Hope that helps.

Angular ng-repeat Error "Duplicates in a repeater are not allowed."

My JSON response was like this:

{"items": 
  &nbsp;[
    &nbsp;&nbsp;{
      "index": 1,
      "name": "Samantha",
      "rarity": "Scarborough",
      "email": "[email protected]"
    },
    &nbsp;&nbsp;{
      "index": 2,
      "name": "Amanda",
      "rarity": "Vick",
      "email": "[email protected]"
    }]
}

So, I used ng-repeat = "item in variables.items" to display it.

How to a convert a date to a number and back again in MATLAB

Use DATESTR

>> datestr(40189)
ans =
12-Jan-0110

Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM

>> datenum(2010,1,11)
ans =
      734149
>> datenum(2010,1,11)-40189
ans =
      693960
>> datestr(40189+693960)
ans =
11-Jan-2010

In other words, to convert any serial Excel date, call

datestr(excelSerialDate + 693960)

EDIT

To get the date in mm/dd/yyyy format, call datestr with the specified format

excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010

Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things

excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010

How to switch to another domain and get-aduser

get-aduser -Server "servername" -Identity %username% -Properties *

get-aduser -Server "testdomain.test.net" -Identity testuser -Properties *

These work when you have the username. Also less to type than using the -filter property.

EDIT: Formatting.

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

Same as AMIB answer, for soft delete error "Unknown column 'table_alias.deleted_at'", just add ->withTrashed() then handle it yourself like ->whereRaw('items_alias.deleted_at IS NULL')

How to perform update operations on columns of type JSONB in Postgres 9.4

Ideally, you don't use JSON documents for structured, regular data that you want to manipulate inside a relational database. Use a normalized relational design instead.

JSON is primarily intended to store whole documents that do not need to be manipulated inside the RDBMS. Related:

Updating a row in Postgres always writes a new version of the whole row. That's the basic principle of Postgres' MVCC model. From a performance perspective, it hardly matters whether you change a single piece of data inside a JSON object or all of it: a new version of the row has to be written.

Thus the advice in the manual:

JSON data is subject to the same concurrency-control considerations as any other data type when stored in a table. Although storing large documents is practicable, keep in mind that any update acquires a row-level lock on the whole row. Consider limiting JSON documents to a manageable size in order to decrease lock contention among updating transactions. Ideally, JSON documents should each represent an atomic datum that business rules dictate cannot reasonably be further subdivided into smaller datums that could be modified independently.

The gist of it: to modify anything inside a JSON object, you have to assign a modified object to the column. Postgres supplies limited means to build and manipulate json data in addition to its storage capabilities. The arsenal of tools has grown substantially with every new release since version 9.2. But the principal remains: You always have to assign a complete modified object to the column and Postgres always writes a new row version for any update.

Some techniques how to work with the tools of Postgres 9.3 or later:

This answer has attracted about as many downvotes as all my other answers on SO together. People don't seem to like the idea: a normalized design is superior for non-dynamic data. This excellent blog post by Craig Ringer explains in more detail:

How to join two JavaScript Objects, without using JQUERY

WORKING FIDDLE

Simplest Way with Jquery -

var finalObj = $.extend(obj1, obj2);

Without Jquery -

var finalobj={};
for(var _obj in obj1) finalobj[_obj ]=obj1[_obj];
for(var _obj in obj2) finalobj[_obj ]=obj2[_obj];

Order columns through Bootstrap4

even this will work:

<div class="container">
            <div class="row">
                <div class="col-4 col-sm-4 col-md-6 order-1">
                    1
                </div>
                <div class="col-4 col-sm-4  col-md-6 order-3">
                    2
                </div>
                <div class="col-4 col-sm-4  col-md-12 order-2">
                    3
                </div>
            </div>
          </div>

Using python's eval() vs. ast.literal_eval()?

I was stuck with ast.literal_eval(). I was trying it in IntelliJ IDEA debugger, and it kept returning None on debugger output.

But later when I assigned its output to a variable and printed it in code. It worked fine. Sharing code example:

import ast
sample_string = '[{"id":"XYZ_GTTC_TYR", "name":"Suction"}]'
output_value = ast.literal_eval(sample_string)
print(output_value)

Its python version 3.6.

Performing a Stress Test on Web Application?

I played with JMeter. One think it could not not test was ASP.NET Webforms. The viewstate broke my tests. I am not shure why, but there are a couple of tools out there that dont handle viewstate right. My current project is ASP.NET MVC and JMeter works well with it.

How to print Unicode character in Python?

Replace '+' with '000'. For example, 'U+1F600' will become 'U0001F600' and prepend the Unicode code with "\" and print. Example:

>>> print("Learning : ", "\U0001F40D")
Learning :  
>>> 

Check this maybe it will help python unicode emoji

How to replicate vector in c?

Vector and list aren't conceptually tied to C++. Similar structures can be implemented in C, just the syntax (and error handling) would look different. For example LodePNG implements a dynamic array with functionality very similar to that of std::vector. A sample usage looks like:

uivector v = {};
uivector_push_back(&v, 1);
uivector_push_back(&v, 42);
for(size_t i = 0; i < v.size; ++i)
    printf("%d\n", v.data[i]);
uivector_cleanup(&v);

As can be seen the usage is somewhat verbose and the code needs to be duplicated to support different types.

nothings/stb gives a simpler implementation that works with any types, but compiles only in C:

double *v = 0;
sb_push(v, 1.0);
sb_push(v, 42.0);
for(int i = 0; i < sb_count(v); ++i)
    printf("%g\n", v[i]);
sb_free(v);

A lot of C code, however, resorts to managing the memory directly with realloc:

void* newMem = realloc(oldMem, newSize);
if(!newMem) {
    // handle error
}
oldMem = newMem;

Note that realloc returns null in case of failure, yet the old memory is still valid. In such situation this common (and incorrect) usage leaks memory:

oldMem = realloc(oldMem, newSize);
if(!oldMem) {
    // handle error
}

Compared to std::vector and the C equivalents from above, the simple realloc method does not provide O(1) amortized guarantee, even though realloc may sometimes be more efficient if it happens to avoid moving the memory around.

Why does intellisense and code suggestion stop working when Visual Studio is open?

@TonyL's answer didn't work for me, but I noticed Intellisense stopped working in the foo class after I changed the method signature in the bar class.

Closing and reopening the foo.cs file fixed it.

PHP PDO: charset, set names?

$conn = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $pass);

Check if a String contains numbers Java

.matches(".*\\d+.*") only works for numbers but not other symbols like // or * etc.

Swift: Determine iOS Screen size

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

In older swift: Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

Swift 4.0

// Screen width.
public var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}

// Screen height.
public var screenHeight: CGFloat {
    return UIScreen.main.bounds.height
}

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

How can I load the contents of a text file into a batch file variable?

Create a file called "SetFile.bat" that contains the following line with no carriage return at the end of it...

set FileContents=

Then in your batch file do something like this...

   @echo off
   copy SetFile.bat + %1 $tmp$.bat > nul
   call $tmp$.bat
   del $tmp$.bat

%1 is the name of your input file and %FileContents% will contain the contents of the input file after the call. This will only work on a one line file though (i.e. a file containing no carriage returns). You could strip out/replace carriage returns from the file before calling the %tmp%.bat if needed.

JQuery - Call the jquery button click event based on name property

$('element[name="element_name"]').click(function(){
    //do stuff
});

in your case:

$('input[name="btnName"]').click(function(){
    //do stuff
});

How to remove certain characters from a string in C++?

I'm afraid there is no such a member for std::string, but you can easily program that kind of functions. It may not be the fastest solution but this would suffice:

std::string RemoveChars(const std::string& source, const std::string& chars) {
   std::string result="";
   for (unsigned int i=0; i<source.length(); i++) {
      bool foundany=false;
      for (unsigned int j=0; j<chars.length() && !foundany; j++) {
         foundany=(source[i]==chars[j]);
      }
      if (!foundany) {
         result+=source[i];
      }
   }
   return result;
}

EDIT: Reading the answer below, I understood it to be more general, not only to detect digit. The above solution will omit every character passed in the second argument string. For example:

std::string result=RemoveChars("(999)99-8765-43.87", "()-");

Will result in

99999876543.87

How do I determine height and scrolling position of window in jQuery?

From jQuery Docs:

const height = $(window).height();
const scrollTop = $(window).scrollTop();

http://api.jquery.com/scrollTop/
http://api.jquery.com/height/

Setting format and value in input type="date"

It's ugly, but it works. :/

var today = new Date().toLocaleString('en-GB').split(' ')[0].split('/').reverse().join('-');

max(length(field)) in mysql

Ok, I am not sure what are you using(MySQL, SLQ Server, Oracle, MS Access..) But you can try the code below. It work in W3School example DB. Here try this:

SELECT city, max(length(city)) FROM Customers;

Auto-expanding layout with Qt-Designer

After creating your QVBoxLayout in Qt Designer, right-click on the background of your widget/dialog/window (not the QVBoxLayout, but the parent widget) and select Lay Out -> Lay Out in a Grid from the bottom of the context-menu. The QVBoxLayout should now stretch to fit the window and will resize automatically when the entire window is resized.

Check file extension in upload form in PHP

Checking the file extension is not considered best practice. The preferred method of accomplishing this task is by checking the files MIME type.

From PHP:

<?php
    $finfo = finfo_open(FILEINFO_MIME_TYPE); // Return MIME type
    foreach (glob("*") as $filename) {
        echo finfo_file($finfo, $filename) . "\n";
    }
    finfo_close($finfo);
?>

The above example will output something similar to which you should be checking.

text/html
image/gif
application/vnd.ms-excel

Although MIME types can also be tricked (edit the first few bytes of a file and modify the magic numbers), it's harder than editing a filename. So you can never be 100% sure what that file type actually is, and care should be taken about handling files uploaded/emailed by your users.

Installing Java on OS X 10.9 (Mavericks)

The OP implied that Java 7 was the need. And Java 6 is in fact no longer being 'supported' so 7 is the version you should be installing at this point unless you have legacy app concerns.

You can get it here: http://java.com/en/download/mac_download.jsp?locale=en

How to write unit testing for Angular / TypeScript for private methods with Jasmine

call private method using square brackets

Ts file

class Calculate{
  private total;
  private add(a: number) {
      return a + total;
  }
}

spect.ts file

it('should return 5 if input 3 and 2', () => {
    component['total'] = 2;
    let result = component['add'](3);
    expect(result).toEqual(5);
});

How to write a comment in a Razor view?

Note that in general, IDE's like Visual Studio will markup a comment in the context of the current language, by selecting the text you wish to turn into a comment, and then using the Ctrl+K Ctrl+C shortcut, or if you are using Resharper / Intelli-J style shortcuts, then Ctrl+/.

Server side Comments:

Razor .cshtml

Like so:

@* Comment goes here *@

.aspx
For those looking for the older .aspx view (and Asp.Net WebForms) server side comment syntax:

<%-- Comment goes here --%>

Client Side Comments

HTML Comment

<!-- Comment goes here -->

Javascript Comment

// One line Comment goes Here
/* Multiline comment
   goes here */

As OP mentions, although not displayed on the browser, client side comments will still be generated for the page / script file on the server and downloaded by the page over HTTP, which unless removed (e.g. minification), will waste I/O, and, since the comment can be viewed by the user by viewing the page source or intercepting the traffic with the browser's Dev Tools or a tool like Fiddler or Wireshark, can also pose a security risk, hence the preference to use server side comments on server generated code (like MVC views or .aspx pages).

what is the difference between uint16_t and unsigned short int incase of 64 bit processor?

uint16_t is unsigned 16-bit integer.

unsigned short int is unsigned short integer, but the size is implementation dependent. The standard only says it's at least 16-bit (i.e, minimum value of UINT_MAX is 65535). In practice, it usually is 16-bit, but you can't take that as guaranteed.

Note:

  1. If you want a portable unsigned 16-bit integer, use uint16_t.
  2. inttypes.h and stdint.h are both introduced in C99. If you are using C89, define your own type.
  3. uint16_t may not be provided in certain implementation(See reference below), but unsigned short int is always available.

Reference: C11(ISO/IEC 9899:201x) §7.20 Integer types

For each type described herein that the implementation provides) shall declare that typedef name and define the associated macros. Conversely, for each type described herein that the implementation does not provide, shall not declare that typedef name nor shall it define the associated macros. An implementation shall provide those types described as ‘‘required’’, but need not provide any of the others (described as ‘optional’’).

Create an instance of a class from a string

Probably my question should have been more specific. I actually know a base class for the string so solved it by:

ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));

The Activator.CreateInstance class has various methods to achieve the same thing in different ways. I could have cast it to an object but the above is of the most use to my situation.

Python MYSQL update statement

Here is the correct way:

import MySQLdb

if __name__ == '__main__':
    connect = MySQLdb.connect(host="localhost", port=3306,
                              user="xxx", passwd="xxx", db='xxx', charset='utf8')

    cursor = connect.cursor()

    cursor.execute("""
       UPDATE tblTableName
       SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
       WHERE Server=%s
    """, (Year, Month, Day, Hour, Minute, ServerID))

    connect.commit()
    connect.close()

P.S. Don't forget connect.commit(), or it won't work

start MySQL server from command line on Mac OS Lion

If it's installed with homebrew try just typing down mysql.server in terminal and that should be it. AFAIK it executable will be under /usr/local/bin/mysql.server.

If not you can always run following "locate mysql.server" which will tell you where to find such file.

What does "subject" mean in certificate?

The Subject, in security, is the thing being secured. In this case it could be a persons email or a website or a machine.

If we take the example of an email, say my email, then the subject key container would be the protected location containing my private key.

The certificate store usually refers to Microsoft certificate store which contains certificates form trusted roots, machines on the network, people etc. In my case the subjects certificate store would be the place, within this store, holding my certificates.

If you are working within a microsoft domain then the subject name will invariably hold the Distinguished Name, of the subject, which is how the domain references the subject and holds it in its directory. e.g. CN=Mark Sutton, OU=Developers, O=Mycompany C=UK

To look at your certificates on a microsoft machine:-

Log in as you run>mmc Select File>add/remove snap-in and select certificates then select my user account click Finish then close then ok. Look in the personal area of the store.

In the other areas of the store you will see the other trusted certificates used to validate signatures etc.

No resource found that matches the given name '@style/ Theme.Holo.Light.DarkActionBar'

There is a major error in the tutorials destined for newbies here: http://developer.android.com/training/basics/actionbar/styling.html

It is major because it is almost impossible to detect cause of error for a newbie.

The error is that this tutorial explicitly states that the tutorial is valid for api level 11 (Android 3.0), while in reality this is only true for the theme Theme.Holo (without further extensions and variants)

But this tutorial uses the the theme Theme.holo.Light.DarkActionBar which is only a valid theme from api level 14 (Android 4.0) and above.

This is only one of many examples on errors found in these tutorials (which are great in other regards). Somebody should correct these errors this weekend because they are really costly and annoying timethieves. If there is a way I can send this info to the Android team, then please tell me and I will do it. Hopefully, however, they read Stackoverflow. (let me suggest: The Android team should consider to put someone newbie to try out all tutorials as a qualification that they are valid).

Another error I (and countless other people) have found is that the appcombat backward compliance module really is not working if you strictly follow the tutorials. Error unknown. I had to give up.

Regarding the error in this thread, here is a quote from the tutorial text with italics on the mismatch:

" For Android 3.0 and higher only

When supporting Android 3.0 and higher only, you can define the action bar's background like this:

    <resources>
        <!-- the theme applied to the application or activity -->
        <style name="CustomActionBarTheme"
        parent="@style/Theme.Holo.Light.DarkActionBar"> 

ERROR1: Only Theme.Holo can be used with Android 3.0. Therefore, remove the "Light.DarkActionBar etc.

ERROR2: @style/Theme.Holo"> will not work. It is necessary to write @android:style/Theme.Holo">in order to indicate that it is a built in Theme that is being referenced. (A bit strange that "built in" is not the default, but needs to be stated?)

The compiler advice for error correction is to define api level 14 as minimum sdk. This is not optimal because it creates incompliance to Andreoid 3.0 (api level 11). Therefore, I use Theme.Holo only and this seems to work fine (a fresh finding, though).

I am using Netbeans with Android support. Works nicely.

Python function to convert seconds into minutes, hours, and days

This tidbit is useful for displaying elapsed time to varying degrees of granularity.

I personally think that questions of efficiency are practically meaningless here, so long as something grossly inefficient isn't being done. Premature optimization is the root of quite a bit of evil. This is fast enough that it'll never be your choke point.

intervals = (
    ('weeks', 604800),  # 60 * 60 * 24 * 7
    ('days', 86400),    # 60 * 60 * 24
    ('hours', 3600),    # 60 * 60
    ('minutes', 60),
    ('seconds', 1),
    )

def display_time(seconds, granularity=2):
    result = []

    for name, count in intervals:
        value = seconds // count
        if value:
            seconds -= value * count
            if value == 1:
                name = name.rstrip('s')
            result.append("{} {}".format(value, name))
    return ', '.join(result[:granularity])

..and this provides decent output:

In [52]: display_time(1934815)
Out[52]: '3 weeks, 1 day'

In [53]: display_time(1934815, 4)
Out[53]: '3 weeks, 1 day, 9 hours, 26 minutes'

Is it possible to read the value of a annotation in java?

For the few people asking for a generic method, this should help you (5 years later :p).

For my below example, I'm pulling the RequestMapping URL value from methods that have the RequestMapping annotation. To adapt this for fields, just change the

for (Method method: clazz.getMethods())

to

for (Field field: clazz.getFields())

And swap usage of RequestMapping for whatever annotation you are looking to read. But make sure that the annotation has @Retention(RetentionPolicy.RUNTIME).

public static String getRequestMappingUrl(final Class<?> clazz, final String methodName)
{
    // Only continue if the method name is not empty.
    if ((methodName != null) && (methodName.trim().length() > 0))
    {
        RequestMapping tmpRequestMapping;
        String[] tmpValues;

        // Loop over all methods in the class.
        for (Method method: clazz.getMethods())
        {
            // If the current method name matches the expected method name, then keep going.
            if (methodName.equalsIgnoreCase(method.getName()))
            {
                // Try to extract the RequestMapping annotation from the current method.
                tmpRequestMapping = method.getAnnotation(RequestMapping.class);

                // Only continue if the current method has the RequestMapping annotation.
                if (tmpRequestMapping != null)
                {
                    // Extract the values from the RequestMapping annotation.
                    tmpValues = tmpRequestMapping.value();

                    // Only continue if there are values.
                    if ((tmpValues != null) && (tmpValues.length > 0))
                    {
                        // Return the 1st value.
                        return tmpValues[0];
                    }
                }
            }
        }
    }

    // Since no value was returned, log it and return an empty string.
    logger.error("Failed to find RequestMapping annotation value for method: " + methodName);

    return "";
}

How to detect online/offline event cross-browser?

Today there's an open source JavaScript library that does this job: it's called Offline.js.

Automatically display online/offline indication to your users.

https://github.com/HubSpot/offline

Be sure to check the full README. It contains events that you can hook into.

Here's a test page. It's beautiful/has a nice feedback UI by the way! :)

Offline.js Simulate UI is an Offline.js plug-in that allows you to test how your pages respond to different connectivity states without having to use brute-force methods to disable your actual connectivity.

How can I convert the "arguments" object to an array in JavaScript?

It's also worth referencing this Bluebird promises library wiki page that shows how to manage the arguments object into array in a way that makes the function optimizable under V8 JavaScript engine:

function doesntLeakArguments() {
    var args = new Array(arguments.length);
    for(var i = 0; i < args.length; ++i) {
        args[i] = arguments[i];
    }
    return args;
}

This method is used in favor of var args = [].slice.call(arguments);. The author also shows how a build step can help reduce the verbosity.

How to output loop.counter in python jinja template?

in python:

env = Environment(loader=FileSystemLoader("templates"))
env.globals["enumerate"] = enumerate

in template:

{% for k,v in enumerate(list) %}
{% endfor %}

how to convert numeric to nvarchar in sql command

select convert(nvarchar(255), 4343)

Should do the trick.

Apache and Node.js on the Same Server

I combined the answer above with certbot SSL cert and CORS access-control-allow-headers and got it working so I thought I would share the results.

Apache httpd.conf added to the bottom of the file:

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

Apache VirtualHost settings (doc root for PHP is under Apache and SSL with Certbot, while node.js/socket.io site runs on port 3000 - and uses SSL cert from Apache) Also notice the node.js site uses the proxy for the folder /nodejs, socket.io, and ws (websockets):

<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerName www.example.com
    ServerAlias www.example.com
    DocumentRoot /var/html/www.example.com
    ErrorLog /var/html/log/error.log
    CustomLog /var/html/log/requests.log combined
    SSLCertificateFile /etc/letsencrypt/live/www.example.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/www.example.com/privkey.pem
    Include /etc/letsencrypt/options-ssl-apache.conf

    RewriteEngine On
    RewriteCond %{REQUEST_URI}  ^socket.io          [NC]
    RewriteCond %{QUERY_STRING} transport=websocket [NC]
    RewriteRule /{.*}       ws://localhost:3000/$1  [P,L]

    RewriteCond %{HTTP:Connection} Upgrade [NC]
    RewriteRule /(.*) ws://localhost:3000/$1 [P,L]

    ProxyPass /nodejs http://localhost:3000/
    ProxyPassReverse /nodejs http://localhost:3000/

    ProxyPass /socket.io http://localhost:3000/socket.io
    ProxyPassReverse /socket.io http://localhost:3000/socket.io

    ProxyPass /socket.io ws://localhost:3000/socket.io
    ProxyPassReverse /socket.io ws://localhost:3000/socket.io

</VirtualHost>
</IfModule>

Then my node.js app (app.js):

var express = require('express');
var app = express();
    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        res.header("Access-Control-Allow-Headers", "Content-Type");
        res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
        next();
    });
var http = require('http').Server(app);
var io = require('socket.io')(http);

http.listen({host:'0.0.0.0',port:3000});

I force a ip4 listener, but that is optional - you can substitute:

http.listen(3000);

node.js app (app.js) code continues with:

io.of('/nodejs').on('connection', function(socket) {
    //optional settings:
    io.set('heartbeat timeout', 3000); 
    io.set('heartbeat interval', 1000);

    //listener for when a user is added
    socket.on('add user', function(data) {
         socket.join('AnyRoomName');
         socket.broadcast.emit('user joined', data);
    });

    //listener for when a user leaves
    socket.on('remove user', function(data) {
         socket.leave('AnyRoomName');
         socket.broadcast.emit('user left', data);
    });

    //sample listener for any other function
    socket.on('named-event', function(data) {
         //code....
         socket.broadcast.emit('named-event-broadcast', data);
    });

    // add more listeners as needed... use different named-events...
});

finally, on the client side (created as nodejs.js):

//notice the /nodejs path
var socket = io.connect('https://www.example.com/nodejs');

//listener for user joined
socket.on('user joined', function(data) {
    // code... data shows who joined...
});

//listener for user left
socket.on('user left', function(data) {
    // code... data shows who left...
});

// sample listener for any function:
socket.on('named-event-broadcast', function(data) {
    // this receives the broadcast data (I use json then parse and execute code)
    console.log('data1=' + data.data1);
    console.log('data2=' + data.data2);
});

// sample send broadcast json data for user joined:
socket.emit('user joined', {
    'userid': 'userid-value',
    'username':'username-value'
});

// sample send broadcast json data for user left 
//(I added the following with an event listener for 'beforeunload'):
// socket.emit('user joined', {
//     'userid': 'userid-value',
//     'username':'username-value'
// });

// sample send broadcast json data for any named-event:
socket.emit('named-event', {
    'data1': 'value1',
    'data2':'value2'
});

In this example when the JS loads, it will emit to the socket a "named-event" sending the data in JSON to the node.js/socket.io server.

Using the io and socket on the server under path /nodejs (connected by client), receives the data an then resends it as a broadcast. Any other users in the socket would receive the data with their listener "named-event-broadcast". Note that the sender does not receive their own broadcast.

How do I get the current date in Cocoa

You need to do something along the lines of the following:

NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:now];
NSLog(@"%d", [components hour]);

And so on.

Navigation Controller Push View Controller

This is working perfect:

PD: Remember to import the destination VC:

#import "DestinationVCName.h"

    - (IBAction)NameOfTheAction:(id)sender 
{
       DestinationVCName *destinationvcname = [self.storyboard instantiateViewControllerWithIdentifier:@"DestinationVCName"];
    [self presentViewController:destinationvcname animated:YES completion:nil];
}

Git Push ERROR: Repository not found

The Problem: Github is not familiar with your repository from some reason.

The Error: prompted in git cli like the following:

remote: Repository not found. fatal: repository ‘https://github.com/MyOrganization/projectName.git/’ not found

The Solution : 2 Options

  1. Github might not familiar with your credentials: - The first Option is to clone the project with the right credentials user:password in case you forgot this Or generate ssh token and adjust this key in your Github. aka git push https://<userName>:<password>@github.com/Company/repositoryName.git

  2. Repo Permissions Issue with some users - In my Use case, I solved this issue when I realized I don't have the right collaborator permissions on Github in my private repo. Users could clone the project but not perform any actions on origin. In order to solve this:

Go to Repository on Github -> Settings -> Collaborators & Teams -> Add Member/Maintainer your users -> Now they got the permission to commit and push

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

Historically, 255 characters has often been the maximum length of a VARCHAR in some DBMSes, and it sometimes still winds up being the effective maximum if you want to use UTF-8 and have the column indexed (because of index length limitations).

Difference between static memory allocation and dynamic memory allocation

Static memory allocation. Memory allocated will be in stack.

int a[10];

Dynamic memory allocation. Memory allocated will be in heap.

int *a = malloc(sizeof(int) * 10);

and the latter should be freed since there is no Garbage Collector(GC) in C.

free(a);

how to list all sub directories in a directory

show all directry and sub directories

def dir():

from glob import glob

dir = []

dir = glob("path")

def all_sub_dir(dir):
{

     for item in dir:

            {
                b = "{}\*".format(item)
                dir += glob(b)
            }
         print(dir)
}

How to include a font .ttf using CSS?

Did you try format?

@font-face {
  font-family: 'The name of the Font Family Here';
  src: URL('font.ttf') format('truetype');
}

Read this article: http://css-tricks.com/snippets/css/using-font-face/

Also, might depend on browser as well.

Decompile an APK, modify it and then recompile it

I know this question has been answered and I am not trying to give better answer here. I'll just share my experience in this topic.

Once I lost my code and I had the apk file only. I decompiled it using the tool below and it made my day.

These tools MUST be used in such situation, otherwise, it is unethical and even sometimes it is illegal, (stealing somebody else's effort). So please use it wisely.

Those are my favorite tools for doing that:

javadecompilers.com

and to get the apk from google play you can google it or check out those sites:

On the date of posting this answer I tested all the links and it worked perfect for me.

NOTE: Apk Decompiling is not effective in case of proguarded code. Because Proguard shrink and obfuscates the code and rename classes to nonsense names which make it fairly hard to understand the code.

Bonus:

Basic tutorial of Using Proguard:

How do I add comments to package.json for npm install?

You can always abuse the fact that duplicated keys are overwritten. This is what I just wrote:

"dependencies": {
  "grunt": "...",
  "grunt-cli": "...",

  "api-easy": "# Here is the pull request: https://github.com/...",
  "api-easy": "git://..."

  "grunt-vows": "...",
  "vows": "..."
}

However, it is not clear whether JSON allows duplicated keys (see Does JSON syntax allow duplicate keys in an object?. It seems to work with npm, so I take the risk.

The recommened hack is to use "//" keys (from the nodejs mailing list). When I tested it, it did not work with "dependencies" sections, though. Also, the example in the post uses multiple "//" keys, which implies that npm does not reject JSON files with duplicated keys. In other words, the hack above should always be fine.

Update: One annoying disadvantage of the duplicated key hack is that npm install --save silently eliminates all duplicates. Unfortunately, it is very easy to overlook it and your well-intentioned comments are gone.

The "//" hack is still the safest as it seems. However, multi-line comments will be removed by npm install --save, too.

In Jinja2, how do you test if a variable is undefined?

You could also define a variable in a jinja2 template like this:

{% if step is not defined %}
{% set step = 1 %}
{% endif %}

And then You can use it like this:

{% if step == 1 %}
<div class="col-xs-3 bs-wizard-step active">
{% elif step > 1 %}
<div class="col-xs-3 bs-wizard-step complete">
{% else %}
<div class="col-xs-3 bs-wizard-step disabled">
{% endif %}

Otherwise (if You wouldn't use {% set step = 1 %}) the upper code would throw:

UndefinedError: 'step' is undefined

Add button to a layout programmatically

This line:

layout = (LinearLayout) findViewById(R.id.statsviewlayout);

Looks for the "statsviewlayout" id in your current 'contentview'. Now you've set that here:

setContentView(new GraphTemperature(getApplicationContext()));

And i'm guessing that new "graphTemperature" does not set anything with that id.

It's a common mistake to think you can just find any view with findViewById. You can only find a view that is in the XML (or appointed by code and given an id).

The nullpointer will be thrown because the layout you're looking for isn't found, so

layout.addView(buyButton);

Throws that exception.

addition: Now if you want to get that view from an XML, you should use an inflater:

layout = (LinearLayout) View.inflate(this, R.layout.yourXMLYouWantToLoad, null);

assuming that you have your linearlayout in a file called "yourXMLYouWantToLoad.xml"

Spring MVC - Why not able to use @RequestBody and @RequestParam together

The @RequestBody javadoc states

Annotation indicating a method parameter should be bound to the body of the web request.

It uses registered instances of HttpMessageConverter to deserialize the request body into an object of the annotated parameter type.

And the @RequestParam javadoc states

Annotation which indicates that a method parameter should be bound to a web request parameter.

  1. Spring binds the body of the request to the parameter annotated with @RequestBody.

  2. Spring binds request parameters from the request body (url-encoded parameters) to your method parameter. Spring will use the name of the parameter, ie. name, to map the parameter.

  3. Parameters are resolved in order. The @RequestBody is processed first. Spring will consume all the HttpServletRequest InputStream. When it then tries to resolve the @RequestParam, which is by default required, there is no request parameter in the query string or what remains of the request body, ie. nothing. So it fails with 400 because the request can't be correctly handled by the handler method.

  4. The handler for @RequestParam acts first, reading what it can of the HttpServletRequest InputStream to map the request parameter, ie. the whole query string/url-encoded parameters. It does so and gets the value abc mapped to the parameter name. When the handler for @RequestBody runs, there's nothing left in the request body, so the argument used is the empty string.

  5. The handler for @RequestBody reads the body and binds it to the parameter. The handler for @RequestParam can then get the request parameter from the URL query string.

  6. The handler for @RequestParam reads from both the body and the URL query String. It would usually put them in a Map, but since the parameter is of type String, Spring will serialize the Map as comma separated values. The handler for @RequestBody then, again, has nothing left to read from the body.

Remove Project from Android Studio

The location of SDK is incorrect, the name of one filer is with place this is creating an issue. By removing that space issue will be resolved. old SDK location:

C:\Users\At Tech\AppData\Local\Android\Sdk

new SDK location:

F:\AndroidSDK\Sdk

Is it possible to get an Excel document's row count without loading the entire document into memory?

This might be extremely convoluted and I might be missing the obvious, but without OpenPyXL filling in the column_dimensions in Iterable Worksheets (see my comment above), the only way I can see of finding the column size without loading everything is to parse the xml directly:

from xml.etree.ElementTree import iterparse
from openpyxl import load_workbook
wb=load_workbook("/path/to/workbook.xlsx", use_iterators=True)
ws=wb.worksheets[0]
xml = ws._xml_source
xml.seek(0)

for _,x in iterparse(xml):

    name= x.tag.split("}")[-1]
    if name=="col":
        print "Column %(max)s: Width: %(width)s"%x.attrib # width = x.attrib["width"]

    if name=="cols":
        print "break before reading the rest of the file"
        break

how to change php version in htaccess in server

An addition to the current marked answer:

Place the addhandler inside the following scope, like so:

<IfModule mod_rewrite.c>

   AddHandler application/x-httpd-php71 .php
   RewriteEngine On

   ....

</IfModule>

How do I configure Notepad++ to use spaces instead of tabs?

I have NotePad++ v6.8.3, and it was in Settings ? Preferences ? Tab Settings ? [Default] ? Replace by space:

NotePad++ Preferences

NotePad++ Tab Settings

IDENTITY_INSERT is set to OFF - How to turn it ON?

Should you instead be setting the identity insert to on within the stored procedure? It looks like you're setting it to on only when changing the stored procedure, not when actually calling it. Try:

ALTER procedure [dbo].[spInsertDeletedIntoTBLContent]
@ContentID int, 

SET IDENTITY_INSERT tbl_content ON

...insert command...

SET IDENTITY_INSERT tbl_content OFF
GO

EditText, inputType values (xml)

You can use the properties tab in eclipse to set various values.

here are all the possible values

  • none
  • text
  • textCapCharacters
  • textCapWords
  • textCapSentences
  • textAutoCorrect
  • textAutoComplete
  • textMultiLine
  • textImeMultiLine
  • textNoSuggestions
  • textUri
  • textEmailAddress
  • textEmailSubject
  • textShortMessage
  • textLongMessage
  • textPersonName
  • textPostalAddress
  • textPassword
  • textVisiblePassword
  • textWebEditText
  • textFilter
  • textPhonetic
  • textWebEmailAddress
  • textWebPassword
  • number
  • numberSigned
  • numberDecimal
  • numberPassword
  • phone
  • datetime
  • date
  • time

Check here for explanations: http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType

jQuery using append with effects

Something like:

$('#test').append('<div id="newdiv">Hello</div>').hide().show('slow');

should do it?

Edit: sorry, mistake in code and took Matt's suggestion on board too.

Java: How to convert a File object to a String object in java?

I use apache common IO to read a text file into a single string

String str = FileUtils.readFileToString(file);

simple and "clean". you can even set encoding of the text file with no hassle.

String str = FileUtils.readFileToString(file, "UTF-8");

How to enter special characters like "&" in oracle database?

Justin's answer is the way to go, but also as an FYI you can use the chr() function with the ascii value of the character you want to insert. For this example it would be:

INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 '||chr(38)||' Oracle_14'); 

How to create a density plot in matplotlib?

Option 1:

Use pandas dataframe plot (built on top of matplotlib):

import pandas as pd
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
pd.DataFrame(data).plot(kind='density') # or pd.Series()

enter image description here

Option 2:

Use distplot of seaborn:

import seaborn as sns
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
sns.distplot(data, hist=False)

enter image description here

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

Some simpler example code for using globalAlpha:

ctx.save();
ctx.globalAlpha = 0.4;
ctx.drawImage(img, x, y);
ctx.restore();

If you need img to be loaded:

var img = new Image();
img.onload = function() {
    ctx.save();
    ctx.globalAlpha = 0.4;
    ctx.drawImage(img, x, y);
    ctx.restore()
};
img.src = "http://...";

Notes:

  • Set the 'src' last, to guarantee that your onload handler is called on all platforms, even if the image is already in the cache.

  • Wrap changes to stuff like globalAlpha between a save and restore (in fact use them lots), to make sure you don't clobber settings from elsewhere, particularly when bits of drawing code are going to be called from events.

How do I ignore files in a directory in Git?

PATTERN FORMAT

  • A blank line matches no files, so it can serve as a separator for readability.

  • A line starting with # serves as a comment.

  • An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

  • If the pattern ends with a slash, it is removed for the purpose of the following description, but it would only find a match with a directory. In other words, foo/ will match a directory foo and paths underneath it, but will not match a regular file or a symbolic link foo (this is consistent with the way how pathspec works in general in git).

  • If the pattern does not contain a slash /, git treats it as a shell glob pattern and checks for a match against the pathname relative to the location of the .gitignore file (relative to the toplevel of the work tree if not from a .gitignore file).

  • Otherwise, git treats the pattern as a shell glob suitable for consumption by fnmatch(3) with the FNM_PATHNAME flag: wildcards in the pattern will not match a / in the pathname. For example, Documentation/*.html matches Documentation/git.html but not Documentation/ppc/ppc.html or tools/perf/Documentation/perf.html.

  • A leading slash matches the beginning of the pathname. For example, /*.c matches cat-file.c but not mozilla-sha1/sha1.c.

You can find more here

git help gitignore
or
man gitignore

WHERE statement after a UNION in SQL?

If you want to apply the WHERE clause to the result of the UNION, then you have to embed the UNION in the FROM clause:

SELECT *
  FROM (SELECT * FROM TableA
        UNION
        SELECT * FROM TableB
       ) AS U
 WHERE U.Col1 = ...

I'm assuming TableA and TableB are union-compatible. You could also apply a WHERE clause to each of the individual SELECT statements in the UNION, of course.

C# - Making a Process.Start wait until the process has start-up

I agree with Tom. In addition, to check the processes while performing Thread.Sleep, check the running processes. Something like:

bool found = 0;
while (!found)
{
    foreach (Process clsProcess in Process.GetProcesses())
        if (clsProcess.Name == Name)
            found = true;

    Thread.CurrentThread.Sleep(1000);
}

How to have Java method return generic list of any type?

You can simply cast to List and then check if every element can be casted to T.

public <T> List<T> asList(final Class<T> clazz) {
    List<T> values = (List<T>) this.value;
    values.forEach(clazz::cast);
    return values;
}

How to get records randomly from the oracle database?

In case of huge tables standard way with sorting by dbms_random.value is not effective because you need to scan whole table and dbms_random.value is pretty slow function and requires context switches. For such cases, there are 3 additional methods:


1: Use sample clause:

for example:

select *
from s1 sample block(1)
order by dbms_random.value
fetch first 1 rows only

ie get 1% of all blocks, then sort them randomly and return just 1 row.


2: if you have an index/primary key on the column with normal distribution, you can get min and max values, get random value in this range and get first row with a value greater or equal than that randomly generated value.

Example:

--big table with 1 mln rows with primary key on ID with normal distribution:
Create table s1(id primary key,padding) as 
   select level, rpad('x',100,'x')
   from dual 
   connect by level<=1e6;

select *
from s1 
where id>=(select 
              dbms_random.value(
                 (select min(id) from s1),
                 (select max(id) from s1) 
              )
           from dual)
order by id
fetch first 1 rows only;

3: get random table block, generate rowid and get row from the table by this rowid:

select * 
from s1
where rowid = (
   select
      DBMS_ROWID.ROWID_CREATE (
         1, 
         objd,
         file#,
         block#,
         1) 
   from    
      (
      select/*+ rule */ file#,block#,objd
      from v$bh b
      where b.objd in (select o.data_object_id from user_objects o where object_name='S1' /* table_name */)
      order by dbms_random.value
      fetch first 1 rows only
      )
);

What does $ mean before a string?

I don't know how it works, but you can also use it to tab your values !

Example :

Console.WriteLine($"I can tab like {"this !", 5}.");

Of course, you can replace "this !" with any variable or anything meaningful, just as you can also change the tab.

Using import fs from 'fs'

In order to use import { readFileSync } from 'fs', you have to:

  1. Be using Node.js 10 or later
  2. Use the --experimental-modules flag (in Node.js 10), e.g. node --experimental-modules server.mjs (see #3 for explanation of .mjs)
  3. Rename the file extension of your file with the import statements, to .mjs, .js will not work, e.g. server.mjs

The other answers hit on 1 and 2, but 3 is also necessary. Also, note that this feature is considered extremely experimental at this point (1/10 stability) and not recommended for production, but I will still probably use it.

Here's the Node.js 10 ESM documentation.

CAST to DECIMAL in MySQL

From MySQL docs: Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC:

In standard SQL, the syntax DECIMAL(M) is equivalent to DECIMAL(M,0)

So, you are converting to a number with 2 integer digits and 0 decimal digits. Try this instead:

CAST((COUNT(*) * 1.5) AS DECIMAL(12,2)) 

Number to String in a formula field

I believe this is what you're looking for:

Convert Decimal Numbers to Text showing only the non-zero decimals

Especially this line might be helpful:

StringVar text     :=  Totext ( {Your.NumberField} , 6 , ""  )  ;

The first parameter is the decimal to be converted, the second parameter is the number of decimal places and the third parameter is the separator for thousands/millions etc.

.htaccess rewrite to redirect root URL to subdirectory

This will try the subdir if the file doesn't exist in the root. Needed this as I moved a basic .html website that expects to be ran at the root level and pushed it to a subdir. Only works if all files are flat (no .htaccess trickery in the subdir possible). Useful for linked things like css and js files.

# Internal Redirect to subdir if file is found there.
RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_URI} !-s
RewriteCond %{DOCUMENT_ROOT}/subdir/%{REQUEST_URI} -s
RewriteRule ^(.*)$ /subdir/$1 [L]

Do I need to convert .CER to .CRT for Apache SSL certificates? If so, how?

I assume that you have a .cer file containing PKCS#7-encoded certificate data and you want to convert it to PEM-encoded certificate data (typically a .crt or .pem file). For instance, a .cer file containing PKCS#7-encoded data looks like this:

-----BEGIN PKCS7-----
MIIW4gYJKoZIhvcNAQcCoIIW0zCCFs8CAQExADALBgkqhkiG9w0BBwGggha1MIIH
...
POI9n9cd2cNgQ4xYDiKWL2KjLB+6rQXvqzJ4h6BUcxm1XAX5Uj5tLUUL9wqT6u0G
+bKhADEA
-----END PKCS7-----

PEM certificate data looks like this:

-----BEGIN CERTIFICATE-----
MIIHNjCCBh6gAwIBAgIQAlBxtqKazsxUSR9QdWWxaDANBgkqhkiG9w0BAQUFADBm
...
nv72c/OV4nlyrvBLPoaS5JFUJvFUG8RfAEY=
-----END CERTIFICATE-----

There is an OpenSSL command that will convert .cer files (with PKCS#7 data) to the PEM data you may be expecting to encounter (the BEGIN CERTIFICATE block in the example above). You can coerce PKCS#7 data into PEM format by this command on a file we'll call certfile.cer:

openssl pkcs7 -text -in certfile.cer -print_certs -outform PEM -out certfile.pem

Note that a .cer or .pem file might contain one or more certificates (possibly the entire certificate chain).

PHP cURL HTTP CODE return 0

What is the exact contents you are passing into $html_brand?

If it is has an invalid URL syntax, you will very likely get the HTTP code 0.

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

From a Java specification summary: http://www.cs.cornell.edu/andru/javaspec/17.doc.html

The synchronized statement (§14.17) computes a reference to an object; it then attempts to perform a lock action on that object and does not proceed further until the lock action has successfully completed. ...

A synchronized method (§8.4.3.5) automatically performs a lock action when it is invoked; its body is not executed until the lock action has successfully completed. If the method is an instance method, it locks the lock associated with the instance for which it was invoked (that is, the object that will be known as this during execution of the body of the method). If the method is static, it locks the lock associated with the Class object that represents the class in which the method is defined. ...

Based on these descriptions, I would say most previous answers are correct, and a synchronized method might be particularly useful for static methods, where you would otherwise have to figure out how to get the "Class object that represents the class in which the method was defined."

Edit: I originally thought these were quotes of the actual Java spec. Clarified that this page is just a summary/explanation of the spec

How to retrieve element value of XML using Java?

If your XML is a String, Then you can do the following:

String xml = ""; //Populated XML String....

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
Element rootElement = document.getDocumentElement();

If your XML is in a file, then Document document will be instantiated like this:

Document document = builder.parse(new File("file.xml"));

The document.getDocumentElement() returns you the node that is the document element of the document (in your case <config>).

Once you have a rootElement, you can access the element's attribute (by calling rootElement.getAttribute() method), etc. For more methods on java's org.w3c.dom.Element

More info on java DocumentBuilder & DocumentBuilderFactory. Bear in mind, the example provided creates a XML DOM tree so if you have a huge XML data, the tree can be huge.


Update Here's an example to get "value" of element <requestqueue>

protected String getString(String tagName, Element element) {
        NodeList list = element.getElementsByTagName(tagName);
        if (list != null && list.getLength() > 0) {
            NodeList subList = list.item(0).getChildNodes();

            if (subList != null && subList.getLength() > 0) {
                return subList.item(0).getNodeValue();
            }
        }

        return null;
    }

You can effectively call it as,

String requestQueueName = getString("requestqueue", element);

How to perform mouseover function in Selenium WebDriver using Java?

Sample program to mouse hover using Selenium java WebDriver :

public class Mhover {
    public static void main(String[] args){
       WebDriver driver = new FirefoxDriver();
       driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
       driver.get("http://www.google.com");
       WebElement ele = driver.findElement(By.id("gbqfba"));
       Actions action = new Actions(driver);
       action.moveToElement(ele).build().perform();
    }
}

Mongoose query where value is not null

I ended up here and my issue was that I was querying for

{$not: {email: /@domain.com/}}

instead of

{email: {$not: /@domain.com/}}

Checking network connection

You can just try to download data, and if connection fail you will know that somethings with connection isn't fine.

Basically you can't check if computer is connected to internet. There can be many reasons for failure, like wrong DNS configuration, firewalls, NAT. So even if you make some tests, you can't have guaranteed that you will have connection with your API until you try.

Make cross-domain ajax JSONP request with jQuery

alert(xml.data[0].city);

use xml.data["Data"][0].city instead

How to retrieve Jenkins build parameters using the Groovy API?

Regarding parameters:

See this answer first. To get a list of all the builds for a project (obtained as per that answer):

project.builds

When you find your particular build, you need to get all actions of type ParametersAction with build.getActions(hudson.model.ParametersAction). You then query the returned object for your specific parameters.

Regarding p4.change: I suspect that it is also stored as an action. In Jenkins Groovy console get all actions for a build that contains p4.change and examine them - it will give you an idea what to look for in your code.

Jquery: How to check if the element has certain css class/style

if ($("element class or id name").css("property") == "value") {
    your code....
}

Inheritance with base class constructor with parameters

I could be wrong, but I believe since you are inheriting from foo, you have to call a base constructor. Since you explicitly defined the foo constructor to require (int, int) now you need to pass that up the chain.

public bar(int a, int b) : base(a, b)
{
     c = a * b;
}

This will initialize foo's variables first and then you can use them in bar. Also, to avoid confusion I would recommend not naming parameters the exact same as the instance variables. Try p_a or something instead, so you won't accidentally be handling the wrong variable.

How does the vim "write with sudo" trick work?

The only problem with cnoremap w!! is that it replaces w with ! (and hangs until you type the next char) whenever you type w! at the : command prompt. Like when you want to actually force-save with w!. Also, even if it's not the first thing after :.

Therefore I would suggest mapping it to something like <Fn>w. I personally have mapleader = F1, so I'm using <Leader>w.

I want to convert std::string into a const wchar_t *

First convert it to std::wstring:

std::wstring widestr = std::wstring(str.begin(), str.end());

Then get the C string:

const wchar_t* widecstr = widestr.c_str();

This only works for ASCII strings, but it will not work if the underlying string is UTF-8 encoded. Using a conversion routine like MultiByteToWideChar() ensures that this scenario is handled properly.

Free tool to Create/Edit PNG Images?

Paint.NET will create and edit PNGs with gusto. It's an excellent program in many respects. It's free as in beer and speech.

Converting java.sql.Date to java.util.Date

From reading the source code, if a java.sql.Date does actually have time information, calling getTime() will return a value that includes the time information.

If that is not working, then the information is not in the java.sql.Date object. I expect that the JDBC drivers or the database is (in effect) zeroing the time component ... or the information wasn't there in the first place.

I think you should be using java.sql.Timestamp and the corresponding resultset methods, and the corresponding SQL type.

How do you programmatically set an attribute?

Also works fine within a class:

def update_property(self, property, value):
   setattr(self, property, value)

What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

If you want to test if an object is strictly or extends a Hash, use:

value = {}
value.is_a?(Hash) || value.is_a?(Array) #=> true

But to make value of Ruby's duck typing, you could do something like:

value = {}
value.respond_to?(:[]) #=> true

It is useful when you only want to access some value using the value[:key] syntax.

Please note that Array.new["key"] will raise a TypeError.

iterrows pandas get next rows value

Firstly, your "messy way" is ok, there's nothing wrong with using indices into the dataframe, and this will not be too slow. iterrows() itself isn't terribly fast.

A version of your first idea that would work would be:

row_iterator = df.iterrows()
_, last = row_iterator.next()  # take first item from row_iterator
for i, row in row_iterator:
    print(row['value'])
    print(last['value'])
    last = row

The second method could do something similar, to save one index into the dataframe:

last = df.irow(0)
for i in range(1, df.shape[0]):
    print(last)
    print(df.irow(i))
    last = df.irow(i)

When speed is critical you can always try both and time the code.

What is the difference between HTTP_HOST and SERVER_NAME in PHP?

As I mentioned in this answer, if the server runs on a port other than 80 (as might be common on a development/intranet machine) then HTTP_HOST contains the port, while SERVER_NAME does not.

$_SERVER['HTTP_HOST'] == 'localhost:8080'
$_SERVER['SERVER_NAME'] == 'localhost'

(At least that's what I've noticed in Apache port-based virtualhosts)

Note that HTTP_HOST does not contain :443 when running on HTTPS (unless you're running on a non-standard port, which I haven't tested).

As others have noted, the two also differ when using IPv6:

$_SERVER['HTTP_HOST'] == '[::1]'
$_SERVER['SERVER_NAME'] == '::1'

How to prevent form from submitting multiple times from client side?

This allow submit every 2 seconds. In case of front validation.

$(document).ready(function() {
    $('form[debounce]').submit(function(e) {
        const submiting = !!$(this).data('submiting');

        if(!submiting) {
            $(this).data('submiting', true);

            setTimeout(() => {
                $(this).data('submiting', false);
            }, 2000);

            return true;
        }

        e.preventDefault();
        return false;
    });
})

Select Top and Last rows in a table (SQL server)

To get the bottom 1000 you will want to order it by a column in descending order, and still take the top 1000.

SELECT TOP 1000 *
FROM [SomeTable]
ORDER BY MySortColumn DESC

If you care for it to be in the same order as before you can use a common table expression for that:

;WITH CTE AS (
    SELECT TOP 1000 *
    FROM [SomeTable]
    ORDER BY MySortColumn DESC
)

SELECT * 
FROM CTE
ORDER BY MySortColumn

How can I generate a unique ID in Python?

unique and random are mutually exclusive. perhaps you want this?

import random
def uniqueid():
    seed = random.getrandbits(32)
    while True:
       yield seed
       seed += 1

Usage:

unique_sequence = uniqueid()
id1 = next(unique_sequence)
id2 = next(unique_sequence)
id3 = next(unique_sequence)
ids = list(itertools.islice(unique_sequence, 1000))

no two returned id is the same (Unique) and this is based on a randomized seed value

Create intermediate folders if one doesn't exist

You have to actually call some method to create the directories. Just creating a file object will not create the corresponding file or directory on the file system.

You can use File#mkdirs() method to create the directory: -

theFile.mkdirs();

Difference between File#mkdir() and File#mkdirs() is that, the later will create any intermediate directory if it does not exist.

Should I use "camel case" or underscores in python?

for everything related to Python's style guide: i'd recommend you read PEP8.

To answer your question:

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default

I found that the direct cause for the error in my case was:

build -> advanced -> language version

this makes sense since the error is stating that there is an invalid option for language.

but, this was working fine before - so it must've been selected. what changed? turns out a member on my team upgraded to vs 2017, while i was still using 2015. after he made changes to the project, the language version was changed and i received that change over source control. but the version selected was not available to my version of vs, so it was blank - hence the error. after selecting a value in the language drop down (i chose default), a new error popped up. the new error was causing a build failure on any lines of code which used the newer version of c#. i changed the code to perform the same functions, but with my c# version syntax and problem solved.

so while the direct cause of the error was indeed an invalid selection of Language Version, the root cause was due to different vs/c# versions conflicting.

How to list all installed packages and their versions in Python?

from command line

python -c help('modules')

can be used to view all modules, and for specific modules

python -c help('os')

For Linux below will work

python -c "help('os')"

What exactly does Double mean in java?

In a comment on @paxdiablo's answer, you asked:

"So basically, is it better to use Double than Float?"

That is a complicated question. I will deal with it in two parts


Deciding between double versus float

On the one hand, a double occupies 8 bytes versus 4 bytes for a float. If you have many of them, this may be significant, though it may also have no impact. (Consider the case where the values are in fields or local variables on a 64bit machine, and the JVM aligns them on 64 bit boundaries.) Additionally, floating point arithmetic with double values is typically slower than with float values ... though once again this is hardware dependent.

On the other hand, a double can represent larger (and smaller) numbers than a float and can represent them with more than twice the precision. For the details, refer to Wikipedia.

The tricky question is knowing whether you actually need the extra range and precision of a double. In some cases it is obvious that you need it. In others it is not so obvious. For instance if you are doing calculations such as inverting a matrix or calculating a standard deviation, the extra precision may be critical. On the other hand, in some cases not even double is going to give you enough precision. (And beware of the trap of expecting float and double to give you an exact representation. They won't and they can't!)

There is a branch of mathematics called Numerical Analysis that deals with the effects of rounding error, etc in practical numerical calculations. It used to be a standard part of computer science courses ... back in the 1970's.


Deciding between Double versus Float

For the Double versus Float case, the issues of precision and range are the same as for double versus float, but the relative performance measures will be slightly different.

  • A Double (on a 32 bit machine) typically takes 16 bytes + 4 bytes for the reference, compared with 12 + 4 bytes for a Float. Compare this to 8 bytes versus 4 bytes for the double versus float case. So the ratio is 5 to 4 versus 2 to 1.

  • Arithmetic involving Double and Float typically involves dereferencing the pointer and creating a new object to hold the result (depending on the circumstances). These extra overheads also affect the ratios in favor of the Double case.


Correctness

Having said all that, the most important thing is correctness, and this typically means getting the most accurate answer. And even if accuracy is not critical, it is usually not wrong to be "too accurate". So, the simple "rule of thumb" is to use double in preference to float, UNLESS there is an overriding performance requirement, AND you have solid evidence that using float will make a difference with respect to that requirement.

Binding value to style

As of now (Jan 2017 / Angular > 2.0) you can use the following:

changeBackground(): any {
    return { 'background-color': this.color };
}

and

<div class="circle" [ngStyle]="changeBackground()">
    <!-- <content></content> --> <!-- content is now deprecated -->
    <ng-content><ng-content> <!-- Use ng-content instead -->
</div>

The shortest way is probably like this:

<div class="circle" [ngStyle]="{ 'background-color': color }">
    <!-- <content></content> --> <!-- content is now deprecated -->
    <ng-content><ng-content> <!-- Use ng-content instead -->
</div>

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

I had this same problem, but I'm a Linux user.

I resolved the problem by reattempting the installation with adminstrator privileges. [For those Linux users reading this, I ran studio.sh with sudo.]

How to remove all the null elements inside a generic list in one go?

There is another simple and elegant option:

parameters.OfType<EmailParameterClass>();

This will remove all elements that are not of type EmailParameterClass which will obviously filter out any elements of type null.

Here's a test:

class Test { }
class Program
{
    static void Main(string[] args)
    {
        var list = new List<Test>();
        list.Add(null);
        Console.WriteLine(list.OfType<Test>().Count());// 0
        list.Add(new Test());
        Console.WriteLine(list.OfType<Test>().Count());// 1
        Test test = null;
        list.Add(test);
        Console.WriteLine(list.OfType<Test>().Count());// 1
        Console.ReadKey();
    }
}

How can I convert a Unix timestamp to DateTime and vice versa?

Unix time conversion is new in .NET Framework 4.6.

You can now more easily convert date and time values to or from .NET Framework types and Unix time. This can be necessary, for example, when converting time values between a JavaScript client and .NET server. The following APIs have been added to the DateTimeOffset structure:

static DateTimeOffset FromUnixTimeSeconds(long seconds)
static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds)
long DateTimeOffset.ToUnixTimeSeconds()
long DateTimeOffset.ToUnixTimeMilliseconds()

Toolbar overlapping below status bar

According google docs ,we should not use fitsSystemWindows attribute in app theme, it is intended to use in layout files. Using in themes can causes problem in toast messages .

Check Issue here & example of problem caused here

<item name="android:fitsSystemWindows">true</item>

Example of using correct way and which works fine with windowTranslucentStatus as well.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"

android:fitsSystemWindows="true"

android:layout_width="match_parent"
android:layout_height="match_parent"
> 


<include layout="@layout/toolbar"
     android:layout_width="match_parent"
     android:layout_height="wrap_content">
</include>

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    android:background="@color/white"
    android:animateLayoutChanges="true"
    app:headerLayout="@layout/navigation_drawer_header"
    app:menu="@menu/navigation_drawer_menu" />

</android.support.v4.widget.DrawerLayout>

How to dynamically create columns in datatable and assign values to it?

If you want to create dynamically/runtime data table in VB.Net then you should follow these steps as mentioned below :

  • Create Data table object.
  • Add columns into that data table object.
  • Add Rows with values into the object.

For eg.

Dim dt As New DataTable

dt.Columns.Add("Id", GetType(Integer))
dt.Columns.Add("FirstName", GetType(String))
dt.Columns.Add("LastName", GetType(String))

dt.Rows.Add(1, "Test", "data")
dt.Rows.Add(15, "Robert", "Wich")
dt.Rows.Add(18, "Merry", "Cylon")
dt.Rows.Add(30, "Tim", "Burst")

How add unique key to existing table (with non uniques rows)

For MySQL:

ALTER TABLE MyTable ADD MyId INT AUTO_INCREMENT PRIMARY KEY;

Best way to create a simple python web service

The simplest way to get a Python script online is to use CGI:

#!/usr/bin/python

print "Content-type: text/html"
print

print "<p>Hello world.</p>"

Put that code in a script that lives in your web server CGI directory, make it executable, and run it. The cgi module has a number of useful utilities when you need to accept parameters from the user.

How to enter quotes in a Java string?

In Java, you can use char value with ":

char quotes ='"';

String strVar=quotes+"ROM"+quotes;

Convert integers to strings to create output filenames at run time

A much easier solution IMHO ...................

character(len=8) :: fmt ! format descriptor

fmt = '(I5.5)' ! an integer of width 5 with zeros at the left

i1= 59

write (x1,fmt) i1 ! converting integer to string using a 'internal file'

filename='output'//trim(x1)//'.dat'

! ====> filename: output00059.dat

Twitter Bootstrap inline input with dropdown

This is the code for Bootstrap with input search dropdown. I search a lot then i try its in javascript and html with bootstrap,

HTML Code :

<div class="form-group">
    <label class="col-xs-3 control-label">Language</label>
    <div class="col-xs-7">
        <div class="dropdown">
          <button id="mydef" class="btn dropdown-toggle" type="button" data-toggle="dropdown" onclick="doOn(this);">
            <div class="col-xs-10">
                <input type="text" id="search" placeholder="search" onkeyup="doOn(this);"></input>
            </div>
            <span class="glyphicon glyphicon-search"></span>
         </button>
      <ul id="def" class="dropdown-menu" style="display:none;" >
            <li><a id="HTML" onclick="mydef(this);" >HTML</a></li>
            <li><a id="CSS" onclick="mydef(this);" >CSS</a></li>
            <li><a id="JavaScript" onclick="mydef(this);" >JavaScript</a></li>
      </ul>
      <ul id="def1" class="dropdown-menu" style="display:none"></ul>
    </div>
</div>

Javascript Code :

function doOn(obj)
     {

        if(obj.id=="mydef")
        {
            document.getElementById("def1").style.display="none";
            document.getElementById("def").style.display="block";
        }
        if(obj.id=="search")
        {
            document.getElementById("def").style.display="none";

            document.getElementById("def1").innerHTML='<li><a id="Java" onclick="mydef(this);" >java</a></li><li><a id="oracle" onclick="mydef(this);" >Oracle</a></li>';

            document.getElementById("def1").style.display="block";
        }

    }
    function mydef(obj)
    {
        document.getElementById("search").value=obj.innerHTML;
        document.getElementById("def1").style.display="none";
        document.getElementById("def").style.display="none";
    }

You can use jquery and json code also as per your requirement.

Output like: enter image description here

enter image description here

enter image description here

while installing vc_redist.x64.exe, getting error "Failed to configure per-machine MSU package."

Posting answer to my own question as I found it here and was hidden in bottom somewhere -

https://social.msdn.microsoft.com/Forums/vstudio/en-US/64baed8c-b00c-40d5-b19a-99b26a11516e/visual-c-redistributable-for-visual-studio-2015-rc-fails-on-windows-server-2012?forum=vssetup

This is because the OS failed to install the required update Windows8.1-KB2999226-x64.msu.

However, you can install it by extracting that update to a folder (e.g. XXXX), and execute following cmdlet. You can find the Windows8.1-KB2999226-x64.msu at below.

C:\ProgramData\Package Cache\469A82B09E217DDCF849181A586DF1C97C0C5C85\packages\Patch\amd64\Windows8.1-KB2999226-x64.msu

copy this file to a folder you like, and

Create a folder XXXX in that and execute following commands from Admin command propmt

wusa.exe Windows8.1-KB2999226-x64.msu /extract:XXXX

DISM.exe /Online /Add-Package /PackagePath:XXXX\Windows8.1-KB2999226-x64.cab

vc_redist.x64.exe /repair

(last command need not be run. Just execute vc_redist.x64.exe once again)

this worked for me.

Android check permission for LocationManager

Use my custome class to check or request permisson

public class Permissons {

        //Request Permisson
        public static void Request_STORAGE(Activity act,int code)
        {

            ActivityCompat.requestPermissions(act, new
                    String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},code);
        }
        public static void Request_CAMERA(Activity act,int code)
        {
            ActivityCompat.requestPermissions(act, new
                    String[]{Manifest.permission.CAMERA},code);
        }
        public static void Request_FINE_LOCATION(Activity act,int code)
        {
            ActivityCompat.requestPermissions(act, new
                    String[]{Manifest.permission.ACCESS_FINE_LOCATION},code);
        }
        public static void Request_READ_SMS(Activity act,int code)
        {
            ActivityCompat.requestPermissions(act, new
                    String[]{Manifest.permission.READ_SMS},code);
        }
        public static void Request_READ_CONTACTS(Activity act,int code)
        {
            ActivityCompat.requestPermissions(act, new
                    String[]{Manifest.permission.READ_CONTACTS},code);
        }
        public static void Request_READ_CALENDAR(Activity act,int code)
        {
            ActivityCompat.requestPermissions(act, new
                    String[]{Manifest.permission.READ_CALENDAR},code);
        }
        public static void Request_RECORD_AUDIO(Activity act,int code)
        {
            ActivityCompat.requestPermissions(act, new
                    String[]{Manifest.permission.RECORD_AUDIO},code);
        }

        //Check Permisson
        public static boolean Check_STORAGE(Activity act)
        {
            int result = ContextCompat.checkSelfPermission(act,android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
            return result == PackageManager.PERMISSION_GRANTED;
        }
        public static boolean Check_CAMERA(Activity act)
        {
            int result = ContextCompat.checkSelfPermission(act, Manifest.permission.CAMERA);
            return result == PackageManager.PERMISSION_GRANTED;
        }
        public static boolean Check_FINE_LOCATION(Activity act)
        {
            int result = ContextCompat.checkSelfPermission(act, Manifest.permission.ACCESS_FINE_LOCATION);
            return result == PackageManager.PERMISSION_GRANTED;
        }
        public static boolean Check_READ_SMS(Activity act)
        {
            int result = ContextCompat.checkSelfPermission(act, Manifest.permission.READ_SMS);
            return result == PackageManager.PERMISSION_GRANTED;
        }
        public static boolean Check_READ_CONTACTS(Activity act)
        {
            int result = ContextCompat.checkSelfPermission(act, Manifest.permission.READ_CONTACTS);
            return result == PackageManager.PERMISSION_GRANTED;
        }
        public static boolean Check_READ_CALENDAR(Activity act)
        {
            int result = ContextCompat.checkSelfPermission(act, Manifest.permission.READ_CALENDAR);
            return result == PackageManager.PERMISSION_GRANTED;
        }
        public static boolean Check_RECORD_AUDIO(Activity act)
        {
            int result = ContextCompat.checkSelfPermission(act, Manifest.permission.RECORD_AUDIO);
            return result == PackageManager.PERMISSION_GRANTED;
        }
    }

Example

if(!Permissons.Check_STORAGE(MainActivity.this))
{
   //if not permisson granted so request permisson with request code
   Permissons.Request_STORAGE(MainActivity.this,22);
}

How to determine the screen width in terms of dp or dip at runtime in Android?

DisplayMetrics displayMetrics = new DisplayMetrics();

getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

int width_px = Resources.getSystem().getDisplayMetrics().widthPixels;

int height_px =Resources.getSystem().getDisplayMetrics().heightPixels;

int pixeldpi = Resources.getSystem().getDisplayMetrics().densityDpi;


int width_dp = (width_px/pixeldpi)*160;
int height_dp = (height_px/pixeldpi)*160;

How to initailize byte array of 100 bytes in java with all 0's

byte [] arr = new byte[100] 

Each element has 0 by default.

You could find primitive default values here:

Data Type   Default Value
byte        0
short       0
int         0
long        0L
float       0.0f
double      0.0d
char        '\u0000'
boolean     false

Using CSS td width absolute, position

This may not be what you want to hear, but display: table-cell does not respect width and will be collapsed based on the width of the entire table. You can get around this easily just by having a display: block element inside of the table cell itself whose width you specify, e.g

<td><div style="width: 300px;">wide</div></td>

This shouldn't make much of a difference if the <table> itself is position: fixed or absolute because the position of the cells are all static relative to the table.

http://jsfiddle.net/ExplosionPIlls/Mkq8L/4/

EDIT: I can't take credit, but as the comments say you can just use min-width instead of width on the table cell instead.

Get a list of checked checkboxes in a div using jQuery

This works for me.

var selecteditems = [];

$("#Div").find("input:checked").each(function (i, ob) { 
    selecteditems.push($(ob).val());
});

If Radio Button is selected, perform validation on Checkboxes

You must use the equals operator not the assignment like

if(document.form1.radio1[0].checked == true) {
    alert("You have selected Option 1");
}

Android Support Design TabLayout: Gravity Center and Mode Scrollable

Look at android-tablayouthelper

Automatically switch TabLayout.MODE_FIXED and TabLayout.MODE_SCROLLABLE depends on total tab width.

How to start Fragment from an Activity

Firstly, you start Activities and Services with an intent, you start fragments with fragment transactions. Secondly, your transaction isnt doing anything. Change it to something like:

FragmentTransaction transaction = getFragmentManager();
    transaction.beginTransaction()
        .replace(R.layout.container, newFragment) //<---replace a view in your layout (id: container) with the newFragment 
        .commit();

Java substring: 'string index out of range'

I"m guessing i'm getting this error because the string is trying to substring a Null value. But wouldn't the ".length() > 0" part eliminate that issue?

No, calling itemdescription.length() when itemdescription is null would not generate a StringIndexOutOfBoundsException, but rather a NullPointerException since you would essentially be trying to call a method on null.

As others have indicated, StringIndexOutOfBoundsException indicates that itemdescription is not at least 38 characters long. You probably want to handle both conditions (I assuming you want to truncate):

final String value;
if (itemdescription == null || itemdescription.length() <= 0) {
    value = "_";
} else if (itemdescription.length() <= 38) {
    value = itemdescription;
} else { 
    value = itemdescription.substring(0, 38);
}
pstmt2.setString(3, value);

Might be a good place for a utility function if you do that a lot...

What's a good way to extend Error in JavaScript?

As some people have said, it's fairly easy with ES6:

class CustomError extends Error { }

So I tried that within my app, (Angular, Typescript) and it just didn't work. After some time I've found that the problem is coming from Typescript :O

See https://github.com/Microsoft/TypeScript/issues/13965

It's very disturbing because if you do:

class CustomError extends Error {}
?

try {
  throw new CustomError()
} catch(e) {
  if (e instanceof CustomError) {
    console.log('Custom error');
  } else {
    console.log('Basic error');
  }
}

In node or directly into your browser it'll display: Custom error

Try to run that with Typescript in your project on on Typescript playground, it'll display Basic error...

The solution is to do the following:

class CustomError extends Error {
  // we have to do the following because of: https://github.com/Microsoft/TypeScript/issues/13965
  // otherwise we cannot use instanceof later to catch a given type
  public __proto__: Error;

  constructor(message?: string) {
    const trueProto = new.target.prototype;
    super(message);

    this.__proto__ = trueProto;
  }
}

How to zip a file using cmd line?

ZIP FILE via Cross-platform Java without manifest and META-INF folder:

jar -cMf {yourfile.zip} {yourfolder}

How to replace a string in a SQL Server Table Column

all answers are great but I just want to give you a good example

select replace('this value from table', 'table',  'table but updated')

this SQL statement will replace the existence of the word "table" (second parameter) inside the given statement(first parameter) with the third parameter

the initial value is this value from table but after executing replace function it will be this value from table but updated

and here is a real example

UPDATE publication
SET doi = replace(doi, '10.7440/perifrasis', '10.25025/perifrasis')
WHERE doi like '10.7440/perifrasis%'

for example if we have this value

10.7440/perifrasis.2010.1.issue-1

it will become

10.25025/perifrasis.2010.1.issue-1

hope this gives you better visualization

Safely casting long to int in Java

DONT: This is not a solution!

My first approach was:

public int longToInt(long theLongOne) {
  return Long.valueOf(theLongOne).intValue();
}

But that merely just casts the long to an int, potentially creating new Long instances or retrieving them from the Long pool.


The drawbacks

  1. Long.valueOf creates a new Long instance if the number is not within Long's pool range [-128, 127].

  2. The intValue implementation does nothing more than:

    return (int)value;
    

So this can be considered even worse than just casting the long to int.

re.sub erroring with "Expected string or bytes-like object"

As you stated in the comments, some of the values appeared to be floats, not strings. You will need to change it to strings before passing it to re.sub. The simplest way is to change location to str(location) when using re.sub. It wouldn't hurt to do it anyways even if it's already a str.

letters_only = re.sub("[^a-zA-Z]",  # Search for all non-letters
                          " ",          # Replace all non-letters with spaces
                          str(location))

Spring Boot access static resources missing scr/main/resources

While working with Spring Boot application, it is difficult to get the classpath resources using resource.getFile() when it is deployed as JAR as I faced the same issue. This scan be resolved using Stream which will find out all the resources which are placed anywhere in classpath.

Below is the code snippet for the same -

ClassPathResource classPathResource = new ClassPathResource("fileName");
InputStream inputStream = classPathResource.getInputStream();
content = IOUtils.toString(inputStream);

Maximum on http header values?

No, HTTP does not define any limit. However most web servers do limit size of headers they accept. For example in Apache default limit is 8KB, in IIS it's 16K. Server will return 413 Entity Too Large error if headers size exceeds that limit.

Related question: How big can a user agent string get?

bitwise XOR of hex numbers in python

If the two hex strings are the same length and you want a hex string output then you might try this.

def hexxor(a, b):    # xor two hex strings of the same length
    return "".join(["%x" % (int(x,16) ^ int(y,16)) for (x, y) in zip(a, b)])

Placing/Overlapping(z-index) a view above another view in android

If you are adding the View programmatically, you can use yourLayout.addView(view, 1);

where 1 is the index.

org.json.simple cannot be resolved

Probably your simple json.jar file isn't in your classpath.

How to create a self-signed certificate with OpenSSL

I can't comment, so I will put this as a separate answer. I found a few issues with the accepted one-liner answer:

  • The one-liner includes a passphrase in the key.
  • The one-liner uses SHA-1 which in many browsers throws warnings in console.

Here is a simplified version that removes the passphrase, ups the security to suppress warnings and includes a suggestion in comments to pass in -subj to remove the full question list:

openssl genrsa -out server.key 2048
openssl rsa -in server.key -out server.key
openssl req -sha256 -new -key server.key -out server.csr -subj '/CN=localhost'
openssl x509 -req -sha256 -days 365 -in server.csr -signkey server.key -out server.crt

Replace 'localhost' with whatever domain you require. You will need to run the first two commands one by one as OpenSSL will prompt for a passphrase.

To combine the two into a .pem file:

cat server.crt server.key > cert.pem

Why is document.body null in my javascript?

Add your code to the onload event. The accepted answer shows this correctly, however that answer as well as all the others at the time of writing also suggest putting the script tag after the closing body tag, .

This is not valid html. However it will cause your code to work, because browsers are too kind ;)

See this answer for more info Is it wrong to place the <script> tag after the </body> tag?

Downvoted other answers for this reason.

How can I get double quotes into a string literal?

Thankfully, with C++11 there is also the more pleasing approach of using raw string literals.

printf("She said \"time flies like an arrow, but fruit flies like a banana\".");

Becomes:

printf(R"(She said "time flies like an arrow, but fruit flies like a banana".)");

With respect to the addition of brackets after the opening quote, and before the closing quote, note that they can be almost any combination of up to 16 characters, helping avoid the situation where the combination is present in the string itself. Specifically:

any member of the basic source character set except: space, the left parenthesis (, the right parenthesis ), the backslash , and the control characters representing horizontal tab, vertical tab, form feed, and newline" (N3936 §2.14.5 [lex.string] grammar) and "at most 16 characters" (§2.14.5/2)

How much clearer it makes this short strings might be debatable, but when used on longer formatted strings like HTML or JSON, it's unquestionably far clearer.

How to vertical align an inline-block in a line of text?

display: inline-block is your friend you just need all three parts of the construct - before, the "block", after - to be one, then you can vertically align them all to the middle:

Working Example

(it looks like your picture anyway ;))

CSS:

p, div {
  display: inline-block; 
  vertical-align: middle;
}
p, div {
  display: inline !ie7; /* hack for IE7 and below */
}

table {
  background: #000; 
  color: #fff; 
  font-size: 16px; 
  font-weight: bold; margin: 0 10px;
}

td {
  padding: 5px; 
  text-align: center;
}

HTML:

<p>some text</p> 
<div>
  <table summary="">
  <tr><td>A</td></tr>
  <tr><td>B</td></tr>
  <tr><td>C</td></tr>
  <tr><td>D</td></tr>
  </table>
</div> 
<p>continues afterwards</p>

Opposite of %in%: exclude rows with values specified in a vector

library(roperators)

1 %ni% 2:10

If you frequently need to use custom infix operators, it is easier to just have them in a package rather than declaring the same exact functions over and over in each script or project.

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

As many others have answered, No.

I use the following code on those unfortunate occasions when I need to use a base type as a derived type. Yes it is a violation of the Liskov Substitution Principle (LSP) and yes most of the time we favor composition over inheritance. Props to Markus Knappen Johansson whose original answer this is based upon.

This code in the base class:

    public T As<T>()
    {
        var type = typeof(T);
        var instance = Activator.CreateInstance(type);

        if (type.BaseType != null)
        {
            var properties = type.BaseType.GetProperties();
            foreach (var property in properties)
                if (property.CanWrite)
                    property.SetValue(instance, property.GetValue(this, null), null);
        }

        return (T) instance;
    }

Allows:

    derivedObject = baseObect.As<derivedType>()

Since it uses reflection, it is "expensive". Use accordingly.

Printing an int list in a single line python3

You want to say

for i in array:
    print(i, end=" ")

The syntax i in array iterates over each member of the list. So, array[i] was trying to access array[1], array[2], and array[3], but the last of these is out of bounds (array has indices 0, 1, and 2).

You can get the same effect with print(" ".join(map(str,array))).

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

As mentioned in some of the existing answers (which annoyingly I'm unable to comment on), the problem is that x++ ++x evaluate to different values (before vs after the increment), which is not obvious and can be very confusing - if that value is used. cdmckay suggests quite wisely to allow use of increment operator, but only in a way that the returned value is not used, e.g. on its own line. I would also include the standard use within a for loop (but only in the third statement, whose return value is not used). I can't think of another example. Having been "burnt" myself, I would recommend the same guideline for other languages as well.

I disagree with the claim that this over-strictness is due to a lot of JS programmers being inexperienced. This is the exact kind of writing typical of "overly-clever" programmers, and I'm sure it's much more common in more traditional languages and with JS developers who have a background in such languages.

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

In your MoviesService you should import FirebaseListObservable in order to define return type FirebaseListObservable<any[]>

import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';

then get() method should like this-

get (): FirebaseListObservable<any[]>{
        return this.db.list('/movies');
    }

this get() method will return FirebaseListObervable of movies list

In your MoviesComponent should look like this

export class MoviesComponent implements OnInit {
  movies: any[];

  constructor(private moviesDb: MoviesService) { }

  ngOnInit() {
    this.moviesDb.get().subscribe((snaps) => {
       this.movies = snaps;
   });
 }
}

Then you can easily iterate through movies without async pipe as movies[] data is not observable type, your html should be this

ul
  li(*ngFor='let movie of movies')
    {{ movie.title }}

if you declear movies as a

movies: FirebaseListObservable<any[]>;

then you should simply call

movies: FirebaseListObservable<any[]>;
ngOnInit() {
    this.movies = this.moviesDb.get();
}

and your html should be this

ul
  li(*ngFor='let movie of movies | async')
    {{ movie.title }}

Flask-SQLalchemy update a row's information

There is a method update on BaseQuery object in SQLAlchemy, which is returned by filter_by.

num_rows_updated = User.query.filter_by(username='admin').update(dict(email='[email protected]')))
db.session.commit()

The advantage of using update over changing the entity comes when there are many objects to be updated.

If you want to give add_user permission to all the admins,

rows_changed = User.query.filter_by(role='admin').update(dict(permission='add_user'))
db.session.commit()

Notice that filter_by takes keyword arguments (use only one =) as opposed to filter which takes an expression.

How can I store and retrieve images from a MySQL database using PHP?

First you create a MySQL table to store images, like for example:

create table testblob (
    image_id        tinyint(3)  not null default '0',
    image_type      varchar(25) not null default '',
    image           blob        not null,
    image_size      varchar(25) not null default '',
    image_ctgy      varchar(25) not null default '',
    image_name      varchar(50) not null default ''
);

Then you can write an image to the database like:

/***
 * All of the below MySQL_ commands can be easily
 * translated to MySQLi_ with the additions as commented
 ***/ 
$imgData = file_get_contents($filename);
$size = getimagesize($filename);
mysql_connect("localhost", "$username", "$password");
mysql_select_db ("$dbname");
// mysqli 
// $link = mysqli_connect("localhost", $username, $password,$dbname); 
$sql = sprintf("INSERT INTO testblob
    (image_type, image, image_size, image_name)
    VALUES
    ('%s', '%s', '%d', '%s')",
    /***
     * For all mysqli_ functions below, the syntax is:
     * mysqli_whartever($link, $functionContents); 
     ***/
    mysql_real_escape_string($size['mime']),
    mysql_real_escape_string($imgData),
    $size[3],
    mysql_real_escape_string($_FILES['userfile']['name'])
    );
mysql_query($sql);

You can display an image from the database in a web page with:

$link = mysql_connect("localhost", "username", "password");
mysql_select_db("testblob");
$sql = "SELECT image FROM testblob WHERE image_id=0";
$result = mysql_query("$sql");
header("Content-type: image/jpeg");
echo mysql_result($result, 0);
mysql_close($link);

Returning a stream from File.OpenRead()

You need

    str.CopyTo(data);
    data.Position = 0; // reset to beginning
    byte[] buf = new byte[data.Length];
    data.Read(buf, 0, buf.Length);  

And since your Test() method is imitating the client it ought to Close() or Dispose() the str Stream. And the memoryStream too, just out of principal.