Programs & Examples On #Win32exception

How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?

I had the same issue today recently installing VS2015 Community Edition Update 1.

I fixed the problem by just adding the "SQL Server Data Tools" from the VS2015 setup installer... When I ran the installer the first time I selected the "Custom" installation type instead of the "Default". I wanted to see what install options were available but not select anything different than what was already ticked. My assumption was that whatever was already ticked was essentially the default install. But its not.

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

There are several other posts about this now and they all point to enabling TLS 1.2. Anything less is unsafe.

You can do this in .NET 3.5 with a patch.
You can do this in .NET 4.0 and 4.5 with a single line of code

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // .NET 4.5
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; // .NET 4.0

In .NET 4.6, it automatically uses TLS 1.2.

See here for more details: .NET support for TLS

SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)

Check you routes, the update on 9/28/2014 impacted us. We had to adjust our older servers and add new routes. Here is the article http://www.rackspace.com/knowledge_center/article/updating-servicenet-routes-on-cloud-servers-created-before-june-3-2013

The network path was not found

As others pointed out this could be more to do with the connectionstring config Make sure,

  1. user id and password are correct
  2. Data Source is pointing to correct one , for example if you are using SQL express it will be .\SQLEXPRESS
  3. Database is pointing to correct name of database Hope that helps.

"The system cannot find the file specified"

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. text

Generally issues like this are related to any of the following need to be looked at:

  • firewall settings from the web server to the database server
  • connection string errors
  • enable the appropriate protocol pipes/ tcp-ip

Try connecting to sql server with sql management server on the system that sql server is installed on and work from there. Pay attention to information in the errorlogs.

Win32Exception (0x80004005): The wait operation timed out

Look into re-indexing tables in your database.

You can first find out the fragmentation level - and if it's above 10% or so you could benefit from re-indexing. If it's very high it's likely this is creating a significant performance bottle neck.

http://blog.sqlauthority.com/2009/01/30/sql-server-2008-2005-rebuild-every-index-of-all-tables-of-database-rebuild-index-with-fillfactor/

This should be done regularly.

Error in Process.Start() -- The system cannot find the file specified

I had the same problem, but none of the solutions worked for me, because the message The system cannot find the file specified can be misleading in some special cases.

In my case, I use Notepad++ in combination with the registry redirect for notepad.exe. Unfortunately my path to Notepad++ in the registry was wrong.

So in fact the message The system cannot find the file specified was telling me, that it cannot find the application (Notepad++) associated with the file type(*.txt), not the file itself.

Add hover text without javascript like we hover on a user's reputation

The title attribute also works well with other html elements, for example a link...

<a title="hover text" ng-href="{{getUrl()}}"> download link
</a>

Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php

If you are trying to read a file, that will take up memory in PHP. For instance, if you are trying to open up and read an MP3 file ( like, say, $data = file("http://mydomain.com/path/sample.mp3" ) it is going to pull it all into memory.

As Nelson suggests, you can work to increase your maximum memory limit if you actually need to be using this much memory.

How to set the margin or padding as percentage of height of parent container?

The fix is that yes, vertical padding and margin are relative to width, but top and bottom aren't.

So just place a div inside another, and in the inner div, use something like top:50% (remember position matters if it still doesn't work)

Android 6.0 Marshmallow. Cannot write to SD Card

Android Documentation on Manifest.permission.Manifest.permission.WRITE_EXTERNAL_STORAGE states:

Starting in API level 19, this permission is not required to read/write files in your application-specific directories returned by getExternalFilesDir(String) and getExternalCacheDir().


I think that this means you do not have to code for the run-time implementation of the WRITE_EXTERNAL_STORAGE permission unless the app is writing to a directory that is not specific to your app.

You can define the max sdk version in the manifest per permission like:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="19" />

Also make sure to change the target SDK in the build.graddle and not the manifest, the gradle settings will always overwrite the manifest settings.

android {
compileSdkVersion 23
buildToolsVersion '23.0.1'
defaultConfig {
    minSdkVersion 17
    targetSdkVersion 22
}

.ssh/config file for windows (git)

For me worked only adding the config or ssh_config file that was on the dir ~/.ssh/config on my Linux system on the c:\Program Files\Git\etc\ssh\ directory on Windows.

In some git versions we need to edit the C:\Users\<username>\AppData\Local\Programs\Git\etc\ssh\ssh_config file.

After that, I was able to use all the alias and settings that I normally used on my Linux connecting or pushing via SSH on the Git Bash.

How do I get the absolute directory of a file in bash?

This will work for both file and folder:

absPath(){
    if [[ -d "$1" ]]; then
        cd "$1"
        echo "$(pwd -P)"
    else 
        cd "$(dirname "$1")"
        echo "$(pwd -P)/$(basename "$1")"
    fi
}

How do I check in SQLite whether a table exists?

Note that to check whether a table exists in the TEMP database, you must use sqlite_temp_master instead of sqlite_master:

SELECT name FROM sqlite_temp_master WHERE type='table' AND name='table_name';

Check if an apt-get package is installed and then install it if it's not on Linux

inspired by Chris above

#! /bin/bash

installed() {
    return $(dpkg-query -W -f '${Status}\n' "${1}" 2>&1|awk '/ok installed/{print 0;exit}{print 1}')
}

pkgs=(libgl1-mesa-dev xorg-dev vulkan-tools libvulkan-dev vulkan-validationlayers-dev spirv-tools)
missing_pkgs=""

for pkg in ${pkgs[@]}; do
    if ! $(installed $pkg) ; then
        missing_pkgs+=" $pkg"
    fi
done

if [ ! -z "$missing_pkgs" ]; then
    cmd="sudo apt install -y $missing_pkgs"
    echo $cmd
fi

Benefits of using the conditional ?: (ternary) operator

There is some performance benefit of using the the ? operator in eg. MS Visual C++, but this is a really a compiler specific thing. The compiler can actually optimize out the conditional branch in some cases.

Relative instead of Absolute paths in Excel VBA

Here's my quick and simple function for getting the absolute path from a relative path.

The difference from the accepted answer is that this function can handle relative paths that moves up to parent folders.

Example:

Workbooks.Open FileName:=GetAbsolutePath("..\..\TRICATEndurance Summary.html")

Code:

' Gets an absolute path from a relative path in the active workbook
Public Function GetAbsolutePath(relativePath As String) As String
    
    Dim absPath As String
    Dim pos As Integer
    
    absPath = ActiveWorkbook.Path
    
    ' Make sure paths are in correct format
    relativePath = Replace(relativePath, "/", "\")
    absPath = Replace(absPath, "/", "\")
    
    Do While Left$(relativePath, 3) = "..\"
    
        ' Remove level from relative path
        relativePath = Mid$(relativePath, 4)
        
        ' Remove level from absolute path
        pos = InStrRev(absPath, "\")
        absPath = Left$(absPath, pos - 1)
    
    Loop
    
    GetAbsolutePath = PathCombine(absPath, relativePath)
    
End Function

c# Image resizing to different size while preserving aspect ratio

I'm going to add my code here too. This code will allow you resize an image with or without the aspect ratio being enforced or to resize with padding. This is a modified version of egrunin's code.

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace ConsoleApplication1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var path = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
            ResizeImage(path, "large.jpg", path, "new.jpg", 100, 100, true, true);
        }

        /// <summary>Resizes an image to a new width and height.</summary>
        /// <param name="originalPath">The folder which holds the original image.</param>
        /// <param name="originalFileName">The file name of the original image.</param>
        /// <param name="newPath">The folder which will hold the resized image.</param>
        /// <param name="newFileName">The file name of the resized image.</param>
        /// <param name="maximumWidth">When resizing the image, this is the maximum width to resize the image to.</param>
        /// <param name="maximumHeight">When resizing the image, this is the maximum height to resize the image to.</param>
        /// <param name="enforceRatio">Indicates whether to keep the width/height ratio aspect or not. If set to false, images with an unequal width and height will be distorted and padding is disregarded. If set to true, the width/height ratio aspect is maintained and distortion does not occur.</param>
        /// <param name="addPadding">Indicates whether fill the smaller dimension of the image with a white background. If set to true, the white padding fills the smaller dimension until it reach the specified max width or height. This is used for maintaining a 1:1 ratio if the max width and height are the same.</param>
        private static void ResizeImage(string originalPath, string originalFileName, string newPath, string newFileName, int maximumWidth, int maximumHeight, bool enforceRatio, bool addPadding)
        {
            var image = Image.FromFile(originalPath + "\\" + originalFileName);
            var imageEncoders = ImageCodecInfo.GetImageEncoders();
            EncoderParameters encoderParameters = new EncoderParameters(1);
            encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
            var canvasWidth = maximumWidth;
            var canvasHeight = maximumHeight;
            var newImageWidth = maximumWidth;
            var newImageHeight = maximumHeight;
            var xPosition = 0;
            var yPosition = 0;


            if (enforceRatio)
            {
                var ratioX = maximumWidth / (double)image.Width;
                var ratioY = maximumHeight / (double)image.Height;
                var ratio = ratioX < ratioY ? ratioX : ratioY;
                newImageHeight = (int)(image.Height * ratio);
                newImageWidth = (int)(image.Width * ratio);

                if (addPadding)
                {
                    xPosition = (int)((maximumWidth - (image.Width * ratio)) / 2);
                    yPosition = (int)((maximumHeight - (image.Height * ratio)) / 2);
                }
                else
                {
                    canvasWidth = newImageWidth;
                    canvasHeight = newImageHeight;                  
                }
            }

            var thumbnail = new Bitmap(canvasWidth, canvasHeight);
            var graphic = Graphics.FromImage(thumbnail);

            if (enforceRatio && addPadding)
            {
                graphic.Clear(Color.White);
            }

            graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphic.SmoothingMode = SmoothingMode.HighQuality;
            graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
            graphic.CompositingQuality = CompositingQuality.HighQuality;
            graphic.DrawImage(image, xPosition, yPosition, newImageWidth, newImageHeight);

            thumbnail.Save(newPath + "\\" + newFileName, imageEncoders[1], encoderParameters);
        }
    }
}

Parse usable Street Address, City, State, Zip from a string

SmartyStreets has a new feature that extracts addresses from arbitrary input strings. (Note: I don't work at SmartyStreets.)

It successfully extracted all addresses from the sample input given in the question above. (By the way, only 9 of those 10 addresses are valid.)

Here's some of the output:enter image description here

And here's the CSV-formatted output of that same request:

ID,Start,End,Segment,Verified,Candidate,Firm,FirstLine,SecondLine,LastLine,City,State,ZIPCode,County,DpvFootnotes,DeliveryPointBarcode,Active,Vacant,CMRA,MatchCode,Latitude,Longitude,Precision,RDI,RecordType,BuildingDefaultIndicator,CongressionalDistrict,Footnotes
1,32,79,"2299 Lewes-Georgetown Hwy, Georgetown, DE 19947",N,,,,,,,,,,,,,,,,,,,,,,
2,81,119,"11522 Shawnee Road, Greenwood DE 19950",Y,0,,11522 Shawnee Rd,,Greenwood DE 19950-5209,Greenwood,DE,19950,Sussex,AABB,199505209226,Y,N,N,Y,38.82865,-75.54907,Zip9,Residential,S,,AL,N#
3,121,160,"144 Kings Highway, S.W. Dover, DE 19901",Y,0,,144 Kings Hwy,,Dover DE 19901-7308,Dover,DE,19901,Kent,AABB,199017308444,Y,N,N,Y,39.16081,-75.52377,Zip9,Commercial,S,,AL,L#
4,190,232,"2 Penns Way Suite 405 New Castle, DE 19720",Y,0,,2 Penns Way Ste 405,,New Castle DE 19720-2407,New Castle,DE,19720,New Castle,AABB,197202407053,Y,N,N,Y,39.68332,-75.61043,Zip9,Commercial,H,,AL,N#
5,247,285,"33 Bridle Ridge Court, Lewes, DE 19958",Y,0,,33 Bridle Ridge Cir,,Lewes DE 19958-8961,Lewes,DE,19958,Sussex,AABB,199588961338,Y,N,N,Y,38.72749,-75.17055,Zip7,Residential,S,,AL,L#
6,306,339,"2742 Pulaski Hwy Newark, DE 19711",Y,0,,2742 Pulaski Hwy,,Newark DE 19702-3911,Newark,DE,19702,New Castle,AABB,197023911421,Y,N,N,Y,39.60328,-75.75869,Zip9,Commercial,S,,AL,A#
7,341,378,"2284 Bryn Zion Road, Smyrna, DE 19904",Y,0,,2284 Bryn Zion Rd,,Smyrna DE 19977-3895,Smyrna,DE,19977,Kent,AABB,199773895840,Y,N,N,Y,39.23937,-75.64065,Zip7,Residential,S,,AL,A#N#
8,406,450,"1500 Serpentine Road, Suite 100 Baltimore MD",Y,0,,1500 Serpentine Rd Ste 100,,Baltimore MD 21209-2034,Baltimore,MD,21209,Baltimore,AABB,212092034250,Y,N,N,Y,39.38194,-76.65856,Zip9,Commercial,H,,03,N#
9,455,495,"580 North Dupont Highway Dover, DE 19901",Y,0,,580 N DuPont Hwy,,Dover DE 19901-3961,Dover,DE,19901,Kent,AABB,199013961803,Y,N,N,Y,39.17576,-75.5241,Zip9,Commercial,S,,AL,N#
10,497,525,"P.O. Box 778 Dover, DE 19903",Y,0,,PO Box 778,,Dover DE 19903-0778,Dover,DE,19903,Kent,AABB,199030778781,Y,N,N,Y,39.20946,-75.57012,Zip5,Residential,P,,AL,

I was the developer who originally wrote the service. The algorithm we implemented is a bit different from any specific answers here, but each extracted address is verified against the address lookup API, so you can be sure if it's valid or not. Each verified result is guaranteed, but we know the other results won't be perfect because, as has been made abundantly clear in this thread, addresses are unpredictable, even for humans sometimes.

Unsupported major.minor version 52.0

You need to upgrade your Java version to Java 8.

Download latest Java archive

Download latest Java SE Development Kit 8 release from its official download page or use following commands to download from the shell.

For 64 bit

 # cd /opt/

 # wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u51-b16/jdk-8u51-linux-x64.tar.gz"

 # tar xzf jdk-8u51-linux-x64.tar.gz

For 32 bit

 # cd /opt/

 # wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u51-b16/jdk-8u51-linux-i586.tar.gz"

  # tar xzf jdk-8u51-linux-i586.tar.gz

Note: If the above wget command doesn’t not work for you, watch this example video to download the Java source archive using the terminal.

Install Java with alternatives

After extracting the archive file, use the alternatives command to install it. The alternatives command is available in the chkconfig package.

 # cd /opt/jdk1.8.0_51/

 # alternatives --install /usr/bin/java java /opt/jdk1.8.0_51/bin/java 2

 # alternatives --config java

At this point Java 8 has been successfully installed on your system. We also recommend to setup javac and jar commands path using alternatives:

 # alternatives --install /usr/bin/jar jar /opt/jdk1.8.0_51/bin/jar 2

 # alternatives --install /usr/bin/javac javac /opt/jdk1.8.0_51/bin/javac 2

 # alternatives --set jar /opt/jdk1.8.0_51/bin/jar

 # alternatives --set javac /opt/jdk1.8.0_51/bin/javac

Check installed Java version

Check the installed version of Java using the following command.

root@tecadmin ~# java -version

java version "1.8.0_51"
Java(TM) SE Runtime Environment (build 1.8.0_51-b16)
Java HotSpot(TM) 64-Bit Server VM (build 25.51-b03, mixed mode)

Configuring Environment Variables

Most of Java-based applications use environment variables to work. Set the Java environment variables using the following commands:

Setup JAVA_HOME Variable

# export JAVA_HOME=/opt/jdk1.8.0_51
Setup JRE_HOME Variable

# export JRE_HOME=$JAVA_HOME/jre
Setup PATH Variable

# export PATH=$JAVA_HOME/bin:$JRE_HOME/bin:$PATH

Note that the change to the PATH variable put the new Java bin folders first so that they override any existing java/bins in the path. It is a bit sloppy to leave two java/bin folders in your path so you should be advised to clean those up as a separate task.

Also, put all above environment variables in the /etc/environment file for auto loading on system boot.

Alter and Assign Object Without Side Effects

You will have the same object two times in your array, because object values are passed by reference. You have to create a new object like this

myElement.id = 244;
myElement.value = 3556;
myArray[0] = $.extend({}, myElement); //for shallow copy or
myArray[0] = $.extend(true, {}, myElement); // for deep copy

or

myArray.push({ id: 24, value: 246 });

Finding the number of non-blank columns in an Excel sheet using VBA

It's possible you forgot a sheet1 each time somewhere before the columns.count, or it will count the activesheet columns and not the sheet1's.

Also, shouldn't it be xltoleft instead of xltoright? (Ok it is very late here, but I think I know my right from left) I checked it, you must write xltoleft.

lastColumn = Sheet1.Cells(1, sheet1.Columns.Count).End(xlToleft).Column

Radio buttons and label to display in same line

If the problem is that the label and input are wrapping to two lines when the window is too narrow, remove the whitespace between them; e.g.:

<label for="one">First Item</label>
<input type="radio" id="one" name="first_item" value="1" />

If you need space between the elements, use non-breaking spaces (&amp; nbsp;) or CSS.

Set the Value of a Hidden field using JQuery

If you have a hidden field like this

  <asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("VertragNr") %>'/>

Now you can use your value like this

$(this).parent().find('input[type=hidden]').val()

How to adjust gutter in Bootstrap 3 grid system?

(Posted on behalf of the OP).

I believe I figured it out.

In my case, I added [class*="col-"] {padding: 0 7.5px;};.

Then added .row {margin: 0 -7.5px;}.

This works pretty well, except there is 1px margin on both sides. So I just make .row {margin: 0 -7.5px;} to .row {margin: 0 -8.5px;}, then it works perfectly.

I have no idea why there is a 1px margin. Maybe someone can explain it?

See the sample I created:

Demo
Code

mysqli::query(): Couldn't fetch mysqli

Probably somewhere you have DBconnection->close(); and then some queries try to execute .


Hint: It's sometimes mistake to insert ...->close(); in __destruct() (because __destruct is event, after which there will be a need for execution of queries)

WITH (NOLOCK) vs SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

To my knowledge the only difference is the scope of the effects as Strommy said. NOLOCK hint on a table and the READ UNCOMMITTED on the session.

As to problems that can occur, it's all about consistency. If you care then be aware that you could get what is called dirty reads which could influence other data being manipulated on incorrect information.

I personally don't think I have seen any problems from this but that may be more due to how I use nolock. You need to be aware that there are scenarios where it will be OK to use. Scenarios where you are mostly adding new data to a table but have another process that comes in behind to check for a data scenario. That will probably be OK since the major flow doesn't include going back and updating rows during a read.

Also I believe that these days you should look into Multi-version Concurrency Control. I believe they added it in 2005 and it helps stop the writers from blocking readers by giving readers a snapshot of the database to use. I'll include a link and leave further research to the reader:

MVCC

Database Isolation Levels

How to start MySQL with --skip-grant-tables?

I had the same problem as the title of this question, so incase anyone else googles upon this question and wants to start MySql in 'skip-grant-tables' mode on Windows, here is what I did.

Stop the MySQL service through Administrator tools, Services.

Modify the my.ini configuration file (assuming default paths)

C:\Program Files\MySQL\MySQL Server 5.5\my.ini

or for MySQL version >= 5.6

C:\ProgramData\MySQL\MySQL Server 5.6\my.ini 

In the SERVER SECTION, under [mysqld], add the following line:

skip-grant-tables

so that you have

# SERVER SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by the MySQL Server. Make sure that
# you have installed the server correctly (see above) so it reads this 
# file.
#
[mysqld]

skip-grant-tables

Start the service again and you should be able to log into your database without a password.

How to get screen width without (minus) scrollbar?

.prop("clientWidth") and .prop("scrollWidth")

var actualInnerWidth = $("body").prop("clientWidth"); // El. width minus scrollbar width
var actualInnerWidth = $("body").prop("scrollWidth"); // El. width minus scrollbar width

in JavaScript:

var actualInnerWidth = document.body.clientWidth;     // El. width minus scrollbar width
var actualInnerWidth = document.body.scrollWidth;     // El. width minus scrollbar width

P.S: Note that to use scrollWidth reliably your element should not overflow horizontally

jsBin demo


You could also use .innerWidth() but this will work only on the body element

var innerWidth = $('body').innerWidth(); // Width PX minus scrollbar 

How do I add multiple conditions to "ng-disabled"?

You can try something like this.

<button class="button" ng-disabled="(!data.var1 && !data.var2) ? false : true">
</button>

Its working fine for me.

Given a URL to a text file, what is the simplest way to read the contents of the text file?

Edit 09/2016: In Python 3 and up use urllib.request instead of urllib2

Actually the simplest way is:

import urllib2  # the lib that handles the url stuff

data = urllib2.urlopen(target_url) # it's a file like object and works just like a file
for line in data: # files are iterable
    print line

You don't even need "readlines", as Will suggested. You could even shorten it to: *

import urllib2

for line in urllib2.urlopen(target_url):
    print line

But remember in Python, readability matters.

However, this is the simplest way but not the safe way because most of the time with network programming, you don't know if the amount of data to expect will be respected. So you'd generally better read a fixed and reasonable amount of data, something you know to be enough for the data you expect but will prevent your script from been flooded:

import urllib2

data = urllib2.urlopen("http://www.google.com").read(20000) # read only 20 000 chars
data = data.split("\n") # then split it into lines

for line in data:
    print line

* Second example in Python 3:

import urllib.request  # the lib that handles the url stuff

for line in urllib.request.urlopen(target_url):
    print(line.decode('utf-8')) #utf-8 or iso8859-1 or whatever the page encoding scheme is

*ngIf and *ngFor on same element causing error

You can not use more than one Structural Directive in Angular on the same element, it makes a bad confusion and structure, so you need to apply them in 2 separate nested elements(or you can use ng-container), read this statement from Angular team:

One structural directive per host element

Someday you'll want to repeat a block of HTML but only when a particular condition is true. You'll try to put both an *ngFor and an *ngIf on the same host element. Angular won't let you. You may apply only one structural directive to an element.

The reason is simplicity. Structural directives can do complex things with the host element and its descendents. When two directives lay claim to the same host element, which one takes precedence? Which should go first, the NgIf or the NgFor? Can the NgIf cancel the effect of the NgFor? If so (and it seems like it should be so), how should Angular generalize the ability to cancel for other structural directives?

There are no easy answers to these questions. Prohibiting multiple structural directives makes them moot. There's an easy solution for this use case: put the *ngIf on a container element that wraps the *ngFor element. One or both elements can be an ng-container so you don't have to introduce extra levels of HTML.

So you can use ng-container (Angular4) as the wrapper (will be deleted from the dom) or a div or span if you have class or some other attributes as below:

<div class="right" *ngIf="show">
  <div *ngFor="let thing of stuff">
    {{log(thing)}}
    <span>{{thing.name}}</span>
  </div>
</div>

Apache Cordova - uninstall globally

Try sudo npm uninstall cordova -g to uninstall it globally and then just npm install cordova without the -g flag after cding to the local app directory

Add Variables to Tuple

" once the info is added to the DB, should I delete the tuple? i mean i dont need the tuple anymore."

No.

Generally, there's no reason to delete anything. There are some special cases for deleting, but they're very, very rare.

Simply define a narrow scope (i.e., a function definition or a method function in a class) and the objects will be garbage collected at the end of the scope.

Don't worry about deleting anything.

[Note. I worked with a guy who -- in addition to trying to delete objects -- was always writing "reset" methods to clear them out. Like he was going to save them and reuse them. Also a silly conceit. Just ignore the objects you're no longer using. If you define your functions in small-enough blocks of code, you have nothing more to think about.]

Error executing command 'ant' on Mac OS X 10.9 Mavericks when building for Android with PhoneGap/Cordova

As an alternative to homebrew, you could download and install macports. Once you have macports, you can use:

sudo port install apache-ant

Why do I have to run "composer dump-autoload" command to make migrations work in laravel?

Short answer: classmaps are static while PSR autoloading is dynamic.

If you don't want to use classmaps, use PSR autoloading instead.

Are duplicate keys allowed in the definition of binary search trees?

If your binary search tree is a red black tree, or you intend to any kind of "tree rotation" operations, duplicate nodes will cause problems. Imagine your tree rule is this:

left < root <= right

Now imagine a simple tree whose root is 5, left child is nil, and right child is 5. If you do a left rotation on the root you end up with a 5 in the left child and a 5 in the root with the right child being nil. Now something in the left tree is equal to the root, but your rule above assumed left < root.

I spent hours trying to figure out why my red/black trees would occasionally traverse out of order, the problem was what I described above. Hopefully somebody reads this and saves themselves hours of debugging in the future!

Just get column names from hive table

use desc tablename from Hive CLI or beeline to get all the column names. If you want the column names in a file then run the below command from the shell.

$ hive -e 'desc dbname.tablename;' > ~/columnnames.txt

where dbname is the name of the Hive database where your table is residing You can find the file columnnames.txt in your root directory.

$cd ~
$ls

Clear and reset form input fields

This one works best to reset the form.

import React, { Component } from 'react'
class MyComponent extends Component {
  constructor(props){
    super(props)
    this.state = {
      inputVal: props.inputValue
    }
    // preserve the initial state in a new object
    this.baseState = this.state ///>>>>>>>>> note this one.
  }
  resetForm = () => {
    this.setState(this.baseState) ///>>>>>>>>> note this one.
  }
  submitForm = () => {
    // submit the form logic
  }
  updateInput = val => this.setState({ inputVal: val })
  render() {
    return (
      <form>
        <input
          onChange={this.updateInput}
          type="text
          value={this.state.inputVal} />
        <button
          onClick={this.resetForm}
          type="button">Cancel</button>
        <button
          onClick={this.submitForm}
          type="submit">Submit</button>
      </form>
    )
  }
}

What is the difference between sscanf or atoi to convert a string to an integer?

*scanf() family of functions return the number of values converted. So you should check to make sure sscanf() returns 1 in your case. EOF is returned for "input failure", which means that ssacnf() will never return EOF.

For sscanf(), the function has to parse the format string, and then decode an integer. atoi() doesn't have that overhead. Both suffer from the problem that out-of-range values result in undefined behavior.

You should use strtol() or strtoul() functions, which provide much better error-detection and checking. They also let you know if the whole string was consumed.

If you want an int, you can always use strtol(), and then check the returned value to see if it lies between INT_MIN and INT_MAX.

Thymeleaf using path variables to th:href

I think your problem was a typo:

<a th:href="@{'/category/edit/' + ${category.id}}">view</a>

You are using category.id, but in your code is idCategory, as Eddie already pointed out.

This would work for you:

<a th:href="@{'/category/edit/' + ${category.idCategory}}">view</a>

How to test abstract class in Java with JUnit?

You could do something like this

public abstract MyAbstractClass {

    @Autowire
    private MyMock myMock;        

    protected String sayHello() {
            return myMock.getHello() + ", " + getName();
    }

    public abstract String getName();
}

// this is your JUnit test
public class MyAbstractClassTest extends MyAbstractClass {

    @Mock
    private MyMock myMock;

    @InjectMocks
    private MyAbstractClass thiz = this;

    private String myName = null;

    @Override
    public String getName() {
        return myName;
    }

    @Test
    public void testSayHello() {
        myName = "Johnny"
        when(myMock.getHello()).thenReturn("Hello");
        String result = sayHello();
        assertEquals("Hello, Johnny", result);
    }
}

Using str_replace so that it only acts on the first match?

Unfortunately, I don't know of any PHP function which can do this.
You can roll your own fairly easily like this:

function replace_first($find, $replace, $subject) {
    // stolen from the comments at PHP.net/str_replace
    // Splits $subject into an array of 2 items by $find,
    // and then joins the array with $replace
    return implode($replace, explode($find, $subject, 2));
}

how to determine size of tablespace oracle 11g

The following query can be used to detemine tablespace and other params:

select df.tablespace_name "Tablespace",
       totalusedspace "Used MB",
       (df.totalspace - tu.totalusedspace) "Free MB",
       df.totalspace "Total MB",
       round(100 * ( (df.totalspace - tu.totalusedspace)/ df.totalspace)) "Pct. Free"
  from (select tablespace_name,
               round(sum(bytes) / 1048576) TotalSpace
          from dba_data_files 
         group by tablespace_name) df,
       (select round(sum(bytes)/(1024*1024)) totalusedspace,
               tablespace_name
          from dba_segments 
         group by tablespace_name) tu
 where df.tablespace_name = tu.tablespace_name 
   and df.totalspace <> 0;

Source: https://community.oracle.com/message/1832920

For your case if you want to know the partition name and it's size just run this query:

select owner,
       segment_name,
       partition_name,
       segment_type,
       bytes / 1024/1024 "MB" 
  from dba_segments 
 where owner = <owner_name>;

Python's most efficient way to choose longest string in list?

From the Python documentation itself, you can use max:

>>> mylist = ['123','123456','1234']
>>> print max(mylist, key=len)
123456

How to put a div in center of browser using CSS?

try this

#center_div
{
       margin: auto;
       position: absolute;
       top: 0; 
       left: 0;
       bottom: 0; 
       right: 0;
 }

Labeling file upload button

It is normally provided by the browser and hard to change, so the only way around it will be a CSS/JavaScript hack,

See the following links for some approaches:

SQL Update with row_number()

I did this for my situation and worked

WITH myUpdate (id, myRowNumber )
AS
( 
    SELECT id, ROW_NUMBER() over (order by ID) As myRowNumber
    FROM AspNetUsers
    WHERE  UserType='Customer' 
 )

update AspNetUsers set EmployeeCode = FORMAT(myRowNumber,'00000#') 
FROM myUpdate
    left join AspNetUsers u on u.Id=myUpdate.id

How to compare two dates in php

I think this one is very simple function

function terminateOrNotStringtoDate($currentDate, $terminationdate)
{
    $crtDate = new DateTime($currentDate);
    $termDate = new DateTime($terminationdate);
    if($crtDate >= $termDate)
    {
        return true;
    } else {
    return false;
    }
}

TCPDF Save file to folder?

If you still get

TCPDF ERROR: Unable to create output file: myfile.pdf

you can avoid TCPDF's file saving logic by putting PDF data to a variable and saving this string to a file:

$pdf_string = $pdf->Output('pseudo.pdf', 'S');
file_put_contents('./mydir/myfile.pdf', $pdf_string);

Ternary operator in AngularJS templates

  <body ng-app="app">
  <button type="button" ng-click="showme==true ? !showme :showme;message='Cancel Quiz'"  class="btn btn-default">{{showme==true ? 'Cancel Quiz': 'Take a Quiz'}}</button>
    <div ng-show="showme" class="panel panel-primary col-sm-4" style="margin-left:250px;">
      <div class="panel-heading">Take Quiz</div>
      <div class="form-group col-sm-8 form-inline" style="margin-top: 30px;margin-bottom: 30px;">

        <button type="button" class="btn btn-default">Start Quiz</button>
      </div>
    </div>
  </body>

Button toggle and change header of button and show/hide div panel. See the Plunkr

C# Pass Lambda Expression as Method Parameter

If I understand you need following code. (passing expression lambda by parameter) The Method

public static void Method(Expression<Func<int, bool>> predicate) { 
    int[] number={1,2,3,4,5,6,7,8,9,10};
    var newList = from x in number
                  .Where(predicate.Compile()) //here compile your clausuly
                  select x;
                newList.ToList();//return a new list
    }

Calling method

Method(v => v.Equals(1));

You can do the same in their class, see this is example.

public string Name {get;set;}

public static List<Class> GetList(Expression<Func<Class, bool>> predicate)
    {
        List<Class> c = new List<Class>();
        c.Add(new Class("name1"));
        c.Add(new Class("name2"));

        var f = from g in c.
                Where (predicate.Compile())
                select g;
        f.ToList();

       return f;
    }

Calling method

Class.GetList(c=>c.Name=="yourname");

I hope this is useful

Java: How to access methods from another class

You need to somehow give class Alpha a reference to cBeta. There are three ways of doing this.

1) Give Alphas a Beta in the constructor. In class Alpha write:

public class Alpha {
   private Beta beta;
   public Alpha(Beta beta) {
     this.beta = beta; 
   }

and call cAlpha = new Alpha(cBeta) from main()

2) give Alphas a mutator that gives them a beta. In class Alpha write:

public class Alpha {
   private Beta beta;
   public void setBeta (Beta newBeta) {
     this.beta = beta;
   }

and call cAlpha = new Alpha(); cAlpha.setBeta(beta); from main(), or

3) have a beta as an argument to doSomethingAlpha. in class Alpha write:

public void DoSomethingAlpha(Beta cBeta) {
      cbeta.DoSomethingBeta()
}

Which strategy you use depends on a few things. If you want every single Alpha to have a Beta, use number 1. If you want only some Alphas to have a Beta, but you want them to hold onto their Betas indefinitely, use number 2. If you want Alphas to deal with Betas only while you're calling doSomethingAlpha, use number 3. Variable scope is complicated at first, but it gets easier when you get the hang of it. Let me know if you have any more questions!

How to set background image of a view?

It's a very bad idea to directly display any text on an irregular and ever changing background. No matter what you do, some of the time the text will be hard to read.

The best design would be to have the labels on a constant background with the images changing behind that.

You can set the labels background color from clear to white and set the from alpha to 50.0 you get a nice translucent effect. The only problem is that the label's background is a stark rectangle.

To get a label with a background with rounded corners you can use a button with user interaction disabled but the user might mistake that for a button.

The best method would be to create image of the label background you want and then put that in an imageview and put the label with the default transparent background onto of that.

Plain UIViews do not have an image background. Instead, you should make a UIImageView your main view and then rotate the images though its image property. If you set the UIImageView's mode to "Scale to fit" it will scale any image to fit the bounds of the view.

How to base64 encode image in linux bash / shell

There is a Linux command for that: base64

base64 DSC_0251.JPG >DSC_0251.b64

To assign result to variable use

test=`base64 DSC_0251.JPG`

Updating a java map entry

You just use the method

public Object put(Object key, Object value)

if the key was already present in the Map then the previous value is returned.

How to use boolean datatype in C?

We can use enum type for this.We don't require a library. For example

           enum {false,true};

the value for false will be 0 and the value for true will be 1.

How to prevent a jQuery Ajax request from caching in Internet Explorer?

You can disable caching globally using $.ajaxSetup(), for example:

$.ajaxSetup({ cache: false });

This appends a timestamp to the querystring when making the request. To turn cache off for a particular $.ajax() call, set cache: false on it locally, like this:

$.ajax({
  cache: false,
  //other options...
});

Is it possible to view RabbitMQ message contents directly from the command line?

a bit late to this, but yes rabbitmq has a build in tracer that allows you to see the incomming messages in a log. When enabled, you can just tail -f /var/tmp/rabbitmq-tracing/.log (on mac) to watch the messages.

the detailed discription is here http://www.mikeobrien.net/blog/tracing-rabbitmq-messages

Use grep to report back only line numbers

I recommend the answers with sed and awk for just getting the line number, rather than using grep to get the entire matching line and then removing that from the output with cut or another tool. For completeness, you can also use Perl:

perl -nE '/pattern/ && say $.' filename

or Ruby:

ruby -ne 'puts $. if /pattern/' filename

What's the difference between setWebViewClient vs. setWebChromeClient?

WebViewClient provides the following callback methods, with which you can interfere in how WebView makes a transition to the next content.

void doUpdateVisitedHistory (WebView view, String url, boolean isReload)
void onFormResubmission (WebView view, Message dontResend, Message resend)
void onLoadResource (WebView view, String url)
void onPageCommitVisible (WebView view, String url)
void onPageFinished (WebView view, String url)
void onPageStarted (WebView view, String url, Bitmap favicon)
void onReceivedClientCertRequest (WebView view, ClientCertRequest request)
void onReceivedError (WebView view, int errorCode, String description, String failingUrl)
void onReceivedError (WebView view, WebResourceRequest request, WebResourceError error)
void onReceivedHttpAuthRequest (WebView view, HttpAuthHandler handler, String host, String realm)
void onReceivedHttpError (WebView view, WebResourceRequest request, WebResourceResponse errorResponse)
void onReceivedLoginRequest (WebView view, String realm, String account, String args)
void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error)
boolean onRenderProcessGone (WebView view, RenderProcessGoneDetail detail)
void onSafeBrowsingHit (WebView view, WebResourceRequest request, int threatType, SafeBrowsingResponse callback)
void onScaleChanged (WebView view, float oldScale, float newScale)
void onTooManyRedirects (WebView view, Message cancelMsg, Message continueMsg)
void onUnhandledKeyEvent (WebView view, KeyEvent event)
WebResourceResponse shouldInterceptRequest (WebView view, WebResourceRequest request)
WebResourceResponse shouldInterceptRequest (WebView view, String url)
boolean shouldOverrideKeyEvent (WebView view, KeyEvent event)
boolean shouldOverrideUrlLoading (WebView view, WebResourceRequest request)
boolean shouldOverrideUrlLoading (WebView view, String url)

WebChromeClient provides the following callback methods, with which your Activity or Fragment can update the surroundings of WebView.

Bitmap getDefaultVideoPoster ()
View getVideoLoadingProgressView ()
void getVisitedHistory (ValueCallback<String[]> callback)
void onCloseWindow (WebView window)
boolean onConsoleMessage (ConsoleMessage consoleMessage)
void onConsoleMessage (String message, int lineNumber, String sourceID)
boolean onCreateWindow (WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg)
void onExceededDatabaseQuota (String url, String databaseIdentifier, long quota, long estimatedDatabaseSize, long totalQuota, WebStorage.QuotaUpdater quotaUpdater)
void onGeolocationPermissionsHidePrompt ()
void onGeolocationPermissionsShowPrompt (String origin, GeolocationPermissions.Callback callback)
void onHideCustomView ()
boolean onJsAlert (WebView view, String url, String message, JsResult result)
boolean onJsBeforeUnload (WebView view, String url, String message, JsResult result)
boolean onJsConfirm (WebView view, String url, String message, JsResult result)
boolean onJsPrompt (WebView view, String url, String message, String defaultValue, JsPromptResult result)
boolean onJsTimeout ()
void onPermissionRequest (PermissionRequest request)
void onPermissionRequestCanceled (PermissionRequest request)
void onProgressChanged (WebView view, int newProgress)
void onReachedMaxAppCacheSize (long requiredStorage, long quota, WebStorage.QuotaUpdater quotaUpdater)
void onReceivedIcon (WebView view, Bitmap icon)
void onReceivedTitle (WebView view, String title)
void onReceivedTouchIconUrl (WebView view, String url, boolean precomposed)
void onRequestFocus (WebView view)
void onShowCustomView (View view, int requestedOrientation, WebChromeClient.CustomViewCallback callback)
void onShowCustomView (View view, WebChromeClient.CustomViewCallback callback)
boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)

Print empty line?

Don't do

print("\n")

on the last line. It will give you 2 empty lines.

Simple way to create matrix of random numbers

You can drop the range(len()):

weights_h = [[random.random() for e in inputs[0]] for e in range(hiden_neurons)]

But really, you should probably use numpy.

In [9]: numpy.random.random((3, 3))
Out[9]:
array([[ 0.37052381,  0.03463207,  0.10669077],
       [ 0.05862909,  0.8515325 ,  0.79809676],
       [ 0.43203632,  0.54633635,  0.09076408]])

Bootstrap full responsive navbar with logo or brand name text

I set .navbar-brand { min-height: inherit } which solved the issue for me (thanks @creimers for inspiration).

How to remove "onclick" with JQuery?

After trying so hard with bind, unbind, on, off, click, attr, removeAttr, prop I made it work. So, I have the following scenario: In my html i have NOT attached any inline onclick handlers.

Then in my Javascript i used the following to add an inline onclick handler:

$(element).attr('onclick','myFunction()');

To remove this at a later point from Javascript I used the following:

$(element).prop('onclick',null);

This is the way it worked for me to bind and unbind click events dinamically in Javascript. Remember NOT to insert any inline onclick handler in your elements.

Redirect echo output in shell script to logfile

You can add this line on top of your script:

#!/bin/bash
# redirect stdout/stderr to a file
exec &> logfile.txt

OR else to redirect only stdout use:

exec > logfile.txt

Set focus and cursor to end of text input field / string w. Jquery

You can do this using Input.setSelectionRange, part of the Range API for interacting with text selections and the text cursor:

var searchInput = $('#Search');

// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;

searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);

Demo: Fiddle

Git adding files to repo

my problem (git on macOS) was solved by using sudo git instead of just git in all add and commit commands

How can I make a weak protocol reference in 'pure' Swift (without @objc)

Supplemental Answer

I was always confused about whether delegates should be weak or not. Recently I've learned more about delegates and when to use weak references, so let me add some supplemental points here for the sake of future viewers.

  • The purpose of using the weak keyword is to avoid strong reference cycles (retain cycles). Strong reference cycles happen when two class instances have strong references to each other. Their reference counts never go to zero so they never get deallocated.

  • You only need to use weak if the delegate is a class. Swift structs and enums are value types (their values are copied when a new instance is made), not reference types, so they don't make strong reference cycles.

  • weak references are always optional (otherwise you would used unowned) and always use var (not let) so that the optional can be set to nil when it is deallocated.

  • A parent class should naturally have a strong reference to its child classes and thus not use the weak keyword. When a child wants a reference to its parent, though, it should make it a weak reference by using the weak keyword.

  • weak should be used when you want a reference to a class that you don't own, not just for a child referencing its parent. When two non-hierarchical classes need to reference each other, choose one to be weak. The one you choose depends on the situation. See the answers to this question for more on this.

  • As a general rule, delegates should be marked as weak because most delegates are referencing classes that they do not own. This is definitely true when a child is using a delegate to communicate with a parent. Using a weak reference for the delegate is what the documentation recommends. (But see this, too.)

  • Protocols can be used for both reference types (classes) and value types (structs, enums). So in the likely case that you need to make a delegate weak, you have to make it an object-only protocol. The way to do that is to add AnyObject to the protocol's inheritance list. (In the past you did this using the class keyword, but AnyObject is preferred now.)

    protocol MyClassDelegate: AnyObject {
        // ...
    }
    
    class SomeClass {
        weak var delegate: MyClassDelegate?
    }
    

Further Study

Reading the following articles is what helped me to understand this much better. They also discuss related issues like the unowned keyword and the strong reference cycles that happen with closures.

Related

How to search through all Git and Mercurial commits in the repository for a certain string?

In addition to richq answer of using git log -g --grep=<regexp> or git grep -e <regexp> $(git log -g --pretty=format:%h): take a look at the following blog posts by Junio C Hamano, current git maintainer


Summary

Both git grep and git log --grep are line oriented, in that they look for lines that match specified pattern.

You can use git log --grep=<foo> --grep=<bar> (or git log --author=<foo> --grep=<bar> that internally translates to two --grep) to find commits that match either of patterns (implicit OR semantic).

Because of being line-oriented, the useful AND semantic is to use git log --all-match --grep=<foo> --grep=<bar> to find commit that has both line matching first and line matching second somewhere.

With git grep you can combine multiple patterns (all which must use the -e <regexp> form) with --or (which is the default), --and, --not, ( and ). For grep --all-match means that file must have lines that match each of alternatives.

Rotating a two-dimensional array in Python

def ruota_orario(matrix):
   ruota=list(zip(*reversed(matrix)))
   return[list(elemento) for elemento in ruota]
def ruota_antiorario(matrix):
   ruota=list(zip(*reversed(matrix)))
   return[list(elemento)[::-1] for elemento in ruota][::-1]

How to interpolate variables in strings in JavaScript, without concatenation?

If you're trying to do interpolation for microtemplating, I like Mustache.js for that purpose.

How can I find where Python is installed on Windows?

Go to C:\Users\USER\AppData\Local\Programs\Python\Python36 if it is not there then open console by windows+^R Then type cmd and hit enter type python if installed in your local file it will show you its version from there type the following import os import sys os.path.dirname(sys.executable)

C# 'or' operator?

Or is || in C#.

You may have a look at this.

Get final URL after curl is redirected

You can do this with wget usually. wget --content-disposition "url" additionally if you add -O /dev/null you will not be actually saving the file.

wget -O /dev/null --content-disposition example.com

How to ignore conflicts in rpm installs

Try Freshen command:

rpm -Fvh *.rpm

How to set environment via `ng serve` in Angular 6

You need to use the new configuration option (this works for ng build and ng serve as well)

ng serve --configuration=local

or

ng serve -c local

If you look at your angular.json file, you'll see that you have finer control over settings for each configuration (aot, optimizer, environment files,...)

"configurations": {
  "production": {
    "optimization": true,
    "outputHashing": "all",
    "sourceMap": false,
    "extractCss": true,
    "namedChunks": false,
    "aot": true,
    "extractLicenses": true,
    "vendorChunk": false,
    "buildOptimizer": true,
    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.prod.ts"
      }
    ]
  }
}

You can get more info here for managing environment specific configurations.

As pointed in the other response below, if you need to add a new 'environment', you need to add a new configuration to the build task and, depending on your needs, to the serve and test tasks as well.

Adding a new environment

Edit: To make it clear, file replacements must be specified in the build section. So if you want to use ng serve with a specific environment file (say dev2), you first need to modify the build section to add a new dev2 configuration

"build": {
   "configurations": {
        "dev2": {

          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.dev2.ts"
            }
            /* You can add all other options here, such as aot, optimization, ... */
          ],
          "serviceWorker": true
        },

Then modify your serve section to add a new configuration as well, pointing to the dev2 build configuration you just declared

"serve":
      "configurations": {
        "dev2": {
          "browserTarget": "projectName:build:dev2"
        }

Then you can use ng serve -c dev2, which will use the dev2 config file

How can I increment a char?

def doubleChar(str):
    result = ''
    for char in str:
        result += char * 2
    return result

print(doubleChar("amar"))

output:

aammaarr

Using SVG as background image

Try placing it on your body

body {
    height: 100%;
    background-image: url(../img/bg.svg);
    background-size:100% 100%;
    -o-background-size: 100% 100%;
    -webkit-background-size: 100% 100%;
    background-size:cover;
}

What is the easiest way to clear a database from the CLI with manage.py in Django?

You can use the Django-Truncate library to delete all data of a table without destroying the table structure.

Example:

  1. First, install django-turncate using your terminal/command line:
pip install django-truncate
  1. Add "django_truncate" to your INSTALLED_APPS in the settings.py file:
INSTALLED_APPS = [
    ...
    'django_truncate',
]
  1. Use this command in your terminal to delete all data of the table from the app.
python manage.py truncate --apps app_name --models table_name

What are examples of TCP and UDP in real life?

Real life examples of both TCP and UDP tcp -> a phone call, sms or anything specific to destination UDP -> a FM radio channel (AM), Wi-Fi.

cannot resolve symbol javafx.application in IntelliJ Idea IDE

Sample Java application:

I'm crossposting my answer from another question here since it is related and also seems to solve the problem in the question.

Here is my example project with OpenJDK 12, JavaFX 12 and Gradle 5.4

  • Opens a JavaFX window with the title "Hello World!"
  • Able to build a working runnable distribution zip file (Windows to be tested)
  • Able to open and run in IntelliJ without additional configuration
  • Able to run from the command line

I hope somebody finds the Github project useful.

Instructions for the Scala case:

Additionally below are instructions that work with the Gradle Scala plugin, but don't seem work with Java. I'm leaving this here in case somebody else is also using Scala, Gradle and JavaFX.

1) As mentioned in the question, the JavaFX Gradle plugin needs to be set up. Open JavaFX has detailed documentation on this

2) Additionally you need the the JavaFX SDK for your platform unzipped somewhere. NOTE: Be sure to scroll down to Latest releases section where JavaFX 12 is (LTS 11 is first for some reason.)

3) Then, in IntelliJ you go to the File -> Project Structure -> Libraries, hit the ?-button and add the lib folder from the unzipped JavaFX SDK.

For longer instructions with screenshots, check out the excellent Open JavaFX docs for IntelliJ I can't get a deep link working, so select JavaFX and IntelliJ and then Modular from IDE from the docs nav. Then scroll down to step 3. Create a library. Consider checking the other steps too if you are having trouble.

It is difficult to say if this is exactly the same situation as in the original question, but it looked similar enough that I landed here, so I'm adding my experience here to help others.

How to send parameters from a notification-click to an activity?

I tried everything but nothing worked.

eventually came up with following solution.

1- in manifest add for the activity android:launchMode="singleTop"

2- while making pending intent do the following, use bundle instead of directly using intent.putString() or intent.putInt()

                    Intent notificationIntent = new Intent(getApplicationContext(), CourseActivity.class);

                    Bundle bundle = new Bundle();
                    bundle.putString(Constants.EXAM_ID,String.valueOf(lectureDownloadStatus.getExamId()));
                    bundle.putInt(Constants.COURSE_ID,(int)lectureDownloadStatus.getCourseId());
                    bundle.putString(Constants.IMAGE_URL,lectureDownloadStatus.getImageUrl());

                    notificationIntent.putExtras(bundle);

                    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                            Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(),
                            new Random().nextInt(), notificationIntent,
                            PendingIntent.FLAG_UPDATE_CURRENT); 

Can you blur the content beneath/behind a div?

you can do this with css3, this blurs the whole element

div (or whatever element) {
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
}

Fiddle: http://jsfiddle.net/H4DU4/

Best dynamic JavaScript/JQuery Grid

Have a look at agiletoolkit.org as this has a simple to use CRUD which supports 2,4,6,7,9,10 and 12 out of the box (uses Ajax to defender the grid when adding,deleting data and it integrates with jquery.

I would post some examples but on an iPad at the moment.

Convert floating point number to a certain precision, and then copy to string

The str function has a bug. Please try the following. You will see '0,196553' but the right output is '0,196554'. Because the str function's default value is ROUND_HALF_UP.

>>> value=0.196553500000 
>>> str("%f" % value).replace(".", ",")

How to push both key and value into an Array in Jquery

arr[title] = link;

You're not pushing into the array, you're setting the element with the key title to the value link. As such your array should be an object.

bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

The new version has changed.. for the latest version use the code below:

$('#UpToDate').datetimepicker({
        format:'MMMM DD, YYYY',
        maxDate:moment(),
        defaultDate:moment()            
    }).on('dp.change',function(e){
        console.log(e);
    });

error: expected declaration or statement at end of input in c

You probably have syntax error. You most likely forgot to put a } or ; somewhere above this function.

Keystore change passwords

Changing keystore password

$ keytool -storepasswd -keystore keystorename
Enter keystore password:  <old password>
New keystore password: <new password>
Re-enter new keystore password: <new password>

Changing keystore alias password

$keytool -keypasswd -keystore keystorename -alias aliasname
Enter keystore password:  
New key password for <aliasname>: 
Re-enter new key password for <aliasname>:

Note:

**Keystorename**: name of your keystore(with path if you are indifferent folder) 
**aliasname**: alias name you used when creating (if name has space you can use \) 
for example: $keytool -keypasswd -keystore keystorename -alias stop\ watch

How to use filesaver.js

For people who want to load it in the console :

var s = document.createElement('script');
s.type = 'text/javascript';
s.src = 'https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js';
document.body.appendChild(s);

Then :

saveAs(new Blob([data], {type: "application/octet-stream ;charset=utf-8"}), "video.ts")

File will be save when you're out of a breakpoint (at least on Chrome)

Asserting successive calls to a mock method

I always have to look this one up time and time again, so here is my answer.


Asserting multiple method calls on different objects of the same class

Suppose we have a heavy duty class (which we want to mock):

In [1]: class HeavyDuty(object):
   ...:     def __init__(self):
   ...:         import time
   ...:         time.sleep(2)  # <- Spends a lot of time here
   ...:     
   ...:     def do_work(self, arg1, arg2):
   ...:         print("Called with %r and %r" % (arg1, arg2))
   ...:  

here is some code that uses two instances of the HeavyDuty class:

In [2]: def heavy_work():
   ...:     hd1 = HeavyDuty()
   ...:     hd1.do_work(13, 17)
   ...:     hd2 = HeavyDuty()
   ...:     hd2.do_work(23, 29)
   ...:    


Now, here is a test case for the heavy_work function:

In [3]: from unittest.mock import patch, call
   ...: def test_heavy_work():
   ...:     expected_calls = [call.do_work(13, 17),call.do_work(23, 29)]
   ...:     
   ...:     with patch('__main__.HeavyDuty') as MockHeavyDuty:
   ...:         heavy_work()
   ...:         MockHeavyDuty.return_value.assert_has_calls(expected_calls)
   ...:  

We are mocking the HeavyDuty class with MockHeavyDuty. To assert method calls coming from every HeavyDuty instance we have to refer to MockHeavyDuty.return_value.assert_has_calls, instead of MockHeavyDuty.assert_has_calls. In addition, in the list of expected_calls we have to specify which method name we are interested in asserting calls for. So our list is made of calls to call.do_work, as opposed to simply call.

Exercising the test case shows us it is successful:

In [4]: print(test_heavy_work())
None


If we modify the heavy_work function, the test fails and produces a helpful error message:

In [5]: def heavy_work():
   ...:     hd1 = HeavyDuty()
   ...:     hd1.do_work(113, 117)  # <- call args are different
   ...:     hd2 = HeavyDuty()
   ...:     hd2.do_work(123, 129)  # <- call args are different
   ...:     

In [6]: print(test_heavy_work())
---------------------------------------------------------------------------
(traceback omitted for clarity)

AssertionError: Calls not found.
Expected: [call.do_work(13, 17), call.do_work(23, 29)]
Actual: [call.do_work(113, 117), call.do_work(123, 129)]


Asserting multiple calls to a function

To contrast with the above, here is an example that shows how to mock multiple calls to a function:

In [7]: def work_function(arg1, arg2):
   ...:     print("Called with args %r and %r" % (arg1, arg2))

In [8]: from unittest.mock import patch, call
   ...: def test_work_function():
   ...:     expected_calls = [call(13, 17), call(23, 29)]    
   ...:     with patch('__main__.work_function') as mock_work_function:
   ...:         work_function(13, 17)
   ...:         work_function(23, 29)
   ...:         mock_work_function.assert_has_calls(expected_calls)
   ...:    

In [9]: print(test_work_function())
None


There are two main differences. The first one is that when mocking a function we setup our expected calls using call, instead of using call.some_method. The second one is that we call assert_has_calls on mock_work_function, instead of on mock_work_function.return_value.

How to create a numpy array of all True or all False?

numpy.full((2,2), True, dtype=bool)

MongoDB and "joins"

The fact that mongoDB is not relational have led some people to consider it useless. I think that you should know what you are doing before designing a DB. If you choose to use noSQL DB such as MongoDB, you better implement a schema. This will make your collections - more or less - resemble tables in SQL databases. Also, avoid denormalization (embedding), unless necessary for efficiency reasons.

If you want to design your own noSQL database, I suggest to have a look on Firebase documentation. If you understand how they organize the data for their service, you can easily design a similar pattern for yours.

As others pointed out, you will have to do the joins client-side, except with Meteor (a Javascript framework), you can do your joins server-side with this package (I don't know of other framework which enables you to do so). However, I suggest you read this article before deciding to go with this choice.

Edit 28.04.17: Recently Firebase published this excellent series on designing noSql Databases. They also highlighted in one of the episodes the reasons to avoid joins and how to get around such scenarios by denormalizing your database.

How to download image using requests

I have the same need for downloading images using requests. I first tried the answer of Martijn Pieters, and it works well. But when I did a profile on this simple function, I found that it uses so many function calls compared to urllib and urllib2.

I then tried the way recommended by the author of requests module:

import requests
from PIL import Image
# python2.x, use this instead  
# from StringIO import StringIO
# for python3.x,
from io import StringIO

r = requests.get('https://example.com/image.jpg')
i = Image.open(StringIO(r.content))

This much more reduced the number of function calls, thus speeded up my application. Here is the code of my profiler and the result.

#!/usr/bin/python
import requests
from StringIO import StringIO
from PIL import Image
import profile

def testRequest():
    image_name = 'test1.jpg'
    url = 'http://example.com/image.jpg'

    r = requests.get(url, stream=True)
    with open(image_name, 'wb') as f:
        for chunk in r.iter_content():
            f.write(chunk)

def testRequest2():
    image_name = 'test2.jpg'
    url = 'http://example.com/image.jpg'

    r = requests.get(url)

    i = Image.open(StringIO(r.content))
    i.save(image_name)

if __name__ == '__main__':
    profile.run('testUrllib()')
    profile.run('testUrllib2()')
    profile.run('testRequest()')

The result for testRequest:

343080 function calls (343068 primitive calls) in 2.580 seconds

And the result for testRequest2:

3129 function calls (3105 primitive calls) in 0.024 seconds

Two div blocks on same line

Try an HTML table or use the following CSS :

<div id="bloc1" style="float:left">...</div>
<div id="bloc2">...</div>

(or use an HTML table)

How to programmatically set drawableLeft on Android button?

Try this:

((Button)btn).getCompoundDrawables()[0].setAlpha(btn.isEnabled() ? 255 : 100);

Is it possible to use an input value attribute as a CSS selector?

Following the currently top voted answer, I've found using a dataset / data attribute works well.

_x000D_
_x000D_
//Javascript

const input1 = document.querySelector("#input1");
input1.value = "0.00";
input1.dataset.value = input1.value;
//dataset.value will set "data-value" on the input1 HTML element
//and will be used by CSS targetting the dataset attribute

document.querySelectorAll("input").forEach((input) => {
  input.addEventListener("input", function() {
    this.dataset.value = this.value;
    console.log(this);
  })
})
_x000D_
/*CSS*/

input[data-value="0.00"] {
  color: red;
}
_x000D_
<!--HTML-->

<div>
  <p>Input1 is programmatically set by JavaScript:</p>
  <label for="input1">Input 1:</label>
  <input id="input1" value="undefined" data-value="undefined">
</div>
<br>
<div>
  <p>Try typing 0.00 inside input2:</p>
  <label for="input2">Input 2:</label>
  <input id="input2" value="undefined" data-value="undefined">
</div>
_x000D_
_x000D_
_x000D_

Matching an empty input box using CSS

This worked for me:

For the HTML, add the required attribute to the input element

<input class="my-input-element" type="text" placeholder="" required />

For the CSS, use the :invalid selector to target the empty input

input.my-input-element:invalid {

}

Notes:

  • About required from w3Schools.com: "When present, it specifies that an input field must be filled out before submitting the form."

calculating number of days between 2 columns of dates in data frame

Without your seeing your data (you can use the output of dput(head(survey)) to show us) this is a shot in the dark:

survey <- data.frame(date=c("2012/07/26","2012/07/25"),tx_start=c("2012/01/01","2012/01/01"))

survey$date_diff <- as.Date(as.character(survey$date), format="%Y/%m/%d")-
                  as.Date(as.character(survey$tx_start), format="%Y/%m/%d")
survey
       date   tx_start date_diff
1 2012/07/26 2012/01/01  207 days
2 2012/07/25 2012/01/01  206 days

Controlling a USB power supply (on/off) with Linux

According to the docs, there were several changes to the USB power management from kernels 2.6.32, which seem to settle in 2.6.38. Now you'll need to wait for the device to become idle, which is governed by the particular device driver. The driver needs to support it, otherwise the device will never reach this state. Unluckily, now the user has no chance to force this. However, if you're lucky and your device can become idle, then to turn this off you need to:

echo "0" > "/sys/bus/usb/devices/usbX/power/autosuspend"
echo "auto" > "/sys/bus/usb/devices/usbX/power/level"

or, for kernels around 2.6.38 and above:

echo "0" > "/sys/bus/usb/devices/usbX/power/autosuspend_delay_ms"
echo "auto" > "/sys/bus/usb/devices/usbX/power/control"

This literally means, go suspend at the moment the device becomes idle.

So unless your fan is something "intelligent" that can be seen as a device and controlled by a driver, you probably won't have much luck on current kernels.

How can INSERT INTO a table 300 times within a loop in SQL?

Found some different answers that I combined to solve simulair problem:

CREATE TABLE nummer (ID INTEGER PRIMARY KEY, num, text, text2);
WITH RECURSIVE
  for(i) AS (VALUES(1) UNION ALL SELECT i+1 FROM for WHERE i < 1000000)
INSERT INTO nummer SELECT i, i+1, "text" || i, "otherText" || i FROM for;

Adds 1 miljon rows with

  • id increased by one every itteration
  • num one greater then id
  • text concatenated with id-number like: text1, text2 ... text1000000
  • text2 concatenated with id-number like: otherText1, otherText2 ... otherText1000000

How to use JavaScript to change div backgroundColor

<script type="text/javascript">
 function enter(elem){
     elem.style.backgroundColor = '#FF0000';
 }

 function leave(elem){
     elem.style.backgroundColor = '#FFFFFF';
 }
</script>
 <div onmouseover="enter(this)" onmouseout="leave(this)">
       Some Text
 </div>

Netbeans - Error: Could not find or load main class

Just close the Netbeans. Go to C:\Users\YOUR_PC_NAME\AppData\Local\Netbeans and delete the Cache folder. The open the Netbeans again and run the project. It works like magic for me.

(AppData folder might be hidden probably, if so, you need to make it appear in Folder Options).enter image description here

Break when a value changes using the Visual Studio debugger

I remember the way you described it using Visual Basic 6.0. In Visual Studio, the only way I have found so far is by specifying a breakpoint condition.

How to store arrays in MySQL?

In MySQL, use the JSON type.

Contra the answers above, the SQL standard has included array types for almost twenty years; they are useful, even if MySQL has not implemented them.

In your example, however, you'll likely want to create three tables: person and fruit, then person_fruit to join them.

DROP TABLE IF EXISTS person_fruit;
DROP TABLE IF EXISTS person;
DROP TABLE IF EXISTS fruit;

CREATE TABLE person (
  person_id   INT           NOT NULL AUTO_INCREMENT,
  person_name VARCHAR(1000) NOT NULL,
  PRIMARY KEY (person_id)
);

CREATE TABLE fruit (
  fruit_id    INT           NOT NULL AUTO_INCREMENT,
  fruit_name  VARCHAR(1000) NOT NULL,
  fruit_color VARCHAR(1000) NOT NULL,
  fruit_price INT           NOT NULL,
  PRIMARY KEY (fruit_id)
);

CREATE TABLE person_fruit (
  pf_id     INT NOT NULL AUTO_INCREMENT,
  pf_person INT NOT NULL,
  pf_fruit  INT NOT NULL,
  PRIMARY KEY (pf_id),
  FOREIGN KEY (pf_person) REFERENCES person (person_id),
  FOREIGN KEY (pf_fruit) REFERENCES fruit (fruit_id)
);

INSERT INTO person (person_name)
VALUES
  ('John'),
  ('Mary'),
  ('John'); -- again

INSERT INTO fruit (fruit_name, fruit_color, fruit_price)
VALUES
  ('apple', 'red', 1),
  ('orange', 'orange', 2),
  ('pineapple', 'yellow', 3);

INSERT INTO person_fruit (pf_person, pf_fruit)
VALUES
  (1, 1),
  (1, 2),
  (2, 2),
  (2, 3),
  (3, 1),
  (3, 2),
  (3, 3);

If you wish to associate the person with an array of fruits, you can do so with a view:

DROP VIEW IF EXISTS person_fruit_summary;
CREATE VIEW person_fruit_summary AS
  SELECT
    person_id                                                                                              AS pfs_person_id,
    max(person_name)                                                                                       AS pfs_person_name,
    cast(concat('[', group_concat(json_quote(fruit_name) ORDER BY fruit_name SEPARATOR ','), ']') as json) AS pfs_fruit_name_array
  FROM
    person
    INNER JOIN person_fruit
      ON person.person_id = person_fruit.pf_person
    INNER JOIN fruit
      ON person_fruit.pf_fruit = fruit.fruit_id
  GROUP BY
    person_id;

The view shows the following data:

+---------------+-----------------+----------------------------------+
| pfs_person_id | pfs_person_name | pfs_fruit_name_array             |
+---------------+-----------------+----------------------------------+
|             1 | John            | ["apple", "orange"]              |
|             2 | Mary            | ["orange", "pineapple"]          |
|             3 | John            | ["apple", "orange", "pineapple"] |
+---------------+-----------------+----------------------------------+

In 5.7.22, you'll want to use JSON_ARRAYAGG, rather than hack the array together from a string.

Deck of cards JAVA

I think the solution is just as simple as this:

Card temp = deck[cardAindex];
deck[cardAIndex]=deck[cardBIndex]; 
deck[cardBIndex]=temp;

Batch File; List files in directory, only filenames?

create a batch-file with the following code:

dir %1 /b /a-d > list.txt

Then drag & drop a directory on it and the files inside the directory will be listed in list.txt

PHP namespaces and "use"

If you need to order your code into namespaces, just use the keyword namespace:

file1.php

namespace foo\bar;

In file2.php

$obj = new \foo\bar\myObj();

You can also use use. If in file2 you put

use foo\bar as mypath;

you need to use mypath instead of bar anywhere in the file:

$obj  = new mypath\myObj();

Using use foo\bar; is equal to use foo\bar as bar;.

How to sort the files according to the time stamp in unix?

File modification:

ls -t

Inode change:

ls -tc

File access:

ls -tu

"Newest" one at the bottom:

ls -tr

None of this is a creation time. Most Unix filesystems don't support creation timestamps.

Terminating idle mysql connections

I don't see any problem, unless you are not managing them using a connection pool.

If you use connection pool, these connections are re-used instead of initiating new connections. so basically, leaving open connections and re-use them it is less problematic than re-creating them each time.

cv2.imshow command doesn't work properly in opencv-python

error: (-215) size.width>0 && size.height>0 in function imshow

This error is produced because the image is not found. So it's not an error of imshow function.

How to loop through an associative array and get the key?

foreach($array as $k => $v)

Where $k is the key and $v is the value

Or if you just need the keys use array_keys()

Is __init__.py not required for packages in Python 3.3+

Python 3.3+ has Implicit Namespace Packages that allow it to create a packages without an __init__.py file.

Allowing implicit namespace packages means that the requirement to provide an __init__.py file can be dropped completely, and affected ... .

The old way with __init__.py files still works as in Python 2.

How do you do exponentiation in C?

Similar to an earlier answer, this will handle positive and negative integer powers of a double nicely.

double intpow(double a, int b)
{
  double r = 1.0;
  if (b < 0)
  {
    a = 1.0 / a;
    b = -b;
  }
  while (b)
  {
    if (b & 1)
      r *= a;
    a *= a;
    b >>= 1;
  }
  return r;
}

How to check if a directory containing a file exist?

EDIT: as of Java8 you'd better use Files class:

Path resultingPath = Files.createDirectories('A/B');

I don't know if this ultimately fixes your problem but class File has method mkdirs() which fully creates the path specified by the file.

File f = new File("/A/B/");
f.mkdirs();

Python list directory, subdirectory, and files

It's just an addition, with this you can get the data into CSV format

import sys,os
try:
    import pandas as pd
except:
    os.system("pip3 install pandas")
    
root = "/home/kiran/Downloads/MainFolder" # it may have many subfolders and files inside
lst = []
from fnmatch import fnmatch
pattern = "*.csv"      #I want to get only csv files 
pattern = "*.*"        # Note: Use this pattern to get all types of files and folders 
for path, subdirs, files in os.walk(root):
    for name in files:
        if fnmatch(name, pattern):
            lst.append((os.path.join(path, name)))
df = pd.DataFrame({"filePaths":lst})
df.to_csv("filepaths.csv")

How to import JsonConvert in C# application?

If you are developing a .Net Core WebApi or WebSite you dont not need to install newtownsoft.json to perform json serialization/deserealization

Just make sure that your controller method returns a JsonResult and call return Json(<objectoToSerialize>); like this example

namespace WebApi.Controllers
{
    [Produces("application/json")]
    [Route("api/Accounts")]
    public class AccountsController : Controller
    {
        // GET: api/Transaction
        [HttpGet]
        public JsonResult Get()
        {
            List<Account> lstAccounts;

            lstAccounts = AccountsFacade.GetAll();

            return Json(lstAccounts);
        }
    }
}

If you are developing a .Net Framework WebApi or WebSite you need to use NuGet to download and install the newtonsoft json package

"Project" -> "Manage NuGet packages" -> "Search for "newtonsoft json". -> click "install".

namespace WebApi.Controllers
{
    [Produces("application/json")]
    [Route("api/Accounts")]
    public class AccountsController : Controller
    {
        // GET: api/Transaction
        [HttpGet]
        public JsonResult Get()
        {
            List<Account> lstAccounts;

            lstAccounts = AccountsFacade.GetAll();

            //This line is different !! 
            return new JsonConvert.SerializeObject(lstAccounts);
        }
    }
}

More details can be found here - https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-2.1

How can I make SMTP authenticated in C#

Set the Credentials property before sending the message.

Set padding for UITextField with UITextBorderStyleNone

Why not Attributed String !?!, this is one of the blessing feature of IOS 6.0 :)

NSMutableParagraphStyle *mps = [[NSMutableParagraphStyle alloc] init];
            mps.firstLineHeadIndent = 5.0f;
UIColor *placeColor = self.item.bgColor;

textFieldInstance.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"My Place Holder" attributes:@{NSForegroundColorAttributeName: placeColor, NSFontAttributeName : [UIFont systemFontOfSize:7.0f], NSParagraphStyleAttributeName : mps}];

How can I run Tensorboard on a remote server?

Here is what I do to avoid the issues of making the remote server accept your local external IP:

  • when I ssh into the machine, I use the option -L to transfer the port 6006 of the remote server into the port 16006 of my machine (for instance): ssh -L 16006:127.0.0.1:6006 olivier@my_server_ip

What it does is that everything on the port 6006 of the server (in 127.0.0.1:6006) will be forwarded to my machine on the port 16006.


  • You can then launch tensorboard on the remote machine using a standard tensorboard --logdir log with the default 6006port
  • On your local machine, go to http://127.0.0.1:16006 and enjoy your remote TensorBoard.

What's the difference between a proxy server and a reverse proxy server?

The previous answers were accurate, but perhaps too terse. I will try to add some examples.

First of all, the word "proxy" describes someone or something acting on behalf of someone else.

In the computer realm, we are talking about one server acting on the behalf of another computer.

For the purposes of accessibility, I will limit my discussion to web proxies - however, the idea of a proxy is not limited to websites.

FORWARD proxy

Most discussion of web proxies refers to the type of proxy known as a "forward proxy."

The proxy event, in this case, is that the "forward proxy" retrieves data from another web site on behalf of the original requestee.

A tale of 3 computers (part I)

For an example, I will list three computers connected to the internet.

  • X = your computer, or "client" computer on the internet
  • Y = the proxy web site, proxy.example.org
  • Z = the web site you want to visit, www.example.net

Normally, one would connect directly from X --> Z.

However, in some scenarios, it is better for Y --> Z on behalf of X, which chains as follows: X --> Y --> Z.

Reasons why X would want to use a forward proxy server:

Here is a (very) partial list of uses of a forward proxy server:

  • 1) X is unable to access Z directly because

    • a) Someone with administrative authority over X's internet connection has decided to block all access to site Z.

      • Examples:

        • The Storm Worm virus is spreading by tricking people into visiting familypostcards2008.com, so the system administrator has blocked access to the site to prevent users from inadvertently infecting themselves.

        • Employees at a large company have been wasting too much time on facebook.com, so management wants access blocked during business hours.

        • A local elementary school disallows internet access to the playboy.com website.

        • A government is unable to control the publishing of news, so it controls access to news instead, by blocking sites such as wikipedia.org. See TOR or FreeNet.

    • b) The administrator of Z has blocked X.

      • Examples:

        • The administrator of Z has noticed hacking attempts coming from X, so the administrator has decided to block X's IP address (and/or netrange).

        • Z is a forum website. X is spamming the forum. Z blocks X.

REVERSE proxy

A tale of 3 computers (part II)

For this example, I will list three computers connected to the internet.

  • X = your computer, or "client" computer on the internet
  • Y = the reverse proxy web site, proxy.example.com
  • Z = the web site you want to visit, www.example.net

Normally, one would connect directly from X --> Z.

However, in some scenarios, it is better for the administrator of Z to restrict or disallow direct access and force visitors to go through Y first. So, as before, we have data being retrieved by Y --> Z on behalf of X, which chains as follows: X --> Y --> Z.

What is different this time compared to a "forward proxy," is that this time the user X does not know he is accessing Z, because the user X only sees he is communicating with Y. The server Z is invisible to clients and only the reverse proxy Y is visible externally. A reverse proxy requires no (proxy) configuration on the client side.

The client X thinks he is only communicating with Y (X --> Y), but the reality is that Y forwarding all communication (X --> Y --> Z again).

Reasons why Z would want to set up a reverse proxy server:

  • 1) Z wants to force all traffic to its web site to pass through Y first.
    • a) Z has a large web site that millions of people want to see, but a single web server cannot handle all the traffic. So Z sets up many servers and puts a reverse proxy on the internet that will send users to the server closest to them when they try to visit Z. This is part of how the Content Distribution Network (CDN) concept works.
  • 2) The administrator of Z is worried about retaliation for content hosted on the server and does not want to expose the main server directly to the public.
    • a) Owners of Spam brands such as "Canadian Pharmacy" appear to have thousands of servers, while in reality having most websites hosted on far fewer servers. Additionally, abuse complaints about the spam will only shut down the public servers, not the main server.

In the above scenarios, Z has the ability to choose Y.

Links to topics from the post:

Content Delivery Network

Forward proxy software (server side)

Reverse proxy software for HTTP (server side)

Reverse proxy software for TCP (server side)

See also:

Cleaning up old remote git branches

Deletion is always a challenging task and can be dangerous!!! Therefore, first execute the following command to see what will happen:

git push --all --prune --dry-run

By doing so like the above, git will provide you with a list of what would happen if the below command is executed.

Then run the following command to remove all branches from the remote repo that are not in your local repo:

git push --all --prune

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

I ran into this exact issue upon a new install of Apache 2.4. After a few hours of googling and testing I finally found out that I also had to allow access to the directory that contains the (non-existent) target of the Alias directive. That is, this worked for me:

# File: /etc/apache2/conf-available/php5-fpm.conf
<IfModule mod_fastcgi.c>
    AddHandler php5-fcgi .php
    Action php5-fcgi /php5-fcgi
    Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi
    FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -socket /var/run/php5-fpm.sock -pass-header Authorization

    # NOTE: using '/usr/lib/cgi-bin/php5-cgi' here does not work,
    #   it doesn't exist in the filesystem!
    <Directory /usr/lib/cgi-bin>
        Require all granted
    </Directory>
</Ifmodule>

How to create a pivot query in sql server without aggregate function

Check this out as well: using xml path and pivot

SQLFIDDLE DEMO

| ACCOUNT | 2000 | 2001 | 2002 |
--------------------------------
|   Asset |  205 |  142 |  421 |
|  Equity |  365 |  214 |  163 |
|  Profit |  524 |  421 |  325 |

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.period) 
            FROM demo c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT account, ' + @cols + ' from 
            (
                select account
                    , value
                    , period
                from demo
           ) x
            pivot 
            (
                 max(value)
                for period in (' + @cols + ')
            ) p '


execute(@query)

How to fix Cannot find module 'typescript' in Angular 4?

If you don't have particular needs, I suggest to install Typescript locally.

NPM Installation Method

npm install --global typescript # Global installation
npm install --save-dev typescript # Local installation

Yarn Installation Method

yarn global add typescript # Global installation
yarn add --dev typescript # Local installation

Removing items from a ListBox in VB.net

This worked for me.

Private Sub listbox_MouseDoubleClick(sender As Object, e As MouseEventArgs) 
        Handles listbox.MouseDoubleClick
        listbox.Items.RemoveAt(listbox.SelectedIndex.ToString())
    End Sub

Integration Testing POSTing an entire object to Spring MVC controller

I think most of these solutions are far too complicated. I assume that in your test controller you have this

 @Autowired
 private ObjectMapper objectMapper;

If its a rest service

@Test
public void test() throws Exception {
   mockMvc.perform(post("/person"))
          .contentType(MediaType.APPLICATION_JSON)
          .content(objectMapper.writeValueAsString(new Person()))
          ...etc
}

For spring mvc using a posted form I came up with this solution. (Not really sure if its a good idea yet)

private MultiValueMap<String, String> toFormParams(Object o, Set<String> excludeFields) throws Exception {
    ObjectReader reader = objectMapper.readerFor(Map.class);
    Map<String, String> map = reader.readValue(objectMapper.writeValueAsString(o));

    MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
    map.entrySet().stream()
            .filter(e -> !excludeFields.contains(e.getKey()))
            .forEach(e -> multiValueMap.add(e.getKey(), (e.getValue() == null ? "" : e.getValue())));
    return multiValueMap;
}



@Test
public void test() throws Exception {
  MultiValueMap<String, String> formParams = toFormParams(new Phone(), 
  Set.of("id", "created"));

   mockMvc.perform(post("/person"))
          .contentType(MediaType.APPLICATION_FORM_URLENCODED)
          .params(formParams))
          ...etc
}

The basic idea is to - first convert object to json string to get all the field names easily - convert this json string into a map and dump it into a MultiValueMap that spring expects. Optionally filter out any fields you dont want to include (Or you could just annotate fields with @JsonIgnore to avoid this extra step)

Can I assume (bool)true == (int)1 for any C++ compiler?

I've found different compilers return different results on true. I've also found that one is almost always better off comparing a bool to a bool instead of an int. Those ints tend to change value over time as your program evolves and if you assume true as 1, you can get bitten by an unrelated change elsewhere in your code.

Java: int[] array vs int array[]

There is no difference between these two declarations, and both have the same performance.

Xampp Access Forbidden php

following steps might help any one

  1. check error log of apache2
  2. check folder permission is it accessible ? if not set it
  3. add following in vhost file <Directory "c://"> Options Indexes FollowSymLinks MultiViews AllowOverride all Order Deny,Allow Allow from all Require all granted
  4. last but might save time like mine check folder name(case sensitive "Pubic" is different form "public") you put in vhosts file and actual name. thanks

How to get the current time as datetime

Swift 2 answer :

 let date = NSDate()
 let calendar = NSCalendar.currentCalendar()
 let components = calendar.components([.Hour, .Minute], fromDate: date)
 let hour = components.hour
 let minutes = components.minute

Why do I get "a label can only be part of a statement and a declaration is not a statement" if I have a variable that is initialized after a label?

The language standard simply doesn't allow for it. Labels can only be followed by statements, and declarations do not count as statements in C. The easiest way to get around this is by inserting an empty statement after your label, which relieves you from keeping track of the scope the way you would need to inside a block.

#include <stdio.h>
int main () 
{
    printf("Hello ");
    goto Cleanup;
Cleanup: ; //This is an empty statement.
    char *str = "World\n";
    printf("%s\n", str);
}

Replace spaces with dashes and make all letters lower-case

Just use the String replace and toLowerCase methods, for example:

var str = "Sonic Free Games";
str = str.replace(/\s+/g, '-').toLowerCase();
console.log(str); // "sonic-free-games"

Notice the g flag on the RegExp, it will make the replacement globally within the string, if it's not used, only the first occurrence will be replaced, and also, that RegExp will match one or more white-space characters.

Declaring and using MySQL varchar variables

Declare @variable type(size);

Set @variable = 'String' or Int ;

Example:

 Declare @id int;
 set @id = 10;

 Declare @str char(50);
 set @str='Hello' ; 

How can I read inputs as numbers?

In Python 3.x, raw_input was renamed to input and the Python 2.x input was removed.

This means that, just like raw_input, input in Python 3.x always returns a string object.

To fix the problem, you need to explicitly make those inputs into integers by putting them in int:

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

Java error: Implicit super constructor is undefined for default constructor

It is possible but not the way you have it.

You have to add a no-args constructor to the base class and that's it!

public abstract class A {
    private String name;
    public A(){
        this.name = getName();
    }
    public abstract String getName();


    public String toString(){
        return "simple class name: " + this.getClass().getSimpleName() + " name:\"" + this.name + "\"";
    }
}
class B extends A {
    public String getName(){
        return "my name is B";
    }
    public static void main( String [] args ) {
        System.out.println( new C() );
    }
}
class C extends A {
    public String getName() {
        return "Zee";
    }
}

When you don't add a constructor ( any ) to a class the compiler add the default no arg contructor for you.

When the defualt no arg calls to super(); and since you don't have it in the super class you get that error message.

That's about the question it self.

Now, expanding the answer:

Are you aware that creating a subclass ( behavior ) to specify different a different value ( data ) makes no sense??!!! I hope you do.

If the only thing that is changes is the "name" then a single class parametrized is enough!

So you don't need this:

MyClass a = new A("A");
MyClass b = new B("B");
MyClass c = new C("C");
MyClass d = new D("D");

or

MyClass a = new A(); // internally setting "A" "B", "C" etc.
MyClass b = new B();
MyClass c = new C();
MyClass d = new D();

When you can write this:

MyClass a = new MyClass("A");
MyClass b = new MyClass("B");
MyClass c = new MyClass("C");
MyClass d = new MyClass("D");

If I were to change the method signature of the BaseClass constructor, I would have to change all the subclasses.

Well that's why inheritance is the artifact that creates HIGH coupling, which is undesirable in OO systems. It should be avoided and perhaps replaced with composition.

Think if you really really need them as subclass. That's why you see very often interfaces used insted:

 public interface NameAware {
     public String getName();
 }



 class A implements NameAware ...
 class B implements NameAware ...
 class C ... etc. 

Here B and C could have inherited from A which would have created a very HIGH coupling among them, by using interfaces the coupling is reduced, if A decides it will no longer be "NameAware" the other classes won't broke.

Of course, if you want to reuse behavior this won't work.

Package php5 have no installation candidate (Ubuntu 16.04)

If you just want to install PHP no matter what version it is, try PHP7

sudo apt-get install php7.0 php7.0-mcrypt

Which sort algorithm works best on mostly sorted data?

ponder Try Heap. I believe it's the most consistent of the O(n lg n) sorts.

What is the Java equivalent for LINQ?

you can try this library: https://code.google.com/p/qood/

Here are some reasons to use it:

  1. lightweight: only 9 public interface/class to learn.
  2. query like SQL: support group-by, order-by, left join, formula,...etc.
  3. for big data: use File(QFS) instead of Heap Memory.
  4. try to solve Object-relational impedance mismatch.

How to escape regular expression special characters using javascript?

Use the \ character to escape a character that has special meaning inside a regular expression.

To automate it, you could use this:

function escapeRegExp(text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}

Update: There is now a proposal to standardize this method, possibly in ES2016: https://github.com/benjamingr/RegExp.escape

Update: The abovementioned proposal was rejected, so keep implementing this yourself if you need it.

Eclipse Build Path Nesting Errors

Got similar issue. Did following steps, issue resolved:

  1. Remove project in eclipse.
  2. Delete .Project file and . Settings folder.
  3. Import project as existing maven project again to eclipse.

Change Toolbar color in Appcompat 21

You can change the color of the text in the toolbar with these:

<item name="android:textColorPrimary">#FFFFFF</item>
<item name="android:textColor">#FFFFFF</item>

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

REACT NATIVE

If you looking for react native solution, then write this snippet in your affected node_modules gradle build file, e.g. firebase in my case.

android {
    configurations.all {
        resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.0'
    }
}

In a simple to understand explanation, what is Runnable in Java?

Runnable is an interface defined as so:

interface Runnable {
    public void run();
}

To make a class which uses it, just define the class as (public) class MyRunnable implements Runnable {

It can be used without even making a new Thread. It's basically your basic interface with a single method, run, that can be called.

If you make a new Thread with runnable as it's parameter, it will call the run method in a new Thread.

It should also be noted that Threads implement Runnable, and that is called when the new Thread is made (in the new thread). The default implementation just calls whatever Runnable you handed in the constructor, which is why you can just do new Thread(someRunnable) without overriding Thread's run method.

Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

changing name of /bootstrap/cache/config.php to config.php.old doesn't work for me neither clearing cache with the commands artisan

  1. php artisan config:clear
  2. php artisan cache:clear
  3. php artisan config:cache

And for some weird reason I can't change permission for the owner on the directories, so my solution was running my IDE (Visual Studio Code) as admin, and everything works.

My project is in an F:/ path of another disk.

How do I set up Visual Studio Code to compile C++ code?

Out of frustration at the lack of clear documentation, I've created a Mac project on github that should just work (both building and debugging):

vscode-mac-c-example

Note that it requires XCode and the VSCode Microsoft cpptools extension.

I plan to do the same for Windows and linux (unless Microsoft write decent documentation first...).

How to enumerate an enum

When you have a bit enum like this

enum DemoFlags
{
    DemoFlag = 1,
    OtherFlag = 2,
    TestFlag = 4,
    LastFlag = 8,
}

With this assignement

DemoFlags demoFlags = DemoFlags.DemoFlag | DemoFlags.TestFlag;

and need a result like this

"DemoFlag | TestFlag"

this method helps:

public static string ConvertToEnumString<T>(T enumToConvert, string separator = " | ") where T : Enum
{
    StringBuilder convertedEnums = new StringBuilder();

    foreach (T enumValue in Enum.GetValues(typeof(T)))
    {
        if (enumToConvert.HasFlag(enumValue)) convertedEnums.Append($"{ enumValue }{separator}");
    }

    if (convertedEnums.Length > 0) convertedEnums.Length -= separator.Length;

    return convertedEnums.ToString();
}

How to calculate time difference in java?

import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) throws Exception{
    String time1 = "12:00:00";
    String time2 = "12:01:00";
    SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
    Date date1 = format.parse(time1);
    Date date2 = format.parse(time2);
    long difference = date2.getTime() - date1.getTime();
    System.out.println(difference/1000);
}}

throws exception handles parsing exceptions

PowerShell The term is not recognized as cmdlet function script file or operable program

Yet another way this error message can occur...

If PowerShell is open in a directory other than the target file, e.g.:

If someScript.ps1 is located here: C:\SlowLearner\some_missing_path\someScript.ps1, then C:\SlowLearner>. ./someScript.ps1 wont work.

In that case, navigate to the path: cd some_missing_path then this would work:

C:\SlowLearner\some_missing_path>. ./someScript.ps1

Reset all the items in a form

There is a very effective way to use to clear or reset Windows Form C# controls like TextBox, ComboBox, RadioButton, CheckBox, DateTimePicker etc.

private void btnClear_Click(object sender, EventArgs e)
{
    Utilities.ClearAllControls(this);
}

internal class Utilities
{
    internal static void ClearAllControls(Control control)
    {
        foreach (Control c in control.Controls)
        {
            if (c is TextBox)
            {
                ((TextBox)c).Clear();
            }
            else if (c is ComboBox)
            {
                ((ComboBox)c).SelectedIndex = -1;
            }
            else if (c is RadioButton)
            {
                ((RadioButton)c).Checked = false;
            }
            else if (c is CheckBox)
            {
                ((CheckBox)c).Checked = false;
            }
            else if (c is DateTimePicker)
            {
                ((DateTimePicker)c).Value = DateTime.Now; // or null 
            }
        }
    }
}

To accomplish this with overall user experience in c# we can use one statement to clear them. Pretty straight forward so far, above is the code.

How can I mix LaTeX in with Markdown?

Hey, this might not be the most ideal solution, but it works for me. I ended up creating a Python-Markdown LaTeX extension.

https://github.com/justinvh/Markdown-LaTeX

It adds support for inline math and text expressions using a $math$ and %text% syntax. The extension is a preprocessor that will use latex/dvipng to generate pngs for the respective equations/text and then base64 encode the data to inline the images directly, rather than have external images.

The data is then put in a simple-delimited cache file that encodes the expression to the base64 representation. This limits the number of times latex actually has to be run.

Here is an example:

%Hello, world!% This is regular text, but this: $y = mx + b$ is not.

The output:

$ markdown -x latex test.markdown
<p><img class='latex-inline math-false' alt='Hello, world!' id='Helloworld' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFwAAAAQBAMAAABpWwV8AAAAMFBMVEX///8iIiK6urpUVFTu7u6YmJgQEBDc3NxERESqqqqIiIgyMjJ2dnZmZmbMzMwAAAAbX03YAAAAAXRSTlMAQObYZgAAAVpJREFUKM9jYICDOgb2BwzYAVji8AQg8fb/PZ79u4AMvv0Mrz/gUA6W8F7AmcLAsJuBYT7Y1PcMfLiUgyWYF/B8Z2DYAVReABKrZ2DHpZwdopzrA0nKOeHKj66CKOcKPQJWwJo2NVFhfwCQyymhYwCUYD0avIApgYFh2927/QUcE3gDwMpvMhRCDJzNMIPhKZg7UW8DUOIMg9sCPgGo6e8ZODeAlAP9xLEArNy/IIwhAMx9D3IM+3cgi70BqnxZaNQFkHJWAQbeBrByjgURExaAuc9AyjnB5hjAlEO9ygVXzrplpskEMPchQvkBmGMcGApgjjkAVs7yhyWVAcwFK2f/AlJeAI0m5gMsEK+aMhQ6aDuA1DcDIZirBg7IOwxlB5g2QBJBF8OZVUz95hqfC3hOXWGYrwBSHskwk4EByGXab8QAlOBaGizFKYAtUlgUGEgBTCSpZnDCLQUA+y6MXeYnPDgAAAAASUVORK5CYII='> This is regular text, but this: <img class='latex-inline math-true' alt='y = mx + b' id='ymxb' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFIAAAAOBAMAAABOTlYkAAAAMFBMVEX///9ERETu7u4yMjK6urp2dnZUVFSIiIjMzMwQEBDc3NwiIiJmZmaYmJiqqqoAAADS00rKAAAAAXRSTlMAQObYZgAAAOtJREFUKM9jYCAACsCk4wYGgiABTLInEKuS+QGxKvkVGBj47jBwI8tcffI84e45BoZ7GVcLECo9751iWLeSoRPITBQEggMMDBy9sxj2MDgz8DIE8yCpPMxwjWFBGUMMkpFcbAEMvxjKGLgYxIE8NkHBiYIyQMY+hmoGhi0Mdsi2czawbGCQBTJ+ILvzE0MaA9MHIIWwnWE9A+sBpk8LGDgmMCnAVXJNYPgCJHhRQvUiA/cDXoECZx4DXoSZTBtYgaaEPw5AVnkOGBRc5xTcbsReQrL9+nWwyxbgC88DcJZ+QygDcYD1+QPiFAIAtLA8KPZOGFEAAAAASUVORK5CYII='> is not.</p>

As you can see it is a verbose output, but that really isn't an issue since you're already using Markdown :)

cast class into another class or convert class to another

You can provide an explicit overload for the cast operator:

public static explicit operator maincs(sub1 val)
{
    var ret = new maincs() { a = val.a, b = val.b, c = val.c };
    return ret;
}

Another option would be to use an interface that has the a, b, and c properties and implement the interface on both of the classes. Then just have the parameter type to methoda be the interface instead of the class.

Git remote branch deleted, but still it appears in 'branch -a'

git remote prune origin, as suggested in the other answer, will remove all such stale branches. That's probably what you'd want in most cases, but if you want to just remove that particular remote-tracking branch, you should do:

git branch -d -r origin/coolbranch

(The -r is easy to forget...)

-r in this case will "List or delete (if used with -d) the remote-tracking branches." according to the Git documentation found here: https://git-scm.com/docs/git-branch

INSTALL_FAILED_NO_MATCHING_ABIS when install apk

This is indeed a strange error that can be caused by multidexing your app. To get around it, use the following block in your app's build.gradle file:

android {
  splits {
    abi {
        enable true
        reset()
        include 'x86', 'armeabi-v7a'
        universalApk true
    }
  }
  ...[rest of your gradle script]

Android: Scale a Drawable or background image?

You can use one of following:

android:gravity="fill_horizontal|clip_vertical"

Or

android:gravity="fill_vertical|clip_horizontal"

AngularJS error: 'argument 'FirstCtrl' is not a function, got undefined'

Watch your letter casing too. I spent a good hour chasing this bug.

<section id="forgotpwd" ng-controller="ForgotPwdController">

while I name the controller

angular
    .module('app')
    .controller('ForgotpwdController', ForgotpwdController);

They all should be consistently named, in this case ForgotpwdController with lower case p.

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#

MVC, MVP, MVVM

MVC (old one)

MVP (more modular because of its low-coupling. Presenter is a mediator between the View and Model)

MVVM (You already have two-way binding between VM and UI component, so it is more automated than MVP) enter image description here

Another image: enter image description here

Send file using POST from a Python script

You may also want to have a look at httplib2, with examples. I find using httplib2 is more concise than using the built-in HTTP modules.

Conditional WHERE clause in SQL Server

To answer the underlying question of how to use a CASE expression in the WHERE clause:

First remember that the value of a CASE expression has to have a normal data type value, not a boolean value. It has to be a varchar, or an int, or something. It's the same reason you can't say SELECT Name, 76 = Age FROM [...] and expect to get 'Frank', FALSE in the result set.

Additionally, all expressions in a WHERE clause need to have a boolean value. They can't have a value of a varchar or an int. You can't say WHERE Name; or WHERE 'Frank';. You have to use a comparison operator to make it a boolean expression, so WHERE Name = 'Frank';

That means that the CASE expression must be on one side of a boolean expression. You have to compare the CASE expression to something. It can't stand by itself!

Here:

WHERE 
    DateDropped = 0
    AND CASE
            WHEN @JobsOnHold  = 1 AND DateAppr >= 0 THEN 'True'
            WHEN DateAppr != 0 THEN 'True'
            ELSE 'False'
        END = 'True'

Notice how in the end the CASE expression on the left will turn the boolean expression into either 'True' = 'True' or 'False' = 'True'.

Note that there's nothing special about 'False' and 'True'. You can use 0 and 1 if you'd rather, too.

You can typically rewrite the CASE expression into boolean expressions we're more familiar with, and that's generally better for performance. However, sometimes is easier or more maintainable to use an existing expression than it is to convert the logic.

How to capitalize the first letter in a String in Ruby

Well, just so we know how to capitalize only the first letter and leave the rest of them alone, because sometimes that is what is desired:

['NASA', 'MHz', 'sputnik'].collect do |word|
  letters = word.split('')
  letters.first.upcase!
  letters.join
end

 => ["NASA", "MHz", "Sputnik"]

Calling capitalize would result in ["Nasa", "Mhz", "Sputnik"].

How to get current route in react-router 2.0.0-rc5

You could use the 'isActive' prop like so:

const { router } = this.context;
if (router.isActive('/login')) {
    router.push('/');
}

isActive will return a true or false.

Tested with react-router 2.7

jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined

There is no need to make a query string. Just put your values in an object and jQuery will take care of the rest for you.

var data = {
    name: $("#form_name").val(),
    email: $("#form_email").val(),
    message: $("#msg_text").val()
};
$.ajax({
    type: "POST",
    url: "email.php",
    data: data,
    success: function(){
        $('.success').fadeIn(1000);
    }
});

SELECT DISTINCT on one column

Try this:

SELECT * FROM [TestData] WHERE Id IN(SELECT DISTINCT MIN(Id) FROM [TestData] GROUP BY Product)   

How to re import an updated package while in Python Interpreter?

dragonfly's answer worked for me (python 3.4.3).

import sys
del sys.modules['module_name']

Here is a lower level solution :

exec(open("MyClass.py").read(), globals())

Android: How to programmatically access the device serial number shown in the AVD manager (API Version 8)

Build.SERIAL can be empty or sometimes return a different value (proof 1, proof 2) than what you can see in your device's settings.

If you want a more complete and robust solution, I've compiled every possible solution I could found in a single gist. Here's a simplified version of it :

public static String getSerialNumber() {
    String serialNumber;

    try {
        Class<?> c = Class.forName("android.os.SystemProperties");
        Method get = c.getMethod("get", String.class);

        serialNumber = (String) get.invoke(c, "gsm.sn1");
        if (serialNumber.equals(""))
            serialNumber = (String) get.invoke(c, "ril.serialnumber");
        if (serialNumber.equals(""))
            serialNumber = (String) get.invoke(c, "ro.serialno");
        if (serialNumber.equals(""))
            serialNumber = (String) get.invoke(c, "sys.serialnumber");
        if (serialNumber.equals(""))
            serialNumber = Build.SERIAL;

        // If none of the methods above worked
        if (serialNumber.equals(""))
            serialNumber = null;
    } catch (Exception e) {
        e.printStackTrace();
        serialNumber = null;
    }

    return serialNumber;
}

I try to update the gist regularly whenever I can test on a new device or Android version. Contributions are welcome too.

Diff files present in two different directories

Try this:

diff -rq /path/to/folder1 /path/to/folder2      

How to sort by two fields in Java?

Using the Java 8 Streams approach...

//Creates and sorts a stream (does not sort the original list)       
persons.stream().sorted(Comparator.comparing(Person::getName).thenComparing(Person::getAge));

And the Java 8 Lambda approach...

//Sorts the original list Lambda style
persons.sort((p1, p2) -> {
        if (p1.getName().compareTo(p2.getName()) == 0) {
            return p1.getAge().compareTo(p2.getAge());
        } else {
            return p1.getName().compareTo(p2.getName());
        } 
    });

Lastly...

//This is similar SYNTAX to the Streams above, but it sorts the original list!!
persons.sort(Comparator.comparing(Person::getName).thenComparing(Person::getAge));

How to compare two JSON have the same properties without order?

DeepCompare method to compare two json objects..

_x000D_
_x000D_
deepCompare = (arg1, arg2) => {_x000D_
  if (Object.prototype.toString.call(arg1) === Object.prototype.toString.call(arg2)){_x000D_
    if (Object.prototype.toString.call(arg1) === '[object Object]' || Object.prototype.toString.call(arg1) === '[object Array]' ){_x000D_
      if (Object.keys(arg1).length !== Object.keys(arg2).length ){_x000D_
        return false;_x000D_
      }_x000D_
      return (Object.keys(arg1).every(function(key){_x000D_
        return deepCompare(arg1[key],arg2[key]);_x000D_
      }));_x000D_
    }_x000D_
    return (arg1===arg2);_x000D_
  }_x000D_
  return false;_x000D_
}_x000D_
_x000D_
console.log(deepCompare({a:1},{a:'1'})) // false_x000D_
console.log(deepCompare({a:1},{a:1}))   // true
_x000D_
_x000D_
_x000D_

Is there a library function for Root mean square error (RMSE) in python?

Just in case someone finds this thread in 2019, there is a library called ml_metrics which is available without pre-installation in Kaggle's kernels, pretty lightweighted and accessible through pypi ( it can be installed easily and fast with pip install ml_metrics):

from ml_metrics import rmse
rmse(actual=[0, 1, 2], predicted=[1, 10, 5])
# 5.507570547286102

It has few other interesting metrics which are not available in sklearn, like mapk.

References:

How can I programmatically generate keypress events in C#?

To produce key events without Windows Forms Context, We can use the following method,

[DllImport("user32.dll")]
public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);

sample code is given below:

const int VK_UP = 0x26; //up key
const int VK_DOWN = 0x28;  //down key
const int VK_LEFT = 0x25;
const int VK_RIGHT = 0x27;
const uint KEYEVENTF_KEYUP = 0x0002;
const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
int press()
{
    //Press the key
    keybd_event((byte)VK_UP, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
    return 0;
}

List of Virtual Keys are defined here.

To get the complete picture, please use the below link, http://tksinghal.blogspot.in/2011/04/how-to-press-and-hold-keyboard-key.html

Angular 2 Routing run in new tab

Late to this one, but I just discovered an alternative way of doing it:

On your template,

<a (click)="navigateAssociates()">Associates</a> 

And on your component.ts, you can use serializeUrl to convert the route into a string, which can be used with window.open()

navigateAssociates() {
  const url = this.router.serializeUrl(
    this.router.createUrlTree(['/page1'])
  );

  window.open(url, '_blank');
}

Angular 4 - get input value

<form (submit)="onSubmit()">
   <input [(ngModel)]="playerName">
</form>

let playerName: string;
onSubmit() {
  return this.playerName;
}

How do I make a semi transparent background?

This is simple and sort. Use hsla css function like below

.transparent {
   background-color: hsla(0,0%,4%,.4);
}

Export a list into a CSV or TXT file in R

You can simply wrap your list as a data.frame (data.frame is in fact a special kind of list). Here is an example:

mylist = list() 
mylist[["a"]] = 1:10 
mylist[["b"]] = letters[1:10]
write.table(as.data.frame(mylist),file="mylist.csv", quote=F,sep=",",row.names=F)

or alternatively you can use write.csv (a wrapper around write.table). For the conversion of the list , you can use both as.data.frame(mylist) and data.frame(mylist).

To help in making a reproducible example, you can use functions like dput on your data.

How can I convert a hex string to a byte array?

I think this may work.

public static byte[] StrToByteArray(string str)
    {
        Dictionary<string, byte> hexindex = new Dictionary<string, byte>();
        for (int i = 0; i <= 255; i++)
            hexindex.Add(i.ToString("X2"), (byte)i);

        List<byte> hexres = new List<byte>();
        for (int i = 0; i < str.Length; i += 2)            
            hexres.Add(hexindex[str.Substring(i, 2)]);

        return hexres.ToArray();
    }

LINQ Contains Case Insensitive

fi => fi.DESCRIPTION.ToLower().Contains(description.ToLower())

How to remove all leading zeroes in a string

Regex was proposed already, but not correctly:

<?php
    $number = '00000004523423400023402340240';
    $withoutLeadingZeroes = preg_replace('/^0+/', '', $number)
    echo $withoutLeadingZeroes;
?>

output is then:

4523423400023402340240

Background on Regex: the ^ signals beginning of string and the + sign signals more or none of the preceding sign. Therefore, the regex ^0+ matches all zeroes at the beginning of a string.

Using PropertyInfo.GetValue()

In your example propertyInfo.GetValue(this, null) should work. Consider altering GetNamesAndTypesAndValues() as follows:

public void GetNamesAndTypesAndValues()
{
  foreach (PropertyInfo propertyInfo in allClassProperties)
  {
    Console.WriteLine("{0} [type = {1}] [value = {2}]",
      propertyInfo.Name,
      propertyInfo.PropertyType,
      propertyInfo.GetValue(this, null));
  }
}

What to put in a python module docstring?

To quote the specifications:

The docstring of a script (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a docstring should document the script's function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.

The docstring for a module should generally list the classes, exceptions and functions (and any other objects) that are exported by the module, with a one-line summary of each. (These summaries generally give less detail than the summary line in the object's docstring.) The docstring for a package (i.e., the docstring of the package's __init__.py module) should also list the modules and subpackages exported by the package.

The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its __init__ method. Individual methods should be documented by their own docstring.

The docstring of a function or method is a phrase ending in a period. It prescribes the function or method's effect as a command ("Do this", "Return that"), not as a description; e.g. don't write "Returns the pathname ...". A multiline-docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.

How to set table name in dynamic SQL query?

Building on a previous answer by @user1172173 that addressed SQL Injection vulnerabilities, see below:

CREATE PROCEDURE [dbo].[spQ_SomeColumnByCustomerId](
@CustomerId int,
@SchemaName varchar(20),
@TableName nvarchar(200)) AS
SET Nocount ON
DECLARE @SQLQuery AS NVARCHAR(500)
DECLARE @ParameterDefinition AS NVARCHAR(100)
DECLARE @Table_ObjectId int;
DECLARE @Schema_ObjectId int;
DECLARE @Schema_Table_SecuredFromSqlInjection NVARCHAR(125)

SET @Table_ObjectId = OBJECT_ID(@TableName)
SET @Schema_ObjectId = SCHEMA_ID(@SchemaName)
SET @Schema_Table_SecuredFromSqlInjection = SCHEMA_NAME(@Schema_ObjectId) + '.' + OBJECT_NAME(@Table_ObjectId)

SET @SQLQuery = N'SELECT TOP 1 ' + @Schema_Table_SecuredFromSqlInjection + '.SomeColumn 
FROM dbo.Customer 
INNER JOIN ' + @Schema_Table_SecuredFromSqlInjection + ' 
ON dbo.Customer.Customerid = ' + @Schema_Table_SecuredFromSqlInjection + '.CustomerId 
WHERE dbo.Customer.CustomerID = @CustomerIdParam 
ORDER BY ' + @Schema_Table_SecuredFromSqlInjection + '.SomeColumn DESC' 
SET @ParameterDefinition =  N'@CustomerIdParam INT'

EXECUTE sp_executesql @SQLQuery, @ParameterDefinition, @CustomerIdParam = @CustomerId; RETURN

How to count total lines changed by a specific author in a Git repository?

@mmrobins @AaronM @ErikZ @JamesMishra provided variants that all have an problem in common: they ask git to produce a mixture of info not intended for script consumption, including line contents from repository on the same line, then match the mess with a regexp.

This is a problem when some lines aren't valid UTF-8 text, and also when some lines happen to match the regexp (this happened here).

Here's a modified line that doesn't have these problems. It requests git to output data cleanly on separate lines, which makes it easy to filter what we want robustly:

git ls-files -z | xargs -0n1 git blame -w --line-porcelain | grep -a "^author " | sort -f | uniq -c | sort -n

You can grep for other strings, like author-mail, committer, etc.

Perhaps first do export LC_ALL=C (assuming bash) to force byte-level processing (this also happens to speed up grep tremendously from the UTF-8-based locales).

How to connect to SQL Server from another computer?

all of above answers would help you but you have to add three ports in the firewall of PC on which SQL Server is installed.

  1. Add new TCP Local port in Windows firewall at port no. 1434

  2. Add new program for SQL Server and select sql server.exe Path: C:\ProgramFiles\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Binn\sqlservr.exe

  3. Add new program for SQL Browser and select sqlbrowser.exe Path: C:\ProgramFiles\Microsoft SQL Server\90\Shared\sqlbrowser.exe

Do I need <class> elements in persistence.xml?

You can provide for jar-file element path to a folder with compiled classes. For example I added something like that when I prepared persistence.xml to some integration tests:

 <jar-file>file:../target/classes</jar-file>

Rendering raw html with reactjs

There are now safer methods to render HTML. I covered this in a previous answer here. You have 4 options, the last uses dangerouslySetInnerHTML.

Methods for rendering HTML

  1. Easiest - Use Unicode, save the file as UTF-8 and set the charset to UTF-8.

    <div>{'First · Second'}</div>

  2. Safer - Use the Unicode number for the entity inside a Javascript string.

    <div>{'First \u00b7 Second'}</div>

    or

    <div>{'First ' + String.fromCharCode(183) + ' Second'}</div>

  3. Or a mixed array with strings and JSX elements.

    <div>{['First ', <span>&middot;</span>, ' Second']}</div>

  4. Last Resort - Insert raw HTML using dangerouslySetInnerHTML.

    <div dangerouslySetInnerHTML={{__html: 'First &middot; Second'}} />

Better techniques for trimming leading zeros in SQL Server?

cast(value as int) will always work if string is a number

What does git rev-parse do?

git rev-parse Also works for getting the current branch name using the --abbrev-ref flag like:

git rev-parse --abbrev-ref HEAD

Ruby on Rails: how to render a string as HTML?

You are mixing your business logic with your content. Instead, I'd recommend sending the data to your page and then using something like JQuery to place the data where you need it to go.

This has the advantage of keeping all your HTML in the HTML pages where it belongs so your web designers can modify the HTML later without having to pour through server side code.

Or if you're not wanting to use JavaScript, you could try this:

@str = "Hi"

<b><%= @str ></b>

At least this way your HTML is in the HTML page where it belongs.

Can I have multiple primary keys in a single table?

Yes, Its possible in SQL, but we can't set more than one primary keys in MsAccess. Then, I don't know about the other databases.

CREATE TABLE CHAPTER (
    BOOK_ISBN VARCHAR(50) NOT NULL,
    IDX INT NOT NULL,
    TITLE VARCHAR(100) NOT NULL,
    NUM_OF_PAGES INT,
    PRIMARY KEY (BOOK_ISBN, IDX)
);

How to change collation of database, table, column?

I read it here, that you need to convert each table manually, it is not true. Here is a solution how to do it with a stored procedure:

DELIMITER $$

DROP PROCEDURE IF EXISTS changeCollation$$

-- character_set parameter could be 'utf8'
-- or 'latin1' or any other valid character set
CREATE PROCEDURE changeCollation(IN character_set VARCHAR(255))
BEGIN
DECLARE v_finished INTEGER DEFAULT 0;
DECLARE v_table_name varchar(255) DEFAULT "";
DECLARE v_message varchar(4000) DEFAULT "No records";

-- This will create a cursor that selects each table,
-- where the character set is not the one
-- that is defined in the parameter

DECLARE alter_cursor CURSOR FOR SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE()
AND COLLATION_NAME NOT LIKE CONCAT(character_set, '_%');

-- This handler will set the value v_finished to 1
-- if there are no more rows

DECLARE CONTINUE HANDLER
FOR NOT FOUND SET v_finished = 1;

OPEN alter_cursor;

-- Start a loop to fetch each rows from the cursor
get_table: LOOP

-- Fetch the table names one by one
FETCH alter_cursor INTO v_table_name;

-- If there is no more record, then we have to skip
-- the commands inside the loop
IF v_finished = 1 THEN
LEAVE get_table;
END IF;

IF v_table_name != '' THEN

IF v_message = 'No records' THEN
SET v_message = '';
END IF;

-- This technic makes the trick, it prepares a statement
-- that is based on the v_table_name parameter and it means
-- that this one is different by each iteration inside the loop

SET @s = CONCAT('ALTER TABLE ',v_table_name,
' CONVERT TO CHARACTER SET ', character_set);
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET v_message = CONCAT('The table ', v_table_name ,
' was changed to the default collation of ', character_set,
'.\n', v_message);

SET v_table_name = '';

END IF;
-- Close the loop and the cursor
END LOOP get_table;
CLOSE alter_cursor;

-- Returns information about the altered tables or 'No records'
SELECT v_message;

END $$

DELIMITER ;

After the procedure is created call it simply:

CALL changeCollation('utf8');

For more details read this blog.

html vertical align the text inside input type button

You can use flexbox (check browser support, depending on your needs).

.testbutton {
  display: inline-flex;
  align-items: center; 
}

Pandas dataframe fillna() only some columns in place

Or something like:

df.loc[df['a'].isnull(),'a']=0
df.loc[df['b'].isnull(),'b']=0

and if there is more:

for i in your_list:
    df.loc[df[i].isnull(),i]=0

How does the "final" keyword in Java work? (I can still modify an object.)

  1. Since the final variable is non-static, it can be initialized in constructor. But if you make it static it can not be initialized by constructor (because constructors are not static).
  2. Addition to list is not expected to stop by making list final. final just binds the reference to particular object. You are free to change the 'state' of that object, but not the object itself.

How to add data into ManyToMany field?

In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj) in your ModelForm.save override, as ModelForm.save later populates your m2m from self.cleaned_data['my_m2m'] which overwrites your changes. Instead call:

my_m2ms = list(self.cleaned_data['my_m2ms'])
my_m2ms.extend(my_custom_new_m2ms)
self.cleaned_data['my_m2ms'] = my_m2ms

(It is fine to convert the incoming QuerySet to a list - the ManyToManyField does that anyway.)

How to make EditText not editable through XML in Android?

Try

.setInputType(InputType.TYPE_NULL);

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

In my case my problem was that I was using an older version of NetBeans. The Maven repository removed an http reference, but the embedded Maven in Netbeans had that http reference hard-coded. I was really confused at first because my pom.xml referenced the proper https://repo.maven.apache.org/maven2.

Fixing it was pretty simple. I downloaded the latest zip archive of Maven from the following location and extracted it to my machine: https://maven.apache.org/download.cgi

Within Netbeans at Tools -> Options -> Java -> Maven on the "Execution" section I set "Maven Home" to the newly extracted zip file location.

Now I could build my project....

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

How to add a touch event to a UIView?

Objective-C:

UIControl *headerView = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, nextY)];
[headerView addTarget:self action:@selector(myEvent:) forControlEvents:UIControlEventTouchDown];

Swift:

let headerView = UIControl(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: nextY))
headerView.addTarget(self, action: #selector(myEvent(_:)), for: .touchDown)

The question asks:

How do I add a touch event to a UIView?

It isn't asking for a tap event.

Specifically OP wants to implement UIControlEventTouchDown

Switching the UIView to UIControl is the right answer here because Gesture Recognisers don't know anything about .touchDown, .touchUpInside, .touchUpOutside etc.

Additionally, UIControl inherits from UIView so you're not losing any functionality.

If all you want is a tap, then you can use the Gesture Recogniser. But if you want finer control, like this question asks for, you'll need UIControl.

https://developer.apple.com/documentation/uikit/uicontrol?language=objc https://developer.apple.com/documentation/uikit/uigesturerecognizer?language=objc

Read text file into string array (and write)

Cannot update first answer.
Anyway, after Go1 release, there are some breaking changes, so I updated as shown below:

package main

import (
    "os"
    "bufio"
    "bytes"
    "io"
    "fmt"
    "strings"
)

// Read a whole file into the memory and store it as array of lines
func readLines(path string) (lines []string, err error) {
    var (
        file *os.File
        part []byte
        prefix bool
    )
    if file, err = os.Open(path); err != nil {
        return
    }
    defer file.Close()

    reader := bufio.NewReader(file)
    buffer := bytes.NewBuffer(make([]byte, 0))
    for {
        if part, prefix, err = reader.ReadLine(); err != nil {
            break
        }
        buffer.Write(part)
        if !prefix {
            lines = append(lines, buffer.String())
            buffer.Reset()
        }
    }
    if err == io.EOF {
        err = nil
    }
    return
}

func writeLines(lines []string, path string) (err error) {
    var (
        file *os.File
    )

    if file, err = os.Create(path); err != nil {
        return
    }
    defer file.Close()

    //writer := bufio.NewWriter(file)
    for _,item := range lines {
        //fmt.Println(item)
        _, err := file.WriteString(strings.TrimSpace(item) + "\n"); 
        //file.Write([]byte(item)); 
        if err != nil {
            //fmt.Println("debug")
            fmt.Println(err)
            break
        }
    }
    /*content := strings.Join(lines, "\n")
    _, err = writer.WriteString(content)*/
    return
}

func main() {
    lines, err := readLines("foo.txt")
    if err != nil {
        fmt.Println("Error: %s\n", err)
        return
    }
    for _, line := range lines {
        fmt.Println(line)
    }
    //array := []string{"7.0", "8.5", "9.1"}
    err = writeLines(lines, "foo2.txt")
    fmt.Println(err)
}

How can I trigger the click event of another element in ng-click using angularjs?

I just came across this problem and have written a solution for those of you who are using Angular. You can write a custom directive composed of a container, a button, and an input element with type file. With CSS you then place the input over the custom button but with opacity 0. You set the containers height and width to exactly the offset width and height of the button and the input's height and width to 100% of the container.

the directive

angular.module('myCoolApp')
  .directive('fileButton', function () {
    return {
      templateUrl: 'components/directives/fileButton/fileButton.html',
      restrict: 'E',
      link: function (scope, element, attributes) {

        var container = angular.element('.file-upload-container');
        var button = angular.element('.file-upload-button');

        container.css({
            position: 'relative',
            overflow: 'hidden',
            width: button.offsetWidth,
            height: button.offsetHeight
        })

      }

    };
  });

a jade template if you are using jade

div(class="file-upload-container") 
    button(class="file-upload-button") +
    input#file-upload(class="file-upload-input", type='file', onchange="doSomethingWhenFileIsSelected()")  

the same template in html if you are using html

<div class="file-upload-container">
   <button class="file-upload-button"></button>
   <input class="file-upload-input" id="file-upload" type="file" onchange="doSomethingWhenFileIsSelected()" /> 
</div>

the css

.file-upload-button {
    margin-top: 40px;
    padding: 30px;
    border: 1px solid black;
    height: 100px;
    width: 100px;
    background: transparent;
    font-size: 66px;
    padding-top: 0px;
    border-radius: 5px;
    border: 2px solid rgb(255, 228, 0); 
    color: rgb(255, 228, 0);
}
.file-upload-input {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
}

Get Absolute Position of element within the window in wpf

I think what BrandonS wants is not the position of the mouse relative to the root element, but rather the position of some descendant element.

For that, there is the TransformToAncestor method:

Point relativePoint = myVisual.TransformToAncestor(rootVisual)
                              .Transform(new Point(0, 0));

Where myVisual is the element that was just double-clicked, and rootVisual is Application.Current.MainWindow or whatever you want the position relative to.

crop text too long inside div

You can use:

overflow:hidden;

to hide the text outside the zone.

Note that it may cut the last letter (so a part of the last letter will still be displayed). A nicer way is to display an ellipsis at the end. You can do it by using text-overflow:

overflow: hidden;
white-space: nowrap; /* Don't forget this one */
text-overflow: ellipsis;

Route [login] not defined

If someone getting this from a rest client (ex. Postman) - You need to set the Header to Accept application/json.

To do this on postman, click on the Headers tab, and add a new key 'Accept' and type the value 'application/json'.

How to style a JSON block in Github Wiki?

I encountered the same problem. So, I tried representing the JSON in different Language syntax formats.But all time favorites are Perl, js, python, & elixir.

This is how it looks.

The following screenshots are from the Gitlab in a markdown file. This may vary based on the colors using for syntax in MARKDOWN files.

JsonasPerl

JsonasPython

JsonasJs

JsonasElixir

Clear git local cache

When you think your git is messed up, you can use this command to do everything up-to-date.

git rm -r --cached .
git add .
git commit -am 'git cache cleared'
git push

Also to revert back last commit use this :

git reset HEAD^ --hard