Programs & Examples On #Part of speech

Linguistic category of words

Method call if not null in C#

Events can be initialized with an empty default delegate which is never removed:

public event EventHandler MyEvent = delegate { };

No null-checking necessary.

[Update, thanks to Bevan for pointing this out]

Be aware of the possible performance impact, though. A quick micro benchmark I did indicates that handling an event with no subscribers is 2-3 times slower when using the the "default delegate" pattern. (On my dual core 2.5GHz laptop that means 279ms : 785ms for raising 50 million not-subscribed events.). For application hot spots, that might be an issue to consider.

git push to specific branch

If your Local branch and remote branch is the same name then you can just do it:

git push origin branchName

When your local and remote branch name is different then you can just do it:

git push origin localBranchName:remoteBranchName

How do I apply a perspective transform to a UIView?

You can only use Core Graphics (Quartz, 2D only) transforms directly applied to a UIView's transform property. To get the effects in coverflow, you'll have to use CATransform3D, which are applied in 3-D space, and so can give you the perspective view you want. You can only apply CATransform3Ds to layers, not views, so you're going to have to switch to layers for this.

Check out the "CovertFlow" sample that comes with Xcode. It's mac-only (ie not for iPhone), but a lot of the concepts transfer well.

SQL Server format decimal places with commas

without considering this to be a good idea...

select dbo.F_AddThousandSeparators(convert(varchar, convert(decimal(18, 4), 1234.1234567), 1))

Function

-- Author:      bummi
-- Create date: 20121106
CREATE FUNCTION F_AddThousandSeparators(@NumStr varchar(50)) 
RETURNS Varchar(50)
AS
BEGIN
declare @OutStr varchar(50)
declare @i int
declare @run int

Select @i=CHARINDEX('.',@NumStr)
if @i=0 
    begin
    set @i=LEN(@NumStr)
    Set @Outstr=''
    end
else
    begin   
     Set @Outstr=SUBSTRING(@NUmStr,@i,50)
     Set @i=@i -1
    end 


Set @run=0

While @i>0
    begin
      if @Run=3
        begin
          Set @Outstr=','+@Outstr
          Set @run=0
        end
      Set @Outstr=SUBSTRING(@NumStr,@i,1) +@Outstr  
      Set @i=@i-1
      Set @run=@run + 1     
    end

    RETURN @OutStr

END
GO

Getting value of HTML text input

If your page is refreshed on submitting - yes, but only through the querystring: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx (You must use method "GET" then). Else, you can return its value from the php script.

Stacked Bar Plot in R

A somewhat different approach using ggplot2:

dat <- read.table(text = "A   B   C   D   E   F    G
1 480 780 431 295 670 360  190
2 720 350 377 255 340 615  345
3 460 480 179 560  60 735 1260
4 220 240 876 789 820 100   75", header = TRUE)

library(reshape2)

dat$row <- seq_len(nrow(dat))
dat2 <- melt(dat, id.vars = "row")

library(ggplot2)

ggplot(dat2, aes(x = variable, y = value, fill = row)) + 
  geom_bar(stat = "identity") +
  xlab("\nType") +
  ylab("Time\n") +
  guides(fill = FALSE) +
  theme_bw()

this gives:

enter image description here

When you want to include a legend, delete the guides(fill = FALSE) line.

Javascript array sort and unique

This might be adequate in circumstances where you can't define the function in advance (like in a bookmarklet):

myData.sort().filter(function(el,i,a){return i===a.indexOf(el)})

Get width/height of SVG element

FireFox have problemes for getBBox(), i need to do this in vanillaJS.

I've a better Way and is the same result as real svg.getBBox() function !

With this good post : Get the real size of a SVG/G element

var el   = document.getElementById("yourElement"); // or other selector like querySelector()
var rect = el.getBoundingClientRect(); // get the bounding rectangle

console.log( rect.width );
console.log( rect.height);

Can you recommend a free light-weight MySQL GUI for Linux?

Why not try MySQL GUI Tools? It's light, and does its job well.

How do I remove all non alphanumeric characters from a string except dash?

Here is a non-regex heap allocation friendly fast solution which was what I was looking for.

Unsafe edition.

public static unsafe void ToAlphaNumeric(ref string input)
{
    fixed (char* p = input)
    {
        int offset = 0;
        for (int i = 0; i < input.Length; i++)
        {
            if (char.IsLetterOrDigit(p[i]))
            {
                p[offset] = input[i];
                offset++;
            }
        }
        ((int*)p)[-1] = offset; // Changes the length of the string
        p[offset] = '\0';
    }
}

And for those who don't want to use unsafe or don't trust the string length hack.

public static string ToAlphaNumeric(string input)
{
    int j = 0;
    char[] newCharArr = new char[input.Length];

    for (int i = 0; i < input.Length; i++)
    {
        if (char.IsLetterOrDigit(input[i]))
        {
            newCharArr[j] = input[i];
            j++;
        }
    }

    Array.Resize(ref newCharArr, j);

    return new string(newCharArr);
}

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

This answer seems relevant since the OP makes reference to a need for a multi-OS solution. This Github help article details available approaches for handling lines endings cross-OS. There are global and per-repo approaches to managing cross-os line endings.

Global approach

Configure Git line endings handling on Linux or OS X:

git config --global core.autocrlf input

Configure Git line endings handling on Windows:

git config --global core.autocrlf true

Per-repo approach:

In the root of your repo, create a .gitattributes file and define line ending settings for your project files, one line at a time in the following format: path_regex line-ending-settings where line-ending-settings is one of the following:

  • text
  • binary (files that Git should not modify line endings for - as this can cause some image types such as PNGs not to render in a browser)

The text value can be configured further to instruct Git on how to handle line endings for matching files:

  • text - Changes line endings to OS native line endings.
  • text eol=crlf - Converts line endings to CRLF on checkout.
  • text eol=lf - Converts line endings to LF on checkout.
  • text=auto - Sensible default that leaves line handle up to Git's discretion.

Here is the content of a sample .gitattributes file:

# Set the default behavior for all files.
* text=auto

# Normalized and converts to 
# native line endings on checkout.
*.c text
*.h text

# Convert to CRLF line endings on checkout.
*.sln text eol=crlf

# Convert to LF line endings on checkout.
*.sh text eol=lf

# Binary files.
*.png binary
*.jpg binary

More on how to refresh your repo after changing line endings settings here. Tldr:

backup your files with Git, delete every file in your repository (except the .git directory), and then restore the files all at once. Save your current files in Git, so that none of your work is lost.

git add . -u

git commit -m "Saving files before refreshing line endings"

Remove the index and force Git to rescan the working directory.

rm .git/index

Rewrite the Git index to pick up all the new line endings.

git reset

Show the rewritten, normalized files.

In some cases, this is all that needs to be done. Others may need to complete the following additional steps:

git status

Add all your changed files back, and prepare them for a commit. This is your chance to inspect which files, if any, were unchanged.

git add -u

It is perfectly safe to see a lot of messages here that read[s] "warning: CRLF will be replaced by LF in file."

Rewrite the .gitattributes file.

git add .gitattributes

Commit the changes to your repository.

git commit -m "Normalize all the line endings"

Rails.env vs RAILS_ENV

ENV['RAILS_ENV'] is now deprecated.

You should use Rails.env which is clearly much nicer.

Can I loop through a table variable in T-SQL?

look like this demo:

DECLARE @vTable TABLE (IdRow int not null primary key identity(1,1),ValueRow int);

-------Initialize---------
insert into @vTable select 345;
insert into @vTable select 795;
insert into @vTable select 565;
---------------------------

DECLARE @cnt int = 1;
DECLARE @max int = (SELECT MAX(IdRow) FROM @vTable);

WHILE @cnt <= @max
BEGIN
    DECLARE @tempValueRow int = (Select ValueRow FROM @vTable WHERE IdRow = @cnt);

    ---work demo----
    print '@tempValueRow:' + convert(varchar(10),@tempValueRow);
    print '@cnt:' + convert(varchar(10),@cnt);
    print'';
    --------------

    set @cnt = @cnt+1;
END

Version without idRow, using ROW_NUMBER

    DECLARE @vTable TABLE (ValueRow int);
-------Initialize---------
insert into @vTable select 345;
insert into @vTable select 795;
insert into @vTable select 565;
---------------------------

DECLARE @cnt int = 1;
DECLARE @max int = (select count(*) from @vTable);

WHILE @cnt <= @max
BEGIN
    DECLARE @tempValueRow int = (
        select ValueRow 
        from (select ValueRow
            , ROW_NUMBER() OVER(ORDER BY (select 1)) as RowId 
            from @vTable
        ) T1 
    where t1.RowId = @cnt
    );

    ---work demo----
    print '@tempValueRow:' + convert(varchar(10),@tempValueRow);
    print '@cnt:' + convert(varchar(10),@cnt);
    print'';
    --------------

    set @cnt = @cnt+1;
END

Uppercase first letter of variable

http://phpjs.org/functions/ucwords:569 has a good example

function ucwords (str) {
    return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
        return $1.toUpperCase();
    });
}

(omitted function comment from source for brevity. please see linked source for details)

EDIT: Please note that this function uppercases the first letter of each word (as your question asks) and not just the first letter of a string (as your question title asks)

LINQ equivalent of foreach for IEnumerable<T>

MoreLinq has IEnumerable<T>.ForEach and a ton of other useful extensions. It's probably not worth taking the dependency just for ForEach, but there's a lot of useful stuff in there.

https://www.nuget.org/packages/morelinq/

https://github.com/morelinq/MoreLINQ

Image library for Python 3

The "friendly PIL fork" Pillow works on Python 2 and 3. Check out the Github project for support matrix and so on.

How to easily import multiple sql files into a MySQL database?

  1. Goto cmd

  2. Type in command prompt C:\users\Usersname>cd [.sql tables folder path ]
    Press Enter
    Ex: C:\users\Usersname>cd E:\project\database

  3. Type command prompt
    C:\users\Usersname>[.sql folder's drive (directory)name]
    Press Enter
    Ex: C:\users\Usersname>E:

  4. Type command prompt for marge all .sql file(table) in a single file
    copy /b *.sql newdatabase.sql
    Press Enter
    EX: E:\project\database>copy /b *.sql newdatabase.sql

  5. You can see Merge Multiple .sql(file) tables Files Into A Single File in your directory folder
    Ex: E:\project\database

What's sizeof(size_t) on 32-bit vs the various 64-bit data models?

size_t is 64 bit normally on 64 bit machine

difference between primary key and unique key

Difference between Primary Key and Unique Key

+-----------------------------------------+-----------------------------------------------+
|                Primary Key              |                    Unique Key                 |
+-----------------------------------------+-----------------------------------------------+
| Primary Key can't accept null values.   | Unique key can accept only one null value.    |
+-----------------------------------------+-----------------------------------------------+
| By default, Primary key is clustered    | By default, Unique key is a unique            |
| index and data in the database table is | non-clustered index.                          |
| physically organized in the sequence of |                                               |
| clustered index.                        |                                               |
+-----------------------------------------+-----------------------------------------------+
| We can have only one Primary key in a   | We can have more than one unique key in a     |
| table.                                  | table.                                        |
+-----------------------------------------+-----------------------------------------------+
| Primary key can be made foreign key     | In SQL Server, Unique key can be made foreign |
| into another table.                     | key into another table.                       |
+-----------------------------------------+-----------------------------------------------+

You can find detailed information from:
http://www.dotnet-tricks.com/Tutorial/sqlserver/V2bS260912-Difference-between-Primary-Key-and-Unique-Key.html

How to get the hours difference between two date objects?

Use the timestamp you get by calling valueOf on the date object:

var diff = date2.valueOf() - date1.valueOf();
var diffInHours = diff/1000/60/60; // Convert milliseconds to hours

How to declare a local variable in Razor?

Not a direct answer to OP's problem, but it may help you too. You can declare a local variable next to some html inside a scope without trouble.

@foreach (var item in Model.Stuff)
{
    var file = item.MoreStuff.FirstOrDefault();

    <li><a href="@item.Source">@file.Name</a></li>
}

Reading an Excel file in python using pandas

Loading an excel file without explicitly naming a sheet but instead giving the number of the sheet order (often one will simply load the first sheet) goes like:

import pandas as pd
myexcel = pd.ExcelFile("C:/filename.xlsx")
myexcel = myexcel.parse(myexcel.sheet_names[0])

Since .sheet_names returns a list of sheet names, it is easy to load one or more sheets by simply calling the list element(s).

How to make `setInterval` behave more in sync, or how to use `setTimeout` instead?

According to your requirement

just show me a basic example of using setTimeout to loop something

we have following example which can help you

_x000D_
_x000D_
var itr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];_x000D_
var  interval = 1000; //one second_x000D_
itr.forEach((itr, index) => {_x000D_
_x000D_
  setTimeout(() => {_x000D_
    console.log(itr)_x000D_
  }, index * interval)_x000D_
})
_x000D_
_x000D_
_x000D_

How to get a string between two characters?

The least generic way I found to do this with Regex and Pattern / Matcher classes:

String text = "test string (67)";

String START = "\\(";  // A literal "(" character in regex
String END   = "\\)";  // A literal ")" character in regex

// Captures the word(s) between the above two character(s)
String pattern = START + "(\w+)" + END;

Pattern pattern = Pattern.compile(pattern);
Matcher matcher = pattern.matcher(text);

while(matcher.find()) {
    System.out.println(matcher.group()
        .replace(START, "").replace(END, ""));
}

This may help for more complex regex problems where you want to get the text between two set of characters.

FlutterError: Unable to load asset

While I was loading a new image in my asset folder, I just encountered the problem every time.

I run flutter clean & then restarted the Android Studio. Seems like flutter packages caches the asset folder and there is no mechanism to update the cache when a developer adds a new image in the project (Personal thoughts).

Create pandas Dataframe by appending one row at a time

pandas.DataFrame.append

DataFrame.append(self, other, ignore_index=False, verify_integrity=False, sort=False) ? 'DataFrame'

df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))
df.append(df2)

With ignore_index set to True:

df.append(df2, ignore_index=True)

How can I permanently enable line numbers in IntelliJ?

Android Studio 1.3.2 and on, IntelliJ 15 and on

Global configuration

File -> Settings -> Editor -> General -> Appearance -> Show line numbers

enter image description here


Current editor configuration

First way: View -> Active Editor -> Show Line Numbers (this option will only be available if you previously have clicked into a file of the active editor)

Second way: Right click on the small area between the project's structure and the active editor (that is, the one that you can set breakpoints) -> Show Line Numbers. enter image description here

How to restore/reset npm configuration to default values?

To reset user defaults

Run this in the command line (or git bash on windows):

echo "" > $(npm config get userconfig)
npm config edit

To reset global defaults

echo "" > $(npm config get globalconfig)
npm config --global edit

If you need sudo then run this instead:

sudo sh -c 'echo "" > $(npm config get globalconfig)'

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists

Work for me in CentOS:

$ service mysql stop
$ mysqld --skip-grant-tables &
$ mysql -u root mysql

mysql> FLUSH PRIVILEGES;
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';

$ service mysql restart

How to format number of decimal places in wpf using style/template?

    void NumericTextBoxInput(object sender, TextCompositionEventArgs e)
    {
        TextBox txt = (TextBox)sender;
        var regex = new Regex(@"^[0-9]*(?:\.[0-9]{0,1})?$");
        string str = txt.Text + e.Text.ToString();
        int cntPrc = 0;
        if (str.Contains('.'))
        {
            string[] tokens = str.Split('.');
            if (tokens.Count() > 0)
            {
                string result = tokens[1];
                char[] prc = result.ToCharArray();
                cntPrc = prc.Count();
            }
        }
        if (regex.IsMatch(e.Text) && !(e.Text == "." && ((TextBox)sender).Text.Contains(e.Text)) && (cntPrc < 3))
        {
            e.Handled = false;
        }
        else
        {
            e.Handled = true;
        }
    }

Is there a way to check which CSS styles are being used or not used on a web page?

Just for completeness and because it was asked in the comments - there's also the CSS audit tool in Chrome now for the same purpose. Some details here:

http://meeech.amihod.com/very-useful-find-unused-css-rules-with-google

Django - iterate number in for loop of a template

[Django HTML template doesn't support index as of now], but you can achieve the goal:

If you use Dictionary inside Dictionary in views.py then iteration is possible using key as index. example:

{% for key, value in DictionartResult.items %} <!-- dictionartResult is a dictionary having key value pair-->
<tr align="center">
    <td  bgcolor="Blue"><a href={{value.ProjectName}}><b>{{value.ProjectName}}</b></a></td>
    <td> {{ value.atIndex0 }} </td>         <!-- atIndex0 is a key which will have its value , you can treat this key as index to resolve-->
    <td> {{ value.atIndex4 }} </td>
    <td> {{ value.atIndex2 }} </td>
</tr>
{% endfor %}

Elseif you use List inside dictionary then not only first and last iteration can be controlled, but all index can be controlled. example:

{% for key, value in DictionaryResult.items %}
    <tr align="center">
    {% for project_data in value %}
        {% if  forloop.counter <= 13 %}  <!-- Here you can control the iteration-->
            {% if forloop.first %}
                <td bgcolor="Blue"><a href={{project_data}}><b> {{ project_data }} </b></a></td> <!-- it will always refer to project_data[0]-->
            {% else %}
                <td> {{ project_data }} </td> <!-- it will refer to all items in project_data[] except at index [0]-->
            {% endif %}
            {% endif %}
    {% endfor %}
    </tr>
{% endfor %}

End If ;)

// Hope have covered the solution with Dictionary, List, HTML template, For Loop, Inner loop, If Else. Django HTML Documentaion for more methods: https://docs.djangoproject.com/en/2.2/ref/templates/builtins/

Are PHP short tags acceptable to use?

No, and they're being phased out by PHP 6 so if you appreciate code longevity, simply don't use them or the <% ... %> tags.

How can I set the PATH variable for javac so I can manually compile my .java works?

Follow the steps given here

http://www.javaandme.com/

after setting variable, just navigate to your java file directory in your cmd and type javac "xyx.java"

or if you don't navigate to the directory, then simply specify the full path of java file

javac "/xyz.java"

JSON.parse vs. eval()

If you parse the JSON with eval, you're allowing the string being parsed to contain absolutely anything, so instead of just being a set of data, you could find yourself executing function calls, or whatever.

Also, JSON's parse accepts an aditional parameter, reviver, that lets you specify how to deal with certain values, such as datetimes (more info and example in the inline documentation here)

C# binary literals

Though the string parsing solution is the most popular, I don't like it, because parsing string can be a great performance hit in some situations.

When there is needed a kind of a bitfield or binary mask, I'd rather write it like

long bitMask = 1011001;

And later

int bit5 = BitField.GetBit(bitMask, 5);

Or

bool flag5 = BitField.GetFlag(bitMask, 5);`

Where BitField class is

public static class BitField
{
    public static int GetBit(int bitField, int index)
    {
        return (bitField / (int)Math.Pow(10, index)) % 10;
    }

    public static bool GetFlag(int bitField, int index)
    {
        return GetBit(bitField, index) == 1;
    }
}

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

'<option value=''.$key.'">'

should be

'<option value="'.$key.'">'

jQuery: Scroll down page a set increment (in pixels) on click?

You can do that using animate like in the following link:

http://blog.freelancer-id.com/index.php/2009/03/26/scroll-window-smoothly-in-jquery

If you want to do it using scrollTo plugin, then take a look the following:

How to scroll the window using JQuery $.scrollTo() function

Name node is in safe mode. Not able to leave

Run the command below using the HDFS OS user to disable safe mode:

sudo -u hdfs hadoop dfsadmin -safemode leave

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

How about using a simple loop to count the occurrences of number of spaces!?

_x000D_
_x000D_
txt = "Just an example here move along" _x000D_
count = 1_x000D_
for i in txt:_x000D_
if i == " ":_x000D_
   count += 1_x000D_
print(count)
_x000D_
_x000D_
_x000D_

Why should I use a container div in HTML?

Most of the browser are taking web page size by default. So, sometime page will not display same in different browser. So, by using user can change for specific HTML element. For example, user can add margin, size, width, height etc of specific HTML tag.

remove item from array using its name / value

Try this.(IE8+)

//Define function
function removeJsonAttrs(json,attrs){
    return JSON.parse(JSON.stringify(json,function(k,v){
        return attrs.indexOf(k)!==-1 ? undefined: v;
}));}
//use object
var countries = {};
countries.results = [
    {id:'AF',name:'Afghanistan'},
    {id:'AL',name:'Albania'},
    {id:'DZ',name:'Algeria'}
];
countries = removeJsonAttrs(countries,["name"]);
//use array
var arr = [
    {id:'AF',name:'Afghanistan'},
    {id:'AL',name:'Albania'},
    {id:'DZ',name:'Algeria'}
];
arr = removeJsonAttrs(arr,["name"]);

Remove Project from Android Studio

In the "Welcome to Android Studio" opening dialog you can highlight the app you want to remove from Android Studio and hit delete on your keyboard.

Get battery level and state in Android

You can use this to get remaining charged in percentage.

private void batteryLevel() {
        BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                context.unregisterReceiver(this);
                int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
                int level = -1;
                if (rawlevel >= 0 && scale > 0) {
                    level = (rawlevel * 100) / scale;
                }
                batterLevel.setText("Battery Level Remaining: " + level + "%");
            }
        };
        IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(batteryLevelReceiver, batteryLevelFilter);
    }

How can I stream webcam video with C#?

I've used VideoCapX for our project. It will stream out as MMS/ASF stream which can be open by media player. You can then embed media player into your webpage.

If you won't need much control, or if you want to try out VideoCapX without writing a code, try U-Broadcast, they use VideoCapX behind the scene.

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

For anybody reading this in the future, here is a simpler answer:

var s = "11:41:02PM";
var time = s.match(/\d{2}/g);
if (time[0] === "12") time[0] = "00";
if (s.indexOf("PM") > -1) time[0] = parseInt(time[0])+12;
return time.join(":");

How to request Administrator access inside a batch file

Here's a one-liner I've been using:

@echo off
if not "%1"=="am_admin" (powershell start -verb runas '%0' am_admin & exit /b)

echo main code here
pause

Notes:

  • Only tested on windows 7 and 10, you might have to mess around with the quoting
  • Doesn't support passing along arguments for now

Get data from php array - AJAX - jQuery

When you do echo $array;, PHP will simply echo 'Array' since it can't convert an array to a string. So The 'A' that you are actually getting is the first letter of Array, which is correct.

You might actually need

echo json_encode($array);

This should get you what you want.

EDIT : And obviously, you'd need to change your JS to work with JSON instead of just text (as pointed out by @genesis)

How to show only next line after the matched one?

Great answer from raim, was very useful for me. It is trivial to extend this to print e.g. line 7 after the pattern

awk -v lines=7 '/blah/ {for(i=lines;i;--i)getline; print $0 }' logfile

Openstreetmap: embedding map in webpage (like Google Maps)

There is simple way to do it if you fear Javascript...I'm still learning. Open Street makes a simple Wordpress plugin you can customize. Add OSM Widget plugin.

This will be a filler until I figure out my Python Java concotion using coverter TIGER line files from the Census Bureau.

How to implement common bash idioms in Python?

I suggest the awesome online book Dive Into Python. It's how I learned the language originally.

Beyond teaching you the basic structure of the language, and a whole lot of useful data structures, it has a good chapter on file handling and subsequent chapters on regular expressions and more.

jQuery Toggle Text?

var el  = $('#someSelector');    
el.text(el.text() == 'view more' ? 'view less' : 'view more');

PHP shell_exec() vs exec()

shell_exec - Execute command via shell and return the complete output as a string

exec - Execute an external program.

The difference is that with shell_exec you get output as a return value.

Execution Failed for task :app:compileDebugJavaWithJavac in Android Studio

Please check your app's build.gradle. I had the same problem, finally I found the problem was in my build.gradle file dependencies{}, it add extra .jar file which actually didn't exist in my project as dependency. So I delete this dependency, and the problem has gone.

How to get JS variable to retain value after page refresh?

You will have to use cookie to store the value across page refresh. You can use any one of the many javascript based cookie libraries to simplify the cookie access, like this one

If you want to support only html5 then you can think of Storage api like localStorage/sessionStorage

Ex: using localStorage and cookies library

var mode = getStoredValue('myPageMode');

function buttonClick(mode) {
    mode = mode;
    storeValue('myPageMode', mode);
}

function storeValue(key, value) {
    if (localStorage) {
        localStorage.setItem(key, value);
    } else {
        $.cookies.set(key, value);
    }
}

function getStoredValue(key) {
    if (localStorage) {
        return localStorage.getItem(key);
    } else {
        return $.cookies.get(key);
    }
}

Sending and receiving data over a network using TcpClient

I have had luck using the socket object directly (rather than the TCP client). I create a Server object that looks something like this (I've edited some stuff such as exception handling out for brevity, but I hope that the idea comes across.)...

public class Server()
{
    private Socket sock;
    // You'll probably want to initialize the port and address in the
    // constructor, or via accessors, but to start your server listening
    // on port 8080 and on any IP address available on the machine...
    private int port = 8080;
    private IPAddress addr = IPAddress.Any;

    // This is the method that starts the server listening.
    public void Start()
    {
        // Create the new socket on which we'll be listening.
        this.sock = new Socket(
            addr.AddressFamily,
            SocketType.Stream,
            ProtocolType.Tcp);
        // Bind the socket to the address and port.
        sock.Bind(new IPEndPoint(this.addr, this.port));
        // Start listening.
        this.sock.Listen(this.backlog);
        // Set up the callback to be notified when somebody requests
        // a new connection.
        this.sock.BeginAccept(this.OnConnectRequest, sock);
    }

    // This is the method that is called when the socket recives a request
    // for a new connection.
    private void OnConnectRequest(IAsyncResult result)
    {
        // Get the socket (which should be this listener's socket) from
        // the argument.
        Socket sock = (Socket)result.AsyncState;
        // Create a new client connection, using the primary socket to
        // spawn a new socket.
        Connection newConn = new Connection(sock.EndAccept(result));
        // Tell the listener socket to start listening again.
        sock.BeginAccept(this.OnConnectRequest, sock);
    }
}

Then, I use a separate Connection class to manage the individual connection with the remote host. That looks something like this...

public class Connection()
{
    private Socket sock;
    // Pick whatever encoding works best for you.  Just make sure the remote 
    // host is using the same encoding.
    private Encoding encoding = Encoding.UTF8;

    public Connection(Socket s)
    {
        this.sock = s;
        // Start listening for incoming data.  (If you want a multi-
        // threaded service, you can start this method up in a separate
        // thread.)
        this.BeginReceive();
    }

    // Call this method to set this connection's socket up to receive data.
    private void BeginReceive()
    {
        this.sock.BeginReceive(
                this.dataRcvBuf, 0,
                this.dataRcvBuf.Length,
                SocketFlags.None,
                new AsyncCallback(this.OnBytesReceived),
                this);
    }

    // This is the method that is called whenever the socket receives
    // incoming bytes.
    protected void OnBytesReceived(IAsyncResult result)
    {
        // End the data receiving that the socket has done and get
        // the number of bytes read.
        int nBytesRec = this.sock.EndReceive(result);
        // If no bytes were received, the connection is closed (at
        // least as far as we're concerned).
        if (nBytesRec <= 0)
        {
            this.sock.Close();
            return;
        }
        // Convert the data we have to a string.
        string strReceived = this.encoding.GetString(
            this.dataRcvBuf, 0, nBytesRec);

        // ...Now, do whatever works best with the string data.
        // You could, for example, look at each character in the string
        // one-at-a-time and check for characters like the "end of text"
        // character ('\u0003') from a client indicating that they've finished
        // sending the current message.  It's totally up to you how you want
        // the protocol to work.

        // Whenever you decide the connection should be closed, call 
        // sock.Close() and don't call sock.BeginReceive() again.  But as long 
        // as you want to keep processing incoming data...

        // Set up again to get the next chunk of data.
        this.sock.BeginReceive(
            this.dataRcvBuf, 0,
            this.dataRcvBuf.Length,
            SocketFlags.None,
            new AsyncCallback(this.OnBytesReceived),
            this);

    }
}

You can use your Connection object to send data by calling its Socket directly, like so...

this.sock.Send(this.encoding.GetBytes("Hello to you, remote host."));

As I said, I've tried to edit the code here for posting, so I apologize if there are any errors in it.

Push eclipse project to GitHub with EGit

Simple Steps:

-Open Eclipse.

  • Select Project which you want to push on github->rightclick.
  • select Team->share Project->Git->Create repository->finish.(it will ask to login in Git account(popup).
  • Right click again to Project->Team->commit. you are done

Maven project version inheritance - do I have to specify the parent version?

eFox's answer worked for a single project, but not when I was referencing a module from another one (the pom.xml were still stored in my .m2 with the property instead of the version).

However, it works if you combine it with the flatten-maven-plugin, since it generates the poms with the correct version, not the property.

The only option I changed in the plug-in definition is the outputDirectory, it's empty by default, but I prefer to have it in target, which is set in my .gitignore configuration:

<plugin>
   <groupId>org.codehaus.mojo</groupId>
   <artifactId>flatten-maven-plugin</artifactId>
   <version>1.0.1</version>
   <configuration>
      <updatePomFile>true</updatePomFile>
      <outputDirectory>target</outputDirectory>
   </configuration>
   <executions>
      <execution>
         <id>flatten</id>
         <phase>process-resources</phase>
         <goals>
            <goal>flatten</goal>
         </goals>
      </execution>
   </executions>
</plugin>

The plug-in configuration goes in the parent pom.xml

refresh div with jquery

I want to just refresh the div, without refreshing the page ... Is this possible?

Yes, though it isn't going to be obvious that it does anything unless you change the contents of the div.

If you just want the graphical fade-in effect, simply remove the .html(data) call:

$("#panel").hide().fadeIn('fast');

Here is a demo you can mess around with: http://jsfiddle.net/ZPYUS/

It changes the contents of the div without making an ajax call to the server, and without refreshing the page. The content is hard coded, though. You can't do anything about that fact without contacting the server somehow: ajax, some sort of sub-page request, or some sort of page refresh.

html:

<div id="panel">test data</div>
<input id="changePanel" value="Change Panel" type="button">?

javascript:

$("#changePanel").click(function() {
    var data = "foobar";
    $("#panel").hide().html(data).fadeIn('fast');
});?

css:

div {
    padding: 1em;
    background-color: #00c000;
}

input {
    padding: .25em 1em;
}?

Div table-cell vertical align not working

This is how I do it:

CSS:

html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    display: table
}
#content {
    display: table-cell;
    text-align: center;
    vertical-align: middle
}

HTML:

<div id="content">
    Content goes here
</div>

See

Example of vertical centering

and

CSS: centering things.

Does MS Access support "CASE WHEN" clause if connect with ODBC?

Since you are using Access to compose the query, you have to stick to Access's version of SQL.

To choose between several different return values, use the switch() function. So to translate and extend your example a bit:

select switch(
  age > 40, 4,
  age > 25, 3,
  age > 20, 2,
  age > 10, 1,
  true, 0
) from demo

The 'true' case is the default one. If you don't have it and none of the other cases match, the function will return null.

The Office website has documentation on this but their example syntax is VBA and it's also wrong. I've given them feedback on this but you should be fine following the above example.

How do I correctly upgrade angular 2 (npm) to the latest version?

If you are looking like me for just updating your project to the latest these is what works form me since Angular 6:

Open the console on your project folder: If you type: ng update then you will get the below message:

        We analyzed your package.json, there are some packages to update:

          Name                               Version                  Command to update
         --------------------------------------------------------------------------------
          @angular/cli                       7.0.7 -> 7.2.2           ng update @angular/cli
          @angular/core                      7.0.4 -> 7.2.1           ng update @angular/core

There might be additional packages that are outdated.
    Run "ng update --all" to try to update all at the same time.

So I usually go straight and do:

ng update --all

Finally you can check your new version:

ng version
Angular CLI: 7.2.2
Node: 8.12.0
OS: win32 x64
Angular: 7.2.1
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.12.2
@angular-devkit/build-angular     0.12.2
@angular-devkit/build-optimizer   0.12.2
@angular-devkit/build-webpack     0.12.2
@angular-devkit/core              7.2.2
@angular-devkit/schematics        7.2.2
@angular/cli                      7.2.2
@ngtools/webpack                  7.2.2
@schematics/angular               7.2.2
@schematics/update                0.12.2
rxjs                              6.3.3
typescript                        3.2.4
webpack                           4.28.4

Minimum Hardware requirements for Android development

I find identically-specced AVDs run and load far better on my home machine (Phenom II x4 945/8GB RAM/Win7 HP 64bit) than they do on my work machine (Core2Duo/3GB RAM/Ubuntu 11.04 32bit).

As you're essentially running a virtual machine, I would personally go for nothing less than a dual core/4GB, though highly recommend a quad/8GB if you can splash out for that.

How to have stored properties in Swift, the same way I had on Objective-C?

My $0.02. This code is written in Swift 2.0

extension CALayer {
    private struct AssociatedKeys {
        static var shapeLayer:CAShapeLayer?
    }

    var shapeLayer: CAShapeLayer? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.shapeLayer) as? CAShapeLayer
        }
        set {
            if let newValue = newValue {
                objc_setAssociatedObject(self, &AssociatedKeys.shapeLayer, newValue as CAShapeLayer?, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
    }
}

I have tried many solutions, and found this is the only way to actually extend a class with extra variable parameters.

Get current cursor position

GetCursorPos() will return to you the x/y if you pass in a pointer to a POINT structure.

Hiding the cursor can be done with ShowCursor().

Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence

Use the ensure_ascii=False switch to json.dumps(), then encode the value to UTF-8 manually:

>>> json_string = json.dumps("??? ????", ensure_ascii=False).encode('utf8')
>>> json_string
b'"\xd7\x91\xd7\xa8\xd7\x99 \xd7\xa6\xd7\xa7\xd7\x9c\xd7\x94"'
>>> print(json_string.decode())
"??? ????"

If you are writing to a file, just use json.dump() and leave it to the file object to encode:

with open('filename', 'w', encoding='utf8') as json_file:
    json.dump("??? ????", json_file, ensure_ascii=False)

Caveats for Python 2

For Python 2, there are some more caveats to take into account. If you are writing this to a file, you can use io.open() instead of open() to produce a file object that encodes Unicode values for you as you write, then use json.dump() instead to write to that file:

with io.open('filename', 'w', encoding='utf8') as json_file:
    json.dump(u"??? ????", json_file, ensure_ascii=False)

Do note that there is a bug in the json module where the ensure_ascii=False flag can produce a mix of unicode and str objects. The workaround for Python 2 then is:

with io.open('filename', 'w', encoding='utf8') as json_file:
    data = json.dumps(u"??? ????", ensure_ascii=False)
    # unicode(data) auto-decodes data to unicode if str
    json_file.write(unicode(data))

In Python 2, when using byte strings (type str), encoded to UTF-8, make sure to also set the encoding keyword:

>>> d={ 1: "??? ????", 2: u"??? ????" }
>>> d
{1: '\xd7\x91\xd7\xa8\xd7\x99 \xd7\xa6\xd7\xa7\xd7\x9c\xd7\x94', 2: u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4'}

>>> s=json.dumps(d, ensure_ascii=False, encoding='utf8')
>>> s
u'{"1": "\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4", "2": "\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4"}'
>>> json.loads(s)['1']
u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4'
>>> json.loads(s)['2']
u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4'
>>> print json.loads(s)['1']
??? ????
>>> print json.loads(s)['2']
??? ????

Converting a PDF to PNG

You can use ImageMagick without separating the first page of the PDF with other tools. Just do

convert -density 288 cover.pdf[0] -resize 25% cover.png


Here I increase the nominal density by 400% (72*4=288) and then resize by 1/4 (25%). This gives a much better quality for the resulting png.

However, if the PDF is CMYK, PNG does not support that. It would need to be converted to sRGB, especially if it has transparency, since Ghostscript cannot handle CMYK with alpha.

convert -density 288 -colorspace sRGB -resize 25% cover.pdf[0] cover.png

Fatal error: [] operator not supported for strings

You have probably defined $name, $date, $text or $date2 to be a string, like:

$name = 'String';

Then if you treat it like an array it will give that fatal error:

$name[] = 'new value'; // fatal error

To solve your problem just add the following code at the beginning of the loop:

$name = array();
$date = array();
$text = array();
$date2 = array();

This will reset their value to array and then you'll able to use them as arrays.

Xcode stuck on Indexing

Close Your Xcode , close any git client(source tree or terminal)if it is opened and finally restart your project.

Kotlin's List missing "add", "remove", Map missing "put", etc?

You can do with create new one like this.

var list1 = ArrayList<Int>()
var list2  = list1.toMutableList()
list2.add(item)

Now you can use list2, Thank you.

What's an Aggregate Root?

From a broken link:

Within an Aggregate there is an Aggregate Root. The Aggregate Root is the parent Entity to all other Entities and Value Objects within the Aggregate.

A Repository operates upon an Aggregate Root.

More info can also be found here.

What characters are forbidden in Windows and Linux directory names?

When creating internet shortcuts in Windows, to create the file name, it skips illegal characters, except for forward slash, which is converted to minus.

How to search in an array with preg_match?

In this post I'll provide you with three different methods of doing what you ask for. I actually recommend using the last snippet, since it's easiest to comprehend as well as being quite neat in code.

How do I see what elements in an array that matches my regular expression?

There is a function dedicated for just this purpose, preg_grep. It will take a regular expression as first parameter, and an array as the second.

See the below example:

$haystack = array (
  'say hello',
  'hello stackoverflow',
  'hello world',
  'foo bar bas'
);

$matches  = preg_grep ('/^hello (\w+)/i', $haystack);

print_r ($matches);

output

Array
(
    [1] => hello stackoverflow
    [2] => hello world
)

Documentation


But I just want to get the value of the specified groups. How?

array_reduce with preg_match can solve this issue in clean manner; see the snippet below.

$haystack = array (
  'say hello',
  'hello stackoverflow',
  'hello world',
  'foo bar bas'
);

function _matcher ($m, $str) {
  if (preg_match ('/^hello (\w+)/i', $str, $matches))
    $m[] = $matches[1];

  return $m;
}

// N O T E :
// ------------------------------------------------------------------------------
// you could specify '_matcher' as an anonymous function directly to
// array_reduce though that kind of decreases readability and is therefore
// not recommended, but it is possible.

$matches = array_reduce ($haystack, '_matcher', array ());

print_r ($matches);

output

Array
(
    [0] => stackoverflow
    [1] => world
)

Documentation


Using array_reduce seems tedious, isn't there another way?

Yes, and this one is actually cleaner though it doesn't involve using any pre-existing array_* or preg_* function.

Wrap it in a function if you are going to use this method more than once.

$matches = array ();

foreach ($haystack as $str) 
  if (preg_match ('/^hello (\w+)/i', $str, $m))
    $matches[] = $m[1];

Documentation

Regex not operator

No, there's no direct not operator. At least not the way you hope for.

You can use a zero-width negative lookahead, however:

\((?!2001)[0-9a-zA-z _\.\-:]*\)

The (?!...) part means "only match if the text following (hence: lookahead) this doesn't (hence: negative) match this. But it doesn't actually consume the characters it matches (hence: zero-width).

There are actually 4 combinations of lookarounds with 2 axes:

  • lookbehind / lookahead : specifies if the characters before or after the point are considered
  • positive / negative : specifies if the characters must match or must not match.

Returning a boolean value in a JavaScript function

An old thread, sure, but a popular one apparently. It's 2020 now and none of these answers have addressed the issue of unreadable code. @pimvdb's answer takes up less lines, but it's also pretty complicated to follow. For easier debugging and better readability, I should suggest refactoring the OP's code to something like this, and adopting an early return pattern, as this is likely the main reason you were unsure of why the were getting undefined:

function validatePassword() {
   const password = document.getElementById("password");
   const confirm_password = document.getElementById("password_confirm");

   if (password.value.length === 0) {
      return false;
   }

   if (password.value !== confirm_password.value) {
      return false;
   }
  
   return true;
}

How to write a confusion matrix in Python?

A numpy-only solution for any number of classes that doesn't require looping:

import numpy as np

classes = 3
true = np.random.randint(0, classes, 50)
pred = np.random.randint(0, classes, 50)

np.bincount(true * classes + pred).reshape((classes, classes))

Make javascript alert Yes/No Instead of Ok/Cancel

"Confirm" in Javascript stops the whole process until it gets a mouse response on its buttons. If that is what you are looking for, you can refer jquery-ui but if you have nothing running behind your process while receiving the response and you control the flow programatically, take a look at this. You will have to hard-code everything by yourself but you have complete command over customization. https://www.w3schools.com/howto/howto_css_modals.asp

Use cell's color as condition in if statement (function)

Although this does not directly address your question, you can actually sort your data by cell colour in Excel (which then makes it pretty easy to label all records with a particular colour in the same way and, hence, condition upon this label).

In Excel 2010, you can do this by going to Data -> Sort -> Sort On "Cell Colour".

Return a value of '1' a referenced cell is empty

Beware: There are also cells which are seemingly blank, but are not truly empty but containg "" or something that is called NULL in other languages. As an example, when a formula results in "" or such result is copied to a cell, the formula

ISBLANK(A1) 

returns FALSE. That means the cell is not truly empty.

The way to go there is to use enter code here

COUNTBLANK(A1)

Which finds both truly empty cells and those containing "". See also this very good answer here

How to convert string to IP address and vice versa

Hexadecimal IP Address to String IP

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    uint32_t ip = 0x0AA40001;
    string ip_str="";
    int temp = 0;
    for (int i = 0; i < 8; i++){
        if (i % 2 == 0)
        {
            temp += ip & 15;
            ip = ip >> 4;
        }
        else
        {
            stringstream ss;
            temp += (ip & 15) * 16;
            ip = ip >> 4;
            ss << temp;
            ip_str = ss.str()+"." + ip_str;
            temp = 0;
        }
    }
    ip_str.pop_back();
    cout << ip_str;
}

Output:10.164.0.1

on change event for file input element

Give unique class and different id for file input

           $("#tab-content").on('change',class,function()
               {
                  var id=$(this).attr('id');
                      $("#"+id).trigger(your function); 
               //for name of file input  $("#"+id).attr("name");
               });

How to display pandas DataFrame of floats using a format string for columns?

You can also set locale to your region and set float_format to use a currency format. This will automatically set $ sign for currency in USA.

import locale

locale.setlocale(locale.LC_ALL, "en_US.UTF-8")

pd.set_option("float_format", locale.currency)

df = pd.DataFrame(
    [123.4567, 234.5678, 345.6789, 456.7890],
    index=["foo", "bar", "baz", "quux"],
    columns=["cost"],
)
print(df)

        cost
foo  $123.46
bar  $234.57
baz  $345.68
quux $456.79

How do I force Postgres to use a particular index?

Sometimes PostgreSQL fails to make the best choice of indexes for a particular condition. As an example, suppose there is a transactions table with several million rows, of which there are several hundred for any given day, and the table has four indexes: transaction_id, client_id, date, and description. You want to run the following query:

SELECT client_id, SUM(amount)
FROM transactions
WHERE date >= 'yesterday'::timestamp AND date < 'today'::timestamp AND
      description = 'Refund'
GROUP BY client_id

PostgreSQL may choose to use the index transactions_description_idx instead of transactions_date_idx, which may lead to the query taking several minutes instead of less than one second. If this is the case, you can force using the index on date by fudging the condition like this:

SELECT client_id, SUM(amount)
FROM transactions
WHERE date >= 'yesterday'::timestamp AND date < 'today'::timestamp AND
      description||'' = 'Refund'
GROUP BY client_id

How do I sort a VARCHAR column in SQL server that contains numbers?

 SELECT *,
       ROW_NUMBER()OVER(ORDER BY CASE WHEN ISNUMERIC (ID)=1 THEN CONVERT(NUMERIC(20,2),SUBSTRING(Id, PATINDEX('%[0-9]%', Id), LEN(Id)))END DESC)Rn ---- numerical
        FROM
            (

        SELECT '1'Id UNION ALL
        SELECT '25.20' Id UNION ALL

    SELECT 'A115' Id UNION ALL
    SELECT '2541' Id UNION ALL
    SELECT '571.50' Id UNION ALL
    SELECT '67' Id UNION ALL
    SELECT 'B48' Id UNION ALL
    SELECT '500' Id UNION ALL
    SELECT '147.54' Id UNION ALL
    SELECT 'A-100' Id
    )A

    ORDER BY 
    CASE WHEN ISNUMERIC (ID)=0                                /* alphabetical sort */ 
         THEN CASE WHEN PATINDEX('%[0-9]%', Id)=0
                   THEN LEFT(Id,PATINDEX('%[0-9]%',Id))
                   ELSE LEFT(Id,PATINDEX('%[0-9]%',Id)-1)
              END
    END DESC

TypeScript: correct way to do string equality?

If you know x and y are both strings, using === is not strictly necessary, but is still good practice.

Assuming both variables actually are strings, both operators will function identically. However, TS often allows you to pass an object that meets all the requirements of string rather than an actual string, which may complicate things.

Given the possibility of confusion or changes in the future, your linter is probably correct in demanding ===. Just go with that.

Ruby: Can I write multi-line string with no concatenation?

Recently with the new features in Ruby 2.3 the new squiggly HEREDOC will let you write our multiline strings in a nice manner with a minimal change so using this combined with the .squish (if you are using rails) will let you write multiline in a nice way! in case of just using ruby, you can do a <<~SQL.split.join(" ") which is almost the same

[1] pry(main)> <<~SQL.squish
[1] pry(main)*   select attr1, attr2, attr3, attr4, attr5, attr6, attr7
[1] pry(main)*   from table1, table2, table3, etc, etc, etc, etc, etc,
[1] pry(main)*   where etc etc etc etc etc etc etc etc etc etc etc etc etc
[1] pry(main)* SQL
=> "select attr1, attr2, attr3, attr4, attr5, attr6, attr7 from table1, table2, table3, etc, etc, etc, etc, etc, where etc etc etc etc etc etc etc etc etc etc etc etc etc"

ref: https://infinum.co/the-capsized-eight/multiline-strings-ruby-2-3-0-the-squiggly-heredoc

MySQL date formats - difficulty Inserting a date

When using a string-typed variable in PHP containing a date, the variable must be enclosed in single quotes:

$NEW_DATE = '1997-07-15';
$sql = "INSERT INTO tbl (NEW_DATE, ...) VALUES ('$NEW_DATE', ...)";

Error when deploying an artifact in Nexus

I had the same problem today with the addition "Return code is: 400, ReasonPhrase: Bad Request." which turned out to be the "artifact is already deployed with that version if it is a release" problem from answer above enter link description here

One solution not mentioned yet is to configure Nexus to allow redeployment into a Release repository. Maybe not a best practice, because this is set for a reason, you nevertheless could go to "Access Settings" in your Nexus repositories´ "Configuration"-Tab and set the "Deployment Policy" to "Allow Redeploy".

Media query to detect if device is touchscreen

This will work. If it doesn't let me know

@media (hover: none) and (pointer: coarse) {
    /* Touch screen device style goes here */
}

edit: hover on-demand is not supported anymore

.crx file install in chrome

Opening the debug console in Chrome, or even looking at the html source file (after it is loaded in the browser), make sure that all the paths there are valid (i.e. when you follow a link you get to it's content, and not an error). When something is not valid, fix the path (e.g. get rid of the server specific part and make sure you only refer to files that are part of your extension through paths like /js/jquery-123-min.js).

How to call a button click event from another method

For me this worked in WPF

    private void Window_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            RoutedEventArgs routedEventArgs = new RoutedEventArgs(ButtonBase.ClickEvent, Button_OK);
            Button_OK.RaiseEvent(routedEventArgs);
        }
    }

ImportError: No module named pythoncom

$ pip3 install pypiwin32

Sometimes using pip3 also works if just pip by itself is not working.

Can't use modulus on doubles?

The % operator is for integers. You're looking for the fmod() function.

#include <cmath>

int main()
{
    double x = 6.3;
    double y = 2.0;
    double z = std::fmod(x,y);

}

Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

Hendry's answer is 100% correct. I had the same problem with my application, where there is repository project dealing with database with use of methods encapsulating EF db context operation. Other projects use this repository, and I don't want to reference EF in those projects. Somehow I don't feel it's proper, I need EF only in repository project. Anyway, copying EntityFramework.SqlServer.dll to other project output directory solves the problem. To avoid problems, when you forget to copy this dll, you can change repository build directory. Go to repository project's properties, select Build tab, and in output section you can set output directory to other project's build directory. Sure, it's just workaround. Maybe the hack, mentioned in some placec, is better:

var instance = System.Data.Entity.SqlServer.SqlProviderServices.Instance;

Still, for development purposes it is enough. Later, when preparing install or publish, you can add this file to package.

I'm quite new to EF. Is there any better method to solve this issue? I don't like "hack" - it makes me feel that there is something that is "not secure".

How can I get log4j to delete old rotating log files?

Logs rotate for a reason, so that you only keep so many log files around. In log4j.xml you can add this to your node:

<param name="MaxBackupIndex" value="20"/>

The value tells log4j.xml to only keep 20 rotated log files around. You can limit this to 5 if you want or even 1. If your application isn't logging that much data, and you have 20 log files spanning the last 8 months, but you only need a weeks worth of logs, then I think you need to tweak your log4j.xml "MaxBackupIndex" and "MaxFileSize" params.

Alternatively, if you are using a properties file (instead of the xml) and wish to save 15 files (for example)

log4j.appender.[appenderName].MaxBackupIndex = 15

How can git be installed on CENTOS 5.5?

For installing git

  1. install last epel-release

rpm -Uvh http://dl.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm

  1. Install git from repository

yum install git

Error message: "'chromedriver' executable needs to be available in the path"

When I downloaded chromedriver.exe I just move it in PATH folder C:\Windows\System32\chromedriver.exe and had exact same problem.

For me solution was to just change folder in PATH, so I just moved it at Pycharm Community bin folder that was also in PATH. ex:

  • C:\Windows\System32\chromedriver.exe --> Gave me exception
  • C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.3\bin\chromedriver.exe --> worked fine

How can I select checkboxes using the Selenium Java WebDriver?

It appears that the Internet Explorer driver does not interact with everything in the same way the other drivers do and checkboxes is one of those cases.

The trick with checkboxes is to send the Space key instead of using a click (only needed on Internet Explorer), like so in C#:

if (driver.Capabilities.BrowserName.Equals(“internet explorer"))
    driver.findElement(By.id("idOfTheElement").SendKeys(Keys.Space);
else
    driver.findElement(By.id("idOfTheElement").Click();

How to reset Jenkins security settings from the command line?

On the offchance you accidentally lock yourself out of Jenkins due to a permission mistake, and you dont have server-side access to switch to the jenkins user or root... You can make a job in Jenkins and add this to the Shell Script:

sed -i 's/<useSecurity>true/<useSecurity>false/' ~/config.xml

Then click Build Now and restart Jenkins (or the server if you need to!)

Angular 4/5/6 Global Variables

You can use the Window object and access it everwhere. example window.defaultTitle = "my title"; then you can access window.defaultTitle without importing anything.

sorting and paging with gridview asp.net

<asp:GridView 
    ID="GridView1" runat="server" AutoGenerateColumns="false" AllowSorting="True" onsorting="GridView1_Sorting" EnableViewState="true"> 
    <Columns>
        <asp:BoundField DataField="bookid" HeaderText="BOOK ID"SortExpression="bookid"  />
        <asp:BoundField DataField="bookname" HeaderText="BOOK NAME" />
        <asp:BoundField DataField="writer" HeaderText="WRITER" />
        <asp:BoundField DataField="totalbook" HeaderText="TOTALBOOK" SortExpression="totalbook"  />
        <asp:BoundField DataField="availablebook" HeaderText="AVAILABLE BOOK" />
    </Columns>
</asp:GridView>

Code behind:

protected void Page_Load(object sender, EventArgs e) {
        if (!IsPostBack) {
            string query = "SELECT * FROM book";
            DataTable DT = new DataTable();
            SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);
            DA.Fill(DT);

            GridView1.DataSource = DT;
            GridView1.DataBind();
        }
    }

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) {

        string query = "SELECT * FROM book";
        DataTable DT = new DataTable();
        SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);
        DA.Fill(DT);

        GridView1.DataSource = DT;
        GridView1.DataBind();

        if (DT != null) {
            DataView dataView = new DataView(DT);
            dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);

            GridView1.DataSource = dataView;
            GridView1.DataBind();
        }
    }

    private string GridViewSortDirection {
        get { return ViewState["SortDirection"] as string ?? "DESC"; }
        set { ViewState["SortDirection"] = value; }
    }

    private string ConvertSortDirectionToSql(SortDirection sortDirection) {
        switch (GridViewSortDirection) {
            case "ASC":
                GridViewSortDirection = "DESC";
                break;

            case "DESC":
                GridViewSortDirection = "ASC";
                break;
        }

        return GridViewSortDirection;
    }
}

What are the differences between .gitignore and .gitkeep?

.gitkeep is just a placeholder. A dummy file, so Git will not forget about the directory, since Git tracks only files.


If you want an empty directory and make sure it stays 'clean' for Git, create a .gitignore containing the following lines within:

# .gitignore sample
###################

# Ignore all files in this dir...
*

# ... except for this one.
!.gitignore

If you desire to have only one type of files being visible to Git, here is an example how to filter everything out, except .gitignore and all .txt files:

# .gitignore to keep just .txt files
###################################

# Filter everything...
*

# ... except the .gitignore...
!.gitignore

# ... and all text files.
!*.txt

('#' indicates comments.)

Java JSON serialization - best practice

Have your tried json-io (https://github.com/jdereg/json-io)?

This library allows you to serialize / deserialize any Java object graph, including object graphs with cycles in them (e.g., A->B, B->A). It does not require your classes to implement any particular interface or inherit from any particular Java class.

In addition to serialization of Java to JSON (and JSON to Java), you can use it to format (pretty print) JSON:

String niceFormattedJson = JsonWriter.formatJson(jsonString)

MySQL Nested Select Query?

You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t below) and alias the columns as well.

The DISTINCT can also be safely removed as the internal GROUP BY makes it redundant:

SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
    SELECT MIN(`date`) AS `date`, `player_name`
    FROM `player_playtime`
    GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;

Since the COUNT is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*) and further simplify the query:

SELECT t.date , COUNT(*) AS player_count
FROM (
    SELECT DATE(MIN(`date`)) AS date
    FROM player_playtime
    GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;

Angular: How to download a file from HttpClient?

Blobs are returned with file type from backend. The following function will accept any file type and popup download window:

downloadFile(route: string, filename: string = null): void{

    const baseUrl = 'http://myserver/index.php/api';
    const token = 'my JWT';
    const headers = new HttpHeaders().set('authorization','Bearer '+token);
    this.http.get(baseUrl + route,{headers, responseType: 'blob' as 'json'}).subscribe(
        (response: any) =>{
            let dataType = response.type;
            let binaryData = [];
            binaryData.push(response);
            let downloadLink = document.createElement('a');
            downloadLink.href = window.URL.createObjectURL(new Blob(binaryData, {type: dataType}));
            if (filename)
                downloadLink.setAttribute('download', filename);
            document.body.appendChild(downloadLink);
            downloadLink.click();
        }
    )
}

Python unexpected EOF while parsing

I'm trying to answer in general, not related to this question, this error generally occurs when you break a syntax in half and forget the other half. Like in my case it was:

try :
 ....

since python was searching for a

except Exception as e:
 ....

but it encountered an EOF (End Of File), hence the error. See if you can find any incomplete syntax in your code.

is there a function in lodash to replace matched item

Came across this as well and did it simply that way.

const persons = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];
const updatedPerson = {id: 1, name: "new Person Name"}
const updatedPersons = persons.map(person => (
  person.id === updated.id
    ? updatedPerson
    : person
))

If wanted we can generalize it

const replaceWhere = (list, predicate, replacement) => {
  return list.map(item => predicate(item) ? replacement : item)
}

replaceWhere(persons, person => person.id === updatedPerson.id, updatedPerson)

Assign output to variable in Bash

In shell, you don't put a $ in front of a variable you're assigning. You only use $IP when you're referring to the variable.

#!/bin/bash

IP=$(curl automation.whatismyip.com/n09230945.asp)

echo "$IP"

sed "s/IP/$IP/" nsupdate.txt | nsupdate

How to print something when running Puppet client?

Easier way, use notice. e.g notice("foo.pp works") or notice($foo)

HTML radio buttons allowing multiple selections

The name of the inputs must be the same to belong to the same group. Then the others will be automatically deselected when one is clicked.

Classes residing in App_Code is not accessible

In my case, I couldn't get a project to build with classes defined in the App_Code folder.

Can't replicate the scenario precisely to comment, but had to close and re-open visual studio for intellisense to co-operate agree...

I noticed that when a class in the App_Code folder is set to 'Compile' instead of 'Content' (right-click it) that the errors were coming from a second version of the class... Look to the left-most of the 3 of the 3 fields between the code pane and the tab. The 'other' one was called something along the lines of 10_App_Code or similar.

To rectify the issue, I renamed the folder from App_Code to Code, explicitly set namespaces on the classes and set all of the classes to 'Compile'

Create local maven repository

Yes you can! For a simple repository that only publish/retrieve artifacts, you can use nginx.

  1. Make sure nginx has http dav module enabled, it should, but nonetheless verify it.

  2. Configure nginx http dav module:

    In Windows: d:\servers\nginx\nginx.conf

    location / {
        # maven repository
        dav_methods  PUT DELETE MKCOL COPY MOVE;
        create_full_put_path  on;
        dav_access  user:rw group:rw all:r;
    }
    

    In Linux (Ubuntu): /etc/nginx/sites-available/default

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            # try_files $uri $uri/ =404;  # IMPORTANT comment this
            dav_methods  PUT DELETE MKCOL COPY MOVE;
            create_full_put_path  on;
            dav_access  user:rw group:rw all:r;
    }
    

    Don't forget to give permissions to the directory where the repo will be located:

    sudo chmod +777 /var/www/html/repository

  3. In your project's pom.xml add the respective configuration:

    Retrieve artifacts:

    <repositories>
        <repository>
            <id>repository</id>
            <url>http://<your.ip.or.hostname>/repository</url>
        </repository>
    </repositories>
    

    Publish artifacts:

    <build>
        <extensions>
            <extension>
                <groupId>org.apache.maven.wagon</groupId>
                <artifactId>wagon-http</artifactId>
                <version>3.2.0</version>
            </extension>
        </extensions>
    </build>
    <distributionManagement>
        <repository>
            <id>repository</id>
            <url>http://<your.ip.or.hostname>/repository</url>
        </repository>
    </distributionManagement>
    
  4. To publish artifacts use mvn deploy. To retrieve artifacts, maven will do it automatically.

And there you have it a simple maven repo.

How to compare two JSON objects with the same elements in a different order equal?

For others who'd like to debug the two JSON objects (usually, there is a reference and a target), here is a solution you may use. It will list the "path" of different/mismatched ones from target to the reference.

level option is used for selecting how deep you would like to look into.

show_variables option can be turned on to show the relevant variable.

def compareJson(example_json, target_json, level=-1, show_variables=False):
  _different_variables = _parseJSON(example_json, target_json, level=level, show_variables=show_variables)
  return len(_different_variables) == 0, _different_variables

def _parseJSON(reference, target, path=[], level=-1, show_variables=False):  
  if level > 0 and len(path) == level:
    return []
  
  _different_variables = list()
  # the case that the inputs is a dict (i.e. json dict)  
  if isinstance(reference, dict):
    for _key in reference:      
      _path = path+[_key]
      try:
        _different_variables += _parseJSON(reference[_key], target[_key], _path, level, show_variables)
      except KeyError:
        _record = ''.join(['[%s]'%str(p) for p in _path])
        if show_variables:
          _record += ': %s <--> MISSING!!'%str(reference[_key])
        _different_variables.append(_record)
  # the case that the inputs is a list/tuple
  elif isinstance(reference, list) or isinstance(reference, tuple):
    for index, v in enumerate(reference):
      _path = path+[index]
      try:
        _target_v = target[index]
        _different_variables += _parseJSON(v, _target_v, _path, level, show_variables)
      except IndexError:
        _record = ''.join(['[%s]'%str(p) for p in _path])
        if show_variables:
          _record += ': %s <--> MISSING!!'%str(v)
        _different_variables.append(_record)
  # the actual comparison about the value, if they are not the same, record it
  elif reference != target:
    _record = ''.join(['[%s]'%str(p) for p in path])
    if show_variables:
      _record += ': %s <--> %s'%(str(reference), str(target))
    _different_variables.append(_record)

  return _different_variables

What is the __del__ method, How to call it?

I wrote up the answer for another question, though this is a more accurate question for it.

How do constructors and destructors work?

Here is a slightly opinionated answer.

Don't use __del__. This is not C++ or a language built for destructors. The __del__ method really should be gone in Python 3.x, though I'm sure someone will find a use case that makes sense. If you need to use __del__, be aware of the basic limitations per http://docs.python.org/reference/datamodel.html:

  • __del__ is called when the garbage collector happens to be collecting the objects, not when you lose the last reference to an object and not when you execute del object.
  • __del__ is responsible for calling any __del__ in a superclass, though it is not clear if this is in method resolution order (MRO) or just calling each superclass.
  • Having a __del__ means that the garbage collector gives up on detecting and cleaning any cyclic links, such as losing the last reference to a linked list. You can get a list of the objects ignored from gc.garbage. You can sometimes use weak references to avoid the cycle altogether. This gets debated now and then: see http://mail.python.org/pipermail/python-ideas/2009-October/006194.html.
  • The __del__ function can cheat, saving a reference to an object, and stopping the garbage collection.
  • Exceptions explicitly raised in __del__ are ignored.
  • __del__ complements __new__ far more than __init__. This gets confusing. See http://www.algorithm.co.il/blogs/programming/python-gotchas-1-del-is-not-the-opposite-of-init/ for an explanation and gotchas.
  • __del__ is not a "well-loved" child in Python. You will notice that sys.exit() documentation does not specify if garbage is collected before exiting, and there are lots of odd issues. Calling the __del__ on globals causes odd ordering issues, e.g., http://bugs.python.org/issue5099. Should __del__ called even if the __init__ fails? See http://mail.python.org/pipermail/python-dev/2000-March/thread.html#2423 for a long thread.

But, on the other hand:

And my pesonal reason for not liking the __del__ function.

  • Everytime someone brings up __del__ it devolves into thirty messages of confusion.
  • It breaks these items in the Zen of Python:
    • Simple is better than complicated.
    • Special cases aren't special enough to break the rules.
    • Errors should never pass silently.
    • In the face of ambiguity, refuse the temptation to guess.
    • There should be one – and preferably only one – obvious way to do it.
    • If the implementation is hard to explain, it's a bad idea.

So, find a reason not to use __del__.

android image button

You can use the button :

1 - make the text empty

2 - set the background for it

+3 - you can use the selector to more useful and nice button


About the imagebutton you can set the image source and the background the same picture and it must be (*.png) when you do it you can make any design for the button

and for more beauty button use the selector //just Google it ;)

Converting milliseconds to a date (jQuery/JavaScript)

Assume the date as milliseconds date is 1526813885836, so you can access the date as string with this sample code:

console.log(new Date(1526813885836).toString());

For clearness see below code:

const theTime = new Date(1526813885836);
console.log(theTime.toString());

add title attribute from css

It is possible to imitate this with HTML & CSS

If you really really want dynamically applied tooltips to work, this (not so performance and architecture friendly) solution can allow you to use browser rendered tooltips without resorting to JS. I can imagine situations where this would be better than JS.

If you have a fixed subset of title attribute values, then you can generate additional elements server-side and let the browser read title from another element positioned above the original one using CSS.

Example:

_x000D_
_x000D_
div{_x000D_
  position: relative;_x000D_
}_x000D_
div > span{_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.pick-tooltip-1 > .tooltip-1, .pick-tooltip-2 > .tooltip-2{_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
}
_x000D_
<div class="pick-tooltip-1">_x000D_
  Hover to see first tooltip_x000D_
  <span class="tooltip-1" title="Tooltip 1"></span>_x000D_
  <span class="tooltip-2" title="Tooltip 2"></span>_x000D_
</div>_x000D_
_x000D_
<div class="pick-tooltip-2">_x000D_
  Hover to see second tooltip_x000D_
  <span class="tooltip-1" title="Tooltip 1"></span>_x000D_
  <span class="tooltip-2" title="Tooltip 2"></span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note: It's not recommended for large scale applications because of unnecessary HTML, possible content repetitions and the fact that your extra elements for tooltip would steal mouse events (text selection, etc)

Does Python have an ordered set?

As others have said, OrderedDict is a superset of an ordered set in terms of functionality, but if you need a set for interacting with an API and don't need it to be mutable, OrderedDict.keys() is actually an implementation abc.collections.Set:

import random
from collections import OrderedDict, abc

a = list(range(0, 100))
random.shuffle(a)

# True
a == list(OrderedDict((i, 0) for i in a).keys())

# True
isinstance(OrderedDict().keys(), abc.Set)   

The caveats are immutability and having to build up the set like a dict, but it's simple and only uses built-ins.

how to fetch array keys with jQuery?

you can use the each function:

var a = {};
a['alfa'] = 0;
a['beta'] = 1;
$.each(a, function(key, value) {
      alert(key)
});

it has several nice shortcuts/tricks: check the gory details here

How can I write these variables into one line of code in C#?

 DateTime dateTime = dateTime.Today.ToString("MM.dd.yyyy");

 Console.Write(dateTime);

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

I'm glad that worked out, so I guess you had to explicitly set 'auto' on IE6 in order for it to mimic other browsers!

I actually recently found another technique for scaling images, again designed for backgrounds. This technique has some interesting features:

  1. The image aspect ratio is preserved
  2. The image's original size is maintained (that is, it can never shrink only grow)

The markup relies on a wrapper element:

<div id="wrap"><img src="test.png" /></div>

Given the above markup you then use these rules:

#wrap {
  height: 100px;
  width: 100px;
}
#wrap img {
  min-height: 100%;
  min-width: 100%;
}

If you then control the size of wrapper you get the interesting scale effects that I list above.

To be explicit, consider the following base state: A container that is 100x100 and an image that is 10x10. The result is a scaled image of 100x100.

  1. Starting at the base state, the container resized to 20x100, the image stays resized at 100x100.
  2. Starting at the base state, the image is changed to 10x20, the image resizes to 100x200.

So, in other words, the image is always at least as big as the container, but will scale beyond it to maintain it's aspect ratio.

This probably isn't useful for your site, and it doesn't work in IE6. But, it is useful to get a scaled background for your view port or container.

LINQ Where with AND OR condition

Well, you're going to have to check for null somewhere. You could do something like this:

from item in db.vw_Dropship_OrderItems
         where (listStatus == null || listStatus.Contains(item.StatusCode)) 
            && (listMerchants == null || listMerchants.Contains(item.MerchantId))
         select item;

jQuery AutoComplete Trigger Change Event

Here is a relatively clean solution for others looking up this topic:

// run when eventlistener is triggered
$("#CompanyList").on( "autocompletechange", function(event,ui) {
   // post value to console for validation
   console.log($(this).val());
});

Per api.jqueryui.com/autocomplete/, this binds a function to the eventlistener. It is triggered both when the user selects a value from the autocomplete list and when they manually type in a value. The trigger fires when the field loses focus.

How to wrap text using CSS?

Try doing this. Works for IE8, FF3.6, Chrome

<body>
  <table>
    <tr>
      <td>
        <div style="word-wrap: break-word; width: 100px">gdfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg</div>
      </td>
    </tr>
  </table>
</body>

Fitting polynomial model to data in R

To get a third order polynomial in x (x^3), you can do

lm(y ~ x + I(x^2) + I(x^3))

or

lm(y ~ poly(x, 3, raw=TRUE))

You could fit a 10th order polynomial and get a near-perfect fit, but should you?

EDIT: poly(x, 3) is probably a better choice (see @hadley below).

Form/JavaScript not working on IE 11 with error DOM7011

I have seen exactly the same error, also with IE11. In my case the issue occurred when user clicked <button> element, which was inside <form> tags.

The issue was remedied, by placing the <button> outside of <form> tags.

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

For all the Kotlin users out there:

context?.let {
    val color = ContextCompat.getColor(it, R.color.colorPrimary)
    // ...
}

Matching a space in regex

In Perl the switch is \s (whitespace).

Removing duplicate rows from table in Oracle

Use the rowid pseudocolumn.

DELETE FROM your_table
WHERE rowid not in
(SELECT MIN(rowid)
FROM your_table
GROUP BY column1, column2, column3);

Where column1, column2, and column3 make up the identifying key for each record. You might list all your columns.

Inserting the same value multiple times when formatting a string

Depends on what you mean by better. This works if your goal is removal of redundancy.

s='foo'
string='%s bar baz %s bar baz %s bar baz' % (3*(s,))

Angular 2 Cannot find control with unspecified name attribute on formArrays

Remove the brackets from

[formArrayName]="areas" 

and use only

formArrayName="areas"

This, because with [ ] you are trying to bind a variable, which this is not. Also notice your submit, it should be:

(ngSubmit)="onSubmit(areasForm.value)"

instead of areasForm.values.

How to find nth occurrence of character in a string?

May be you could achieve this through String.split(..) method also.

String str = "";
String[] tokens = str.split("/")
return tokens[nthIndex] == null 

Using .Select and .Where in a single LINQ statement

Did you add the Select() after the Where() or before?

You should add it after, because of the concurrency logic:

 1 Take the entire table  
 2 Filter it accordingly  
 3 Select only the ID's  
 4 Make them distinct.  

If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.

Update: For clarity, this order of operators should work:

db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();

Probably want to add a .toList() at the end but that's optional :)

Disable a Maven plugin defined in a parent POM

The following works for me when disabling Findbugs in a child POM:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>findbugs-maven-plugin</artifactId>
    <executions>
        <execution>
            <id>ID_AS_IN_PARENT</id> <!-- id is necessary sometimes -->
            <phase>none</phase>
        </execution>
    </executions>
</plugin>

Note: the full definition of the Findbugs plugin is in our parent/super POM, so it'll inherit the version and so-on.

In Maven 3, you'll need to use:

 <configuration>
      <skip>true</skip>
 </configuration>

for the plugin.

Switch firefox to use a different DNS than what is in the windows.host file

I use this to override system's DNS with localserver
in about:config
change this value:

  • network.dns.forceResolve
  • network.dns.ipv4OnlyDomains
  • network.dns.localDomains
  • with IP address of local DNS server (for exsample 192.168.1.88)
    Sorry for my english

    Make flex items take content width, not width of parent container

    In addtion to align-self you can also consider auto margin which will do almost the same thing

    _x000D_
    _x000D_
    .container {_x000D_
      background: red;_x000D_
      height: 200px;_x000D_
      flex-direction: column;_x000D_
      padding: 10px;_x000D_
      display: flex;_x000D_
    }_x000D_
    a {_x000D_
      margin-right:auto;_x000D_
      padding: 10px 40px;_x000D_
      background: pink;_x000D_
    }
    _x000D_
    <div class="container">_x000D_
      <a href="#">Test</a>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Best way to access a control on another form in Windows Forms?

    This looks like a prime candidate for separating the presentation from the data model. In this case, your preferences should be stored in a separate class that fires event updates whenever a particular property changes (look into INotifyPropertyChanged if your properties are a discrete set, or into a single event if they are more free-form text-based keys).

    In your tree view, you'll make the changes to your preferences model, it will then fire an event. In your other forms, you'll subscribe to the changes that you're interested in. In the event handler you use to subscribe to the property changes, you use this.InvokeRequired to see if you are on the right thread to make the UI call, if not, then use this.BeginInvoke to call the desired method to update the form.

    angular.service vs angular.factory

    The factory pattern is more flexible as it can return functions and values as well as objects.

    There isn't a lot of point in the service pattern IMHO, as everything it does you can just as easily do with a factory. The exceptions might be:

    • If you care about the declared type of your instantiated service for some reason - if you use the service pattern, your constructor will be the type of the new service.
    • If you already have a constructor function that you're using elsewhere that you also want to use as a service (although probably not much use if you want to inject anything into it!).

    Arguably, the service pattern is a slightly nicer way to create a new object from a syntax point of view, but it's also more costly to instantiate. Others have indicated that angular uses "new" to create the service, but this isn't quite true - it isn't able to do that because every service constructor has a different number of parameters. What angular actually does is use the factory pattern internally to wrap your constructor function. Then it does some clever jiggery pokery to simulate javascript's "new" operator, invoking your constructor with a variable number of injectable arguments - but you can leave out this step if you just use the factory pattern directly, thus very slightly increasing the efficiency of your code.

    No tests found with test runner 'JUnit 4'

    Using ScalaIDE (3.0.4-2.11-20140723-2253-Typesafe) I was having a similar problem with the Right Click Scala Test Class-> Run As -> Scala Junit Test context menu.

    I tried editting the class(but not for a compile failure), cleaning, closing the project, closing Eclipse. None of those worked to restore the context menu for classes that had previously worked well. The test classes don't use the @Test annotation and instead use the @RunWith(classOf[JUnitRunner]) annotation at the top of the class using ScalaTest code.

    When I tried choosing Scala Junit Test from the Run Configuration launch editor directly, I received the dialog from the question. Footix29's answer was the key for me.

    I noticed that even though I had cleaned my project a few times, my classes in the /bin directory hadn't actually been rebuilt in a while.

    Here's how I got back the context menu, and was able to once again run Scala Junit Tests:

    • manually cleaned the classes by deleting the /bin/<package dir>* via Explorer
    • Project -> Cleaned the project along with a full rebuild

    I suspect that a class edit in general is able to clean some saved state of Eclipse and get it going again. In my case all of the previously working classes I tried had failed so the manual clean step was just the hammer I needed. However, other tricks that affect Eclipse's concept of the class path/build state should also work.

    Further, I think that this behaviour was triggered in part by attempting to refactor a Scala class by renaming it( which the Scala Eclipse IDE sucks at ), where all the cleanup after the initial file change is manual. There were no build errors, but there were also no warnings that I was expecting meaning something was definitely stuck in Eclipse's build state info.

    Who sets response content-type in Spring MVC (@ResponseBody)

    I set the content-type in the MarshallingView in the ContentNegotiatingViewResolver bean. It works easily, clean and smoothly:

    <property name="defaultViews">
      <list>
        <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
          <constructor-arg>
            <bean class="org.springframework.oxm.xstream.XStreamMarshaller" />     
          </constructor-arg>
          <property name="contentType" value="application/xml;charset=UTF-8" />
        </bean>
      </list>
    </property>
    

    How to load up CSS files using Javascript?

    use:

    document.getElementById("of head/body tag")
            .innerHTML += '<link rel="stylesheet" type="text/css" href="style.css">';
    

    How can I break up this long line in Python?

    That's a start. It's not a bad practice to define your longer strings outside of the code that uses them. It's a way to separate data and behavior. Your first option is to join string literals together implicitly by making them adjacent to one another:

    ("This is the first line of my text, "
    "which will be joined to a second.")
    

    Or with line ending continuations, which is a little more fragile, as this works:

    "This is the first line of my text, " \
    "which will be joined to a second."
    

    But this doesn't:

    "This is the first line of my text, " \ 
    "which will be joined to a second."
    

    See the difference? No? Well you won't when it's your code either.

    The downside to implicit joining is that it only works with string literals, not with strings taken from variables, so things can get a little more hairy when you refactor. Also, you can only interpolate formatting on the combined string as a whole.

    Alternatively, you can join explicitly using the concatenation operator (+):

    ("This is the first line of my text, " + 
    "which will be joined to a second.")
    

    Explicit is better than implicit, as the zen of python says, but this creates three strings instead of one, and uses twice as much memory: there are the two you have written, plus one which is the two of them joined together, so you have to know when to ignore the zen. The upside is you can apply formatting to any of the substrings separately on each line, or to the whole lot from outside the parentheses.

    Finally, you can use triple-quoted strings:

    """This is the first line of my text
    which will be joined to a second."""
    

    This is often my favorite, though its behavior is slightly different as the newline and any leading whitespace on subsequent lines will show up in your final string. You can eliminate the newline with an escaping backslash.

    """This is the first line of my text \
    which will be joined to a second."""
    

    This has the same problem as the same technique above, in that correct code only differs from incorrect code by invisible whitespace.

    Which one is "best" depends on your particular situation, but the answer is not simply aesthetic, but one of subtly different behaviors.

    Swift GET request with parameters

    When building a GET request, there is no body to the request, but rather everything goes on the URL. To build a URL (and properly percent escaping it), you can also use URLComponents.

    var url = URLComponents(string: "https://www.google.com/search/")!
    
    url.queryItems = [
        URLQueryItem(name: "q", value: "War & Peace")
    ]
    

    The only trick is that most web services need + character percent escaped (because they'll interpret that as a space character as dictated by the application/x-www-form-urlencoded specification). But URLComponents will not percent escape it. Apple contends that + is a valid character in a query and therefore shouldn't be escaped. Technically, they are correct, that it is allowed in a query of a URI, but it has a special meaning in application/x-www-form-urlencoded requests and really should not be passed unescaped.

    Apple acknowledges that we have to percent escaping the + characters, but advises that we do it manually:

    var url = URLComponents(string: "https://www.wolframalpha.com/input/")!
    
    url.queryItems = [
        URLQueryItem(name: "i", value: "1+2")
    ]
    
    url.percentEncodedQuery = url.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
    

    This is an inelegant work-around, but it works, and is what Apple advises if your queries may include a + character and you have a server that interprets them as spaces.

    So, combining that with your sendRequest routine, you end up with something like:

    func sendRequest(_ url: String, parameters: [String: String], completion: @escaping ([String: Any]?, Error?) -> Void) {
        var components = URLComponents(string: url)!
        components.queryItems = parameters.map { (key, value) in 
            URLQueryItem(name: key, value: value) 
        }
        components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
        let request = URLRequest(url: components.url!)
    
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data,                            // is there data
                let response = response as? HTTPURLResponse,  // is there HTTP response
                (200 ..< 300) ~= response.statusCode,         // is statusCode 2XX
                error == nil else {                           // was there no error, otherwise ...
                    completion(nil, error)
                    return
            }
    
            let responseObject = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
            completion(responseObject, nil)
        }
        task.resume()
    }
    

    And you'd call it like:

    sendRequest("someurl", parameters: ["foo": "bar"]) { responseObject, error in
        guard let responseObject = responseObject, error == nil else {
            print(error ?? "Unknown error")
            return
        }
    
        // use `responseObject` here
    }
    

    Personally, I'd use JSONDecoder nowadays and return a custom struct rather than a dictionary, but that's not really relevant here. Hopefully this illustrates the basic idea of how to percent encode the parameters into the URL of a GET request.


    See previous revision of this answer for Swift 2 and manual percent escaping renditions.

    Python JSON serialize a Decimal object

    For Django users:

    Recently came across TypeError: Decimal('2337.00') is not JSON serializable while JSON encoding i.e. json.dumps(data)

    Solution:

    # converts Decimal, Datetime, UUIDs to str for Encoding
    from django.core.serializers.json import DjangoJSONEncoder  
    
    json.dumps(response.data, cls=DjangoJSONEncoder)
    

    But, now the Decimal value will be a string, now we can explicitly set the decimal/float value parser when decoding data, using parse_float option in json.loads:

    import decimal 
    
    data = json.loads(data, parse_float=decimal.Decimal) # default is float(num_str)
    

    How to check if a string contains text from an array of substrings in JavaScript?

    You can check like this:

    <!DOCTYPE html>
    <html>
       <head>
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
          <script>
             $(document).ready(function(){
             var list = ["bad", "words", "include"] 
             var sentence = $("#comments_text").val()
    
             $.each(list, function( index, value ) {
               if (sentence.indexOf(value) > -1) {
                    console.log(value)
                }
             });
             });
          </script>
       </head>
       <body>
          <input id="comments_text" value="This is a bad, with include test"> 
       </body>
    </html>
    

    SQL Server - INNER JOIN WITH DISTINCT

    select distinct a.FirstName, a.LastName, v.District from AddTbl a inner join ValTbl v on a.LastName = v.LastName order by a.FirstName;

    hope this helps

    jQuery: outer html()

    No siblings solution:

    var x = $('#xxx').parent().html();
    alert(x);
    

    Universal solution:

    // no cloning necessary    
    var x = $('#xxx').wrapAll('<div>').parent().html(); 
    alert(x);
    

    Fiddle here: http://jsfiddle.net/ezmilhouse/Mv76a/

    Access denied for root user in MySQL command-line

    navigate do C:\xampp\mysql\bin\ and make sure the file mysql.exe is in that folder.

    mysql -uroot -p
    

    if dont have a password just press enter.

    the prompt changes to

    mysql>
    

    do your mysql commands

    Regex pattern including all special characters

    Try using this for the same things - StringUtils.isAlphanumeric(value)

    What is the default encoding of the JVM?

    To get default java settings just use :

    java -XshowSettings 
    

    Accessing items in an collections.OrderedDict by index

    It is dramatically more efficient to use IndexedOrderedDict from the indexed package.

    Following Niklas's comment, I have done a benchmark on OrderedDict and IndexedOrderedDict with 1000 entries.

    In [1]: from numpy import *
    In [2]: from indexed import IndexedOrderedDict
    In [3]: id=IndexedOrderedDict(zip(arange(1000),random.random(1000)))
    In [4]: timeit id.keys()[56]
    1000000 loops, best of 3: 969 ns per loop
    
    In [8]: from collections import OrderedDict
    In [9]: od=OrderedDict(zip(arange(1000),random.random(1000)))
    In [10]: timeit od.keys()[56]
    10000 loops, best of 3: 104 µs per loop
    

    IndexedOrderedDict is ~100 times faster in indexing elements at specific position in this specific case.

    how to get 2 digits after decimal point in tsql?

    DECLARE @i AS FLOAT = 2 SELECT @i / 3 SELECT cast(@i / cast(3 AS DECIMAL(18,2))as decimal (18,2))

    Both factor and result requires casting to be considered as decimals.

    how to make password textbox value visible when hover an icon

    In one line of code as below :

    _x000D_
    _x000D_
    <p> cursor on text field shows text .if not password will be shown</p>_x000D_
    <input type="password" name="txt_password" onmouseover="this.type='text'"_x000D_
           onmouseout="this.type='password'" placeholder="password" />
    _x000D_
    _x000D_
    _x000D_

    How to Select Every Row Where Column Value is NOT Distinct

    This is significantly faster than the EXISTS way:

    SELECT [EmailAddress], [CustomerName] FROM [Customers] WHERE [EmailAddress] IN
      (SELECT [EmailAddress] FROM [Customers] GROUP BY [EmailAddress] HAVING COUNT(*) > 1)
    

    mysql query result in php variable

    Of course there is. Check out mysql_query, and mysql_fetch_row if you use MySQL.
    Example from PHP manual:

    <?php
    $result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
    if (!$result) {
        echo 'Could not run query: ' . mysql_error();
        exit;
    }
    $row = mysql_fetch_row($result);
    
    echo $row[0]; // 42
    echo $row[1]; // the email value
    ?>
    

    How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds

    See https://www.eclipse.org/m2e/documentation/m2e-execution-not-covered.html .

    To solve some long-standing issues, m2e 1.0 requires explicit instructions what to do with all Maven plugins bound to "interesting" phases of project build lifecycle. We call these instructions "project build lifecycle mapping" or simply "lifecycle mapping" because they define how m2e maps information from project pom.xml file to Eclipse workspace project configuration and behaviour during Eclipse workspace build.

    Project build lifecycle mapping configuration can be specified in project pom.xml, contributed by Eclipse plugins and there is also default configuration for some commonly used Maven plugins shipped with m2e. We call these "lifecycle mapping metadata sources". m2e will create error marker like below for all plugin executions that do not have lifecycle mapping in any of the mapping metadata sources.

    Plugin execution not covered by lifecycle configuration:
    org.apache.maven.plugins:maven-antrun-plugin:1.3:run
       (execution: generate-sources-input, phase: generate-sources)
    

    m2e matches plugin executions to actions using combination of plugin groupId, artifactId, version range and goal. There are three basic actions that m2e can be instructed to do with a plugin execution -- ignore, execute and delegate to a project configurator.

    How to find the path of the local git repository when I am possibly in a subdirectory

    git rev-parse --show-toplevel
    

    could be enough if executed within a git repo.
    From git rev-parse man page:

    --show-toplevel
    

    Show the absolute path of the top-level directory.

    For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

    git rev-parse --git-dir
    

    That would give the path of the .git directory.


    The OP mentions:

    git rev-parse --show-prefix
    

    which returns the local path under the git repo root. (empty if you are at the git repo root)


    Note: for simply checking if one is in a git repo, I find the following command quite expressive:

    git rev-parse --is-inside-work-tree
    

    And yes, if you need to check if you are in a .git git-dir folder:

    git rev-parse --is-inside-git-dir
    

    How to post data in PHP using file_get_contents?

    Sending an HTTP POST request using file_get_contents is not that hard, actually : as you guessed, you have to use the $context parameter.


    There's an example given in the PHP manual, at this page : HTTP context options (quoting) :

    $postdata = http_build_query(
        array(
            'var1' => 'some content',
            'var2' => 'doh'
        )
    );
    
    $opts = array('http' =>
        array(
            'method'  => 'POST',
            'header'  => 'Content-Type: application/x-www-form-urlencoded',
            'content' => $postdata
        )
    );
    
    $context  = stream_context_create($opts);
    
    $result = file_get_contents('http://example.com/submit.php', false, $context);
    

    Basically, you have to create a stream, with the right options (there is a full list on that page), and use it as the third parameter to file_get_contents -- nothing more ;-)


    As a sidenote : generally speaking, to send HTTP POST requests, we tend to use curl, which provides a lot of options an all -- but streams are one of the nice things of PHP that nobody knows about... too bad...

    how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

    setText is changing the text content to exactly what you give it, not appending it.

    Convert the String from the field first, then apply it directly...

    String value = "This Is A Test";
    StringBuilder sb = new StringBuilder(value);
    for (int index = 0; index < sb.length(); index++) {
        char c = sb.charAt(index);
        if (Character.isLowerCase(c)) {
            sb.setCharAt(index, Character.toUpperCase(c));
        } else {
            sb.setCharAt(index, Character.toLowerCase(c));
        }
    }
    
    SecondTextField.setText(sb.toString());
    

    Where can I download Spring Framework jars without using Maven?

    Please edit to keep this list of mirrors current

    I found this maven repo where you could download from directly a zip file containing all the jars you need.

    Alternate solution: Maven

    The solution I prefer is using Maven, it is easy and you don't have to download each jar alone. You can do it with the following steps:

    1. Create an empty folder anywhere with any name you prefer, for example spring-source

    2. Create a new file named pom.xml

    3. Copy the xml below into this file

    4. Open the spring-source folder in your console

    5. Run mvn install

    6. After download finished, you'll find spring jars in /spring-source/target/dependencies

      <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>spring-source-download</groupId>
        <artifactId>SpringDependencies</artifactId>
        <version>1.0</version>
        <properties>
          <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        </properties>
        <dependencies>
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.2.4.RELEASE</version>
          </dependency>
        </dependencies>
        <build>
          <plugins>
            <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-dependency-plugin</artifactId>
              <version>2.8</version>
              <executions>
                <execution>
                  <id>download-dependencies</id>
                  <phase>generate-resources</phase>
                  <goals>
                    <goal>copy-dependencies</goal>
                  </goals>
                  <configuration>
                    <outputDirectory>${project.build.directory}/dependencies</outputDirectory>
                  </configuration>
                </execution>
              </executions>
            </plugin>
          </plugins>
        </build>
      </project>
      

    Also, if you need to download any other spring project, just copy the dependency configuration from its corresponding web page.

    For example, if you want to download Spring Web Flow jars, go to its web page, and add its dependency configuration to the pom.xml dependencies, then run mvn install again.

    <dependency>
      <groupId>org.springframework.webflow</groupId>
      <artifactId>spring-webflow</artifactId>
      <version>2.3.2.RELEASE</version>
    </dependency>
    

    How can I define colors as variables in CSS?

    You can try CSS3 variables:

    body {
      --fontColor: red;
      color: var(--fontColor);
    }
    

    Select <a> which href ends with some string

    Just in case you don't want to import a big library like jQuery to accomplish something this trivial, you can use the built-in method querySelectorAll instead. Almost all selector strings used for jQuery work with DOM methods as well:

    const anchors = document.querySelectorAll('a[href$="ABC"]');
    

    Or, if you know that there's only one matching element:

    const anchor = document.querySelector('a[href$="ABC"]');
    

    You may generally omit the quotes around the attribute value if the value you're searching for is alphanumeric, eg, here, you could also use

    a[href$=ABC]
    

    but quotes are more flexible and generally more reliable.

    What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

    If sudo make uninstall is unavailable:

    In a Debian based system, instead of (or after*) doing make install you can run sudo checkinstall to make a .deb file that gets automatically installed. You can then remove it using the system package manager (e.g. apt/synaptic/aptitude/dpkg). Checkinstall also supports creating other types of package, e.g. RPM.

    See also http://community.linuxmint.com/tutorial/view/162 and some basic checkinstall usage and debian checkinstall package.


    *: If you're reading this after having installed with make install you can still follow the above instructions and do a dpkg -r $PACKAGE_NAME_YOU_CHOSEN afterwards.

    How could I create a list in c++?

    You should really use the standard List class. Unless, of course, this is a homework question, or you want to know how lists are implemented by STL.

    You'll find plenty of simple tutorials via google, like this one. If you want to know how linked lists work "under the hood", try searching for C list examples/tutorials rather than C++.

    How can I get two form fields side-by-side, with each field’s label above the field, in CSS?

    You need an HTML element for each column in your layout.

    I’d suggest:

    HTML

    <div class="two-col">
        <div class="col1">
            <label for="field1">Field One:</label>
            <input id="field1" name="field1" type="text">
        </div>
    
        <div class="col2">
            <label for="field2">Field Two:</label>
            <input id="field2" name="field2" type="text">
        </div>
    </div>
    

    CSS

    .two-col {
        overflow: hidden;/* Makes this div contain its floats */
    }
    
    .two-col .col1,
    .two-col .col2 {
        width: 49%;
    }
    
    .two-col .col1 {
        float: left;
    }
    
    .two-col .col2 {
        float: right;
    }
    
    .two-col label {
        display: block;
    }
    

    How to sum columns in a dataTable?

    There is also a way to do this without loops using the DataTable.Compute Method. The following example comes from that page. You can see that the code used is pretty simple.:

    private void ComputeBySalesSalesID(DataSet dataSet)
    {
        // Presumes a DataTable named "Orders" that has a column named "Total."
        DataTable table;
        table = dataSet.Tables["Orders"];
    
        // Declare an object variable. 
        object sumObject;
        sumObject = table.Compute("Sum(Total)", "EmpID = 5");
    }
    

    I must add that if you do not need to filter the results, you can always pass an empty string:

    sumObject = table.Compute("Sum(Total)", "")
    

    how to create insert new nodes in JsonNode?

    I've recently found even more interesting way to create any ValueNode or ContainerNode (Jackson v2.3).

    ObjectNode node = JsonNodeFactory.instance.objectNode();
    

    Add Legend to Seaborn point plot

    Old question, but there's an easier way.

    sns.pointplot(x=x_col,y=y_col,data=df_1,color='blue')
    sns.pointplot(x=x_col,y=y_col,data=df_2,color='green')
    sns.pointplot(x=x_col,y=y_col,data=df_3,color='red')
    plt.legend(labels=['legendEntry1', 'legendEntry2', 'legendEntry3'])
    

    This lets you add the plots sequentially, and not have to worry about any of the matplotlib crap besides defining the legend items.

    Android - How to decode and decompile any APK file?

    To decompile APK Use APKTool.
    You can learn how APKTool works on http://www.decompileandroid.com/ or by reading the documentation.

    Convert UNIX epoch to Date object

    With library(lubridate), numeric representations of date and time saved as the number of seconds since 1970-01-01 00:00:00 UTC, can be coerced into dates with as_datetime():

    lubridate::as_datetime(1352068320)
    
    [1] "2012-11-04 22:32:00 UTC"
    

    How to create a simple http proxy in node.js?

    Super simple and readable, here's how you create a local proxy server to a local HTTP server with just Node.js (tested on v8.1.0). I've found it particular useful for integration testing so here's my share:

    /**
     * Once this is running open your browser and hit http://localhost
     * You'll see that the request hits the proxy and you get the HTML back
     */
    
    'use strict';
    
    const net = require('net');
    const http = require('http');
    
    const PROXY_PORT = 80;
    const HTTP_SERVER_PORT = 8080;
    
    let proxy = net.createServer(socket => {
        socket.on('data', message => {
            console.log('---PROXY- got message', message.toString());
    
            let serviceSocket = new net.Socket();
    
            serviceSocket.connect(HTTP_SERVER_PORT, 'localhost', () => {
                console.log('---PROXY- Sending message to server');
                serviceSocket.write(message);
            });
    
            serviceSocket.on('data', data => {
                console.log('---PROXY- Receiving message from server', data.toString();
                socket.write(data);
            });
        });
    });
    
    let httpServer = http.createServer((req, res) => {
        switch (req.url) {
            case '/':
                res.writeHead(200, {'Content-Type': 'text/html'});
                res.end('<html><body><p>Ciao!</p></body></html>');
                break;
            default:
                res.writeHead(404, {'Content-Type': 'text/plain'});
                res.end('404 Not Found');
        }
    });
    
    proxy.listen(PROXY_PORT);
    httpServer.listen(HTTP_SERVER_PORT);
    

    https://gist.github.com/fracasula/d15ae925835c636a5672311ef584b999

    How to get all elements which name starts with some string?

    You can use getElementsByName("input") to get a collection of all the inputs on the page. Then loop through the collection, checking the name on the way. Something like this:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset=utf-8 />
    <title>JS Bin</title>
    
    </head>
    <body>
    
      <input name="q1_a" type="text" value="1A"/>
      <input name="q1_b" type="text" value="1B"/>
      <input name="q1_c" type="text" value="1C"/>
      <input name="q2_d" type="text" value="2D"/>
    
      <script type="text/javascript">
      var inputs = document.getElementsByTagName("input");
      for (x = 0 ; x < inputs.length ; x++){
        myname = inputs[x].getAttribute("name");
        if(myname.indexOf("q1_")==0){
          alert(myname);
          // do more stuff here
           }
        }
        </script>
    </body>
    </html>
    

    Demo

    How to set the allowed url length for a nginx request (error code: 414, uri too large)

    From: http://nginx.org/r/large_client_header_buffers

    Syntax: large_client_header_buffers number size ;
    Default: large_client_header_buffers 4 8k;
    Context: http, server

    Sets the maximum number and size of buffers used for reading large client request header. A request line cannot exceed the size of one buffer, or the 414 (Request-URI Too Large) error is returned to the client. A request header field cannot exceed the size of one buffer as well, or the 400 (Bad Request) error is returned to the client. Buffers are allocated only on demand. By default, the buffer size is equal to 8K bytes. If after the end of request processing a connection is transitioned into the keep-alive state, these buffers are released.

    so you need to change the size parameter at the end of that line to something bigger for your needs.

    How can I roll back my last delete command in MySQL?

    I also had deleted some values from my development database, but I had the same copy in QA database, so I did a generate script and selected option "type of data to script" to "data only" and selected my table.

    Then I got the insert statements with same data, and then I run the script on my development database.

    Android: Cancel Async Task

    create some member variables in your activity like

    YourAsyncTask mTask;
    Dialog mDialog;
    

    use these for your dialog and task;

    in onPause() simply call

    if(mTask!=null) mTask.cancel(); 
    if(mDialog!=null) mDialog.dismiss();
    

    Multiple models in a view

    My advice is to make a big view model:

    public BigViewModel
    {
        public LoginViewModel LoginViewModel{get; set;}
        public RegisterViewModel RegisterViewModel {get; set;}
    }
    

    In your Index.cshtml, if for example you have 2 partials:

    @addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers
    @model .BigViewModel
    
    @await Html.PartialAsync("_LoginViewPartial", Model.LoginViewModel)
    
    @await Html.PartialAsync("_RegisterViewPartial ", Model.RegisterViewModel )
    

    and in controller:

    model=new BigViewModel();
    model.LoginViewModel=new LoginViewModel();
    model.RegisterViewModel=new RegisterViewModel(); 
    

    How to filter WooCommerce products by custom attribute

    A plugin is probably your best option. Look in the wordpress plugins directory or google to see if you can find one. I found the one below and that seemed to work perfect.

    https://wordpress.org/plugins/woocommerce-products-filter/

    This one seems to do exactly what you are after

    Changing position of the Dialog on screen android

    I used this code to show the dialog at the bottom of the screen:

    Dialog dlg = <code to create custom dialog>;
    
    Window window = dlg.getWindow();
    WindowManager.LayoutParams wlp = window.getAttributes();
    
    wlp.gravity = Gravity.BOTTOM;
    wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
    window.setAttributes(wlp);
    

    This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


    private void showPictureialog() {
        final Dialog dialog = new Dialog(this,
                android.R.style.Theme_Translucent_NoTitleBar);
    
        // Setting dialogview
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
    
        window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        dialog.setTitle(null);
        dialog.setContentView(R.layout.selectpic_dialog);
        dialog.setCancelable(true);
    
        dialog.show();
    }
    

    you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

    How to start anonymous thread class

    The entire new expression is an object reference, so methods can be invoked on it:

    public class A {
        public static void main(String[] arg)
        {
            new Thread()
            {
                public void run() {
                    System.out.println("blah");
                }
            }.start();
        }
    }
    

    JSON Java 8 LocalDateTime format in Spring Boot

    1) Dependency

     compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: '2.8.8' 
    

    2) Annotation with date-time format.

    public class RestObject {
    
        private LocalDateTime timestamp;
    
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        public LocalDateTime getTimestamp() {
            return timestamp;
        }
    }
    

    3) Spring Config.

    @Configuration
    public class JacksonConfig {
    
        @Bean
        @Primary
        public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
            System.out.println("Config is starting.");
            ObjectMapper objectMapper = builder.createXmlMapper(false).build();
            objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
            return objectMapper;
        }
    }
    

    How do I POST urlencoded form data with $http without jQuery?

    I think you need to do is to transform your data from object not to JSON string, but to url params.

    From Ben Nadel's blog.

    By default, the $http service will transform the outgoing request by serializing the data as JSON and then posting it with the content- type, "application/json". When we want to post the value as a FORM post, we need to change the serialization algorithm and post the data with the content-type, "application/x-www-form-urlencoded".

    Example from here.

    $http({
        method: 'POST',
        url: url,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        transformRequest: function(obj) {
            var str = [];
            for(var p in obj)
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
            return str.join("&");
        },
        data: {username: $scope.userName, password: $scope.password}
    }).then(function () {});
    

    UPDATE

    To use new services added with AngularJS V1.4, see

    Moment.js: Date between dates

    I do believe that

    if (startDate <= date && date <= endDate) {
      alert("Yay");
    } else {
      alert("Nay! :("); 
    }
    

    works too...

    How do you find out the caller function in JavaScript?

    Note you can't use Function.caller in Node.js, use caller-id package instead. For example:

    var callerId = require('caller-id');
    
    function foo() {
        bar();
    }
    function bar() {
        var caller = callerId.getData();
        /*
        caller = {
            typeName: 'Object',
            functionName: 'foo',
            filePath: '/path/of/this/file.js',
            lineNumber: 5,
            topLevelFlag: true,
            nativeFlag: false,
            evalFlag: false
        }
        */
    }
    

    Could not load file or assembly 'System.Net.Http.Formatting' or one of its dependencies. The system cannot find the path specified

    Whenever I have a NuGet error such as these I usually take these steps:

    1. Go to the packages folder in the Windows Explorer and delete it.
    2. Open Visual Studio and Go to Tools > Library Package Manager > Package Manager Settings and under the Package Manager item on the left hand side there is a "Clear Package Cache" button. Click this button and make sure that the check box for "Allow NuGet to download missing packages during build" is checked.
    3. Clean the solution
    4. Then right click the solution in the Solution Explorer and enable NuGet Package Restore
    5. Build the solution
    6. Restart Visual Studio

    Taking all of these steps almost always restores all the packages and dll's I need for my MVC program.


    EDIT >>>

    For Visual Studio 2013 and above, step 2) should read:

    1. Open Visual Studio and go to Tools > Options > NuGet Package Manager and on the right hand side there is a "Clear Package Cache button". Click this button and make sure that the check boxes for "Allow NuGet to download missing packages" and "Automatically check for missing packages during build in Visual Studio" are checked.

    Django - Did you forget to register or load this tag?

    In gameprofile.html please change the tag {% endblock content %} to {% endblock %} then it works otherwise django will not load the endblock and give error.

    "Missing return statement" within if / for / while

    Any how myMethod() should return a String value .what if your condition is false is myMethod return anything? ans is no so you need to define return null or some string value in false condition

    public String myMethod() {
        boolean c=true;
        if (conditions) {
            return "d";
        }
        return null;//or some other string value
    }
    

    Remove columns from dataframe where ALL values are NA

    I hope this may also help. It could be made into a single command, but I found it easier for me to read by dividing it in two commands. I made a function with the following instruction and worked lightning fast.

    naColsRemoval = function (DataTable) { na.cols = DataTable [ , .( which ( apply ( is.na ( .SD ) , 2 , all ) ) )] DataTable [ , unlist (na.cols) := NULL , with = F] }

    .SD will allow to limit the verification to part of the table, if you wish, but it will take the whole table as

    Detect if value is number in MySQL

    you can do using CAST

      SELECT * from tbl where col1 = concat(cast(col1 as decimal), "")
    

    using stored procedure in entity framework

    Simple. Just instantiate your entity, set it to an object and pass it to your view in your controller.

    enter image description here

    Entity

    VehicleInfoEntities db = new VehicleInfoEntities();

    Stored Procedure

    dbo.prcGetMakes()

    or

    you can add any parameters in your stored procedure inside the brackets ()

    dbo.prcGetMakes("BMW")

    Controller

    public class HomeController : Controller
    {
        VehicleInfoEntities db = new VehicleInfoEntities();
    
        public ActionResult Index()
        {
            var makes = db.prcGetMakes(null);
    
            return View(makes);
        }
    }
    

    How to parse a JSON string to an array using Jackson

    I finally got it:

    ObjectMapper objectMapper = new ObjectMapper();
    TypeFactory typeFactory = objectMapper.getTypeFactory();
    List<SomeClass> someClassList = objectMapper.readValue(jsonString, typeFactory.constructCollectionType(List.class, SomeClass.class));
    

    How does the Spring @ResponseBody annotation work?

    The first basic thing to understand is the difference in architectures.

    One end you have the MVC architecture, which is based on your normal web app, using web pages, and the browser makes a request for a page:

    Browser <---> Controller <---> Model
                   |      |
                   +-View-+
    

    The browser makes a request, the controller (@Controller) gets the model (@Entity), and creates the view (JSP) from the model and the view is returned back to the client. This is the basic web app architecture.

    On the other end, you have a RESTful architecture. In this case, there is no View. The Controller only sends back the model (or resource representation, in more RESTful terms). The client can be a JavaScript application, a Java server application, any application in which we expose our REST API to. With this architecture, the client decides what to do with this model. Take for instance Twitter. Twitter as the Web (REST) API, that allows our applications to use its API to get such things as status updates, so that we can use it to put that data in our application. That data will come in some format like JSON.

    That being said, when working with Spring MVC, it was first built to handle the basic web application architecture. There are may different method signature flavors that allow a view to be produced from our methods. The method could return a ModelAndView where we explicitly create it, or there are implicit ways where we can return some arbitrary object that gets set into model attributes. But either way, somewhere along the request-response cycle, there will be a view produced.

    But when we use @ResponseBody, we are saying that we do not want a view produced. We just want to send the return object as the body, in whatever format we specify. We wouldn't want it to be a serialized Java object (though possible). So yes, it needs to be converted to some other common type (this type is normally dealt with through content negotiation - see link below). Honestly, I don't work much with Spring, though I dabble with it here and there. Normally, I use

    @RequestMapping(..., produces = MediaType.APPLICATION_JSON_VALUE)
    

    to set the content type, but maybe JSON is the default. Don't quote me, but if you are getting JSON, and you haven't specified the produces, then maybe it is the default. JSON is not the only format. For instance, the above could easily be sent in XML, but you would need to have the produces to MediaType.APPLICATION_XML_VALUE and I believe you need to configure the HttpMessageConverter for JAXB. As for the JSON MappingJacksonHttpMessageConverter configured, when we have Jackson on the classpath.

    I would take some time to learn about Content Negotiation. It's a very important part of REST. It'll help you learn about the different response formats and how to map them to your methods.

    Pandas left outer join multiple dataframes on multiple columns

    Merge them in two steps, df1 and df2 first, and then the result of that to df3.

    In [33]: s1 = pd.merge(df1, df2, how='left', on=['Year', 'Week', 'Colour'])
    

    I dropped year from df3 since you don't need it for the last join.

    In [39]: df = pd.merge(s1, df3[['Week', 'Colour', 'Val3']],
                           how='left', on=['Week', 'Colour'])
    
    In [40]: df
    Out[40]: 
       Year Week Colour  Val1  Val2 Val3
    0  2014    A    Red    50   NaN  NaN
    1  2014    B    Red    60   NaN   60
    2  2014    B  Black    70   100   10
    3  2014    C    Red    10    20  NaN
    4  2014    D  Green    20   NaN   20
    
    [5 rows x 6 columns]
    

    Why do I need to explicitly push a new branch?

    The actual reason is that, in a new repo (git init), there is no branch (no master, no branch at all, zero branches)

    So when you are pushing for the first time to an empty upstream repo (generally a bare one), that upstream repo has no branch of the same name.

    And:

    In both cases, since the upstream empty repo has no branch:

    • there is no matching named branch yet
    • there is no upstream branch at all (with or without the same name! Tracking or not)

    That means your local first push has no idea:

    • where to push
    • what to push (since it cannot find any upstream branch being either recorded as a remote tracking branch, and/or having the same name)

    So you need at least to do a:

    git push origin master
    

    But if you do only that, you:

    • will create an upstream master branch on the upstream (now non-empty repo): good.
    • won't record that the local branch 'master' needs to be pushed to upstream (origin) 'master' (upstream branch): bad.

    That is why it is recommended, for the first push, to do a:

    git push -u origin master
    

    That will record origin/master as a remote tracking branch, and will enable the next push to automatically push master to origin/master.

    git checkout master
    git push
    

    And that will work too with push policies 'current' or 'upstream'.
    In each case, after the initial git push -u origin master, a simple git push will be enough to continue pushing master to the right upstream branch.

    jQuery UI - Close Dialog When Clicked Outside

    The given example(s) use one dialog with id '#dialog', i needed a solution that close any dialog:

    $.extend($.ui.dialog.prototype.options, {
        modal: true,
        open: function(object) {
            jQuery('.ui-widget-overlay').bind('click', function() {              
                var id = jQuery(object.target).attr('id');
                jQuery('#'+id).dialog('close');
            })
        }
    });
    

    Thanks to my colleague Youri Arkesteijn for the suggestion of using prototype.

    ggplot combining two plots from different data.frames

    The only working solution for me, was to define the data object in the geom_line instead of the base object, ggplot.

    Like this:

    ggplot() + 
    geom_line(data=Data1, aes(x=A, y=B), color='green') + 
    geom_line(data=Data2, aes(x=C, y=D), color='red')
    

    instead of

    ggplot(data=Data1, aes(x=A, y=B), color='green') + 
    geom_line() + 
    geom_line(data=Data2, aes(x=C, y=D), color='red')
    

    More info here