Programs & Examples On #Database template

How do I create a readable diff of two spreadsheets using git diff?

I don't know of any tools, but there are two roll-your-own solutions that come to mind, both require Excel:

  1. You could write some VBA code that steps through each Worksheet, Row, Column and Cell of the two Workbooks, reporting differences.

  2. If you use Excel 2007, you could save the Workbooks as Open-XML (*.xlsx) format, extract the XML and diff that. The Open-XML file is essentially just a .zip file of .xml files and manifests.

You'll end up with a lot of "noise" in either case if your spreadsheets aren't structurally "close" to begin with.

Regex to replace multiple spaces with a single space

I know we have to use regex, but during an interview, I was asked to do WITHOUT USING REGEX.

@slightlytyler helped me in coming with the below approach.

_x000D_
_x000D_
const testStr = "I   LOVE    STACKOVERFLOW   LOL";_x000D_
_x000D_
const removeSpaces = str  => {_x000D_
  const chars = str.split('');_x000D_
  const nextChars = chars.reduce(_x000D_
    (acc, c) => {_x000D_
      if (c === ' ') {_x000D_
        const lastChar = acc[acc.length - 1];_x000D_
        if (lastChar === ' ') {_x000D_
          return acc;_x000D_
        }_x000D_
      }_x000D_
      return [...acc, c];_x000D_
    },_x000D_
    [],_x000D_
  );_x000D_
  const nextStr = nextChars.join('');_x000D_
  return nextStr_x000D_
};_x000D_
_x000D_
console.log(removeSpaces(testStr));
_x000D_
_x000D_
_x000D_

remove empty lines from text file with PowerShell

I found a nice one liner here >> http://www.pixelchef.net/remove-empty-lines-file-powershell. Just tested it out with several blanks lines including newlines only as well as lines with just spaces, just tabs, and combinations.

(gc file.txt) | ? {$_.trim() -ne "" } | set-content file.txt

See the original for some notes about the code. Nice :)

How to convert index of a pandas dataframe into a column?

A very simple way of doing this is to use reset_index() method.For a data frame df use the code below:

df.reset_index(inplace=True)

This way, the index will become a column, and by using inplace as True,this become permanent change.

How to properly apply a lambda function into a pandas data frame column

You need mask:

sample['PR'] = sample['PR'].mask(sample['PR'] < 90, np.nan)

Another solution with loc and boolean indexing:

sample.loc[sample['PR'] < 90, 'PR'] = np.nan

Sample:

import pandas as pd
import numpy as np

sample = pd.DataFrame({'PR':[10,100,40] })
print (sample)
    PR
0   10
1  100
2   40

sample['PR'] = sample['PR'].mask(sample['PR'] < 90, np.nan)
print (sample)
      PR
0    NaN
1  100.0
2    NaN
sample.loc[sample['PR'] < 90, 'PR'] = np.nan
print (sample)
      PR
0    NaN
1  100.0
2    NaN

EDIT:

Solution with apply:

sample['PR'] = sample['PR'].apply(lambda x: np.nan if x < 90 else x)

Timings len(df)=300k:

sample = pd.concat([sample]*100000).reset_index(drop=True)

In [853]: %timeit sample['PR'].apply(lambda x: np.nan if x < 90 else x)
10 loops, best of 3: 102 ms per loop

In [854]: %timeit sample['PR'].mask(sample['PR'] < 90, np.nan)
The slowest run took 4.28 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 3.71 ms per loop

Python read JSON file and modify

There is really quite a number of ways to do this and all of the above are in one way or another valid approaches... Let me add a straightforward proposition. So assuming your current existing json file looks is this....

{
     "name":"myname"
}

And you want to bring in this new json content (adding key "id")

{
     "id": "134",
     "name": "myname"
 }

My approach has always been to keep the code extremely readable with easily traceable logic. So first, we read the entire existing json file into memory, assuming you are very well aware of your json's existing key(s).

import json 

# first, get the absolute path to json file
PATH_TO_JSON = 'data.json' #  assuming same directory (but you can work your magic here with os.)

# read existing json to memory. you do this to preserve whatever existing data. 
with open(PATH_TO_JSON,'r') as jsonfile:
    json_content = json.load(jsonfile) # this is now in memory! you can use it outside 'open'

Next, we use the 'with open()' syntax again, with the 'w' option. 'w' is a write mode which lets us edit and write new information to the file. Here s the catch that works for us ::: any existing json with the same target write name will be erased automatically.

So what we can do now, is simply write to the same filename with the new data

# add the id key-value pair (rmbr that it already has the "name" key value)
json_content["id"] = "134"

with open(PATH_TO_JSON,'w') as jsonfile:
    json.dump(json_content, jsonfile, indent=4) # you decide the indentation level

And there you go! data.json should be good to go for an good old POST request

How to synchronize or lock upon variables in Java?

Use the synchronized keyword.

class sample {
    private String msg=null;

    public synchronized void newmsg(String x){
        msg=x;
    }

    public synchronized string getmsg(){
        String temp=msg;
        msg=null;
        return msg;
    }
}

Using the synchronized keyword on the methods will require threads to obtain a lock on the instance of sample. Thus, if any one thread is in newmsg(), no other thread will be able to get a lock on the instance of sample, even if it were trying to invoke getmsg().

On the other hand, using synchronized methods can become a bottleneck if your methods perform long-running operations - all threads, even if they want to invoke other methods in that object that could be interleaved, will still have to wait.

IMO, in your simple example, it's ok to use synchronized methods since you actually have two methods that should not be interleaved. However, under different circumstances, it might make more sense to have a lock object to synchronize on, as shown in Joh Skeet's answer.

How Big can a Python List Get?

In casual code I've created lists with millions of elements. I believe that Python's implementation of lists are only bound by the amount of memory on your system.

In addition, the list methods / functions should continue to work despite the size of the list.

If you care about performance, it might be worthwhile to look into a library such as NumPy.

target input by type and name (selector)

You want a multiple attribute selector

$("input[type='checkbox'][name='ProductCode']").each(function(){ ...

or

$("input:checkbox[name='ProductCode']").each(function(){ ...

It would be better to use a CSS class to identify those that you want to select however as a lot of the modern browsers implement the document.getElementsByClassName method which will be used to select elements and be much faster than selecting by the name attribute

How to install PostgreSQL's pg gem on Ubuntu?

For .RVM users it will be better:

rvmsudo gem install pg -- --with-pg-lib=/usr/lib 

it worked for me (after i saw jdupont version)

Run chrome in fullscreen mode on Windows

It's very easy.

"your chrome path" -kiosk -fullscreen "your URL"

Example:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -kiosk -fullscreen http://google.com

Close all Chrome sessions first !

To exit: Press ALT-TAB > hold ALT and press X in the windows task. (win10)

Open a PDF using VBA in Excel

If it's a matter of just opening PDF to send some keys to it then why not try this

Sub Sample()
    ActiveWorkbook.FollowHyperlink "C:\MyFile.pdf"
End Sub

I am assuming that you have some pdf reader installed.

Input type DateTime - Value format?

That one shows up correctly as HTML5-Tag for those looking for this:

<input type="datetime" name="somedatafield" value="2011-12-21T11:33:23Z" />

In log4j, does checking isDebugEnabled before logging improve performance?

In Java 8, you don't have to use isDebugEnabled() to improve the performance.

https://logging.apache.org/log4j/2.0/manual/api.html#Java_8_lambda_support_for_lazy_logging

import java.util.logging.Logger;
...
Logger.getLogger("hello").info(() -> "Hello " + name);

Resource leak: 'in' is never closed

private static Scanner in;

I fixed it by declaring in as a private static Scanner class variable. Not sure why that fixed it but that is what eclipse recommended I do.

CSS: background-color only inside the margin

I needed something similar, and came up with using the :before (or :after) pseudoclasses:

#mydiv {
   background-color: #fbb;
   margin-top: 100px;
   position: relative;
}
#mydiv:before {
   content: "";
   background-color: #bfb;
   top: -100px;
   height: 100px;
   width: 100%;
   position: absolute;
}

JSFiddle

How to sort an array of integers correctly

TypeScript variant

const compareNumbers = (a: number, b: number): number => a - b

myArray.sort(compareNumbers)

What does Html.HiddenFor do?

Like a lot of functions, this one can be used in many different ways to solve many different problems, I think of it as yet another tool in our toolbelts.

So far, the discussion has focused heavily on simply hiding an ID, but that is only one value, why not use it for lots of values! That is what I am doing, I use it to load up the values in a class only one view at a time, because html.beginform creates a new object and if your model object for that view already had some values passed to it, those values will be lost unless you provide a reference to those values in the beginform.

To see a great motivation for the html.hiddenfor, I recommend you see Passing data from a View to a Controller in .NET MVC - "@model" not highlighting

jQuery `.is(":visible")` not working in Chrome

Generally i live this situation when parent of my object is hidden. for example when the html is like this:

    <div class="div-parent" style="display:none">
        <div class="div-child" style="display:block">
        </div>
    </div>

if you ask if child is visible like:

    $(".div-child").is(":visible");

it will return false because its parent is not visible so that div wont be visible, also.

Format decimal for percentage values?

This code may help you:

double d = double.Parse(input_value);
string output= d.ToString("F2", CultureInfo.InvariantCulture) + "%";

How do I use vim registers?

My friend Brian wrote a comprehensive article on this. I think it is a great intro to how to use topics. https://www.brianstorti.com/vim-registers/

Is there an "if -then - else " statement in XPath?

Unfortunately the previous answers were no option for me so i researched for a while and found this solution:

http://blog.alessio.marchetti.name/post/2011/02/12/the-Oliver-Becker-s-XPath-method

I use it to output text if a certain Node exists. 4 is the length of the text foo. So i guess a more elegant solution would be the use of a variable.

substring('foo',number(not(normalize-space(/elements/the/element/)))*4)

Getting current directory in .NET web application

The current directory is a system-level feature; it returns the directory that the server was launched from. It has nothing to do with the website.

You want HttpRuntime.AppDomainAppPath.

If you're in an HTTP request, you can also call Server.MapPath("~/Whatever").

Why this "Implicit declaration of function 'X'"?

summation and your other functions are defined after they're used in main, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.

You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.

Either move the function bodies before main, or include method signatures before main, e.g.:

#include <stdio.h>

int summation(int *, int *, int *);

int main()
{
    // ...

Fastest way to check if string contains only digits

The char already has an IsDigit(char c) which does this:

 public static bool IsDigit(char c)
    {
      if (!char.IsLatin1(c))
        return CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber;
      if ((int) c >= 48)
        return (int) c <= 57;
      else
        return false;
    }

You can simply do this:

var theString = "839278";
bool digitsOnly = theString.All(char.IsDigit);

Combine two or more columns in a dataframe into a new column with a new name

For inserting a separator:

df$x <- paste(df$n, "-", df$s)

Indentation shortcuts in Visual Studio

Visual studio’s smart indenting does automatically indenting, but we can select a block or all the code for indentation.

  1. Select all the code: Ctrl+a

  2. Use either of the two ways to indentation the code:

    • Shift+Tab,

    • Ctrl+k+f.

Get the cell value of a GridView row

Windows Form Iteration Technique

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (row.Selected)
    {
        foreach (DataGridViewCell cell in row.Cells)
        {
            int index = cell.ColumnIndex;
            if (index == 0)
            {
                value = cell.Value.ToString();
                //do what you want with the value
            }
        }
    }
}

How can I get list of values from dict?

Yes it's the exact same thing in Python 2:

d.values()

In Python 3 (where dict.values returns a view of the dictionary’s values instead):

list(d.values())

Combining paste() and expression() functions in plot labels

EDIT: added a new example for ggplot2 at the end

See ?plotmath for the different mathematical operations in R

You should be able to use expression without paste. If you use the tilda (~) symbol within the expression function it will assume there is a space between the characters, or you could use the * symbol and it won't put a space between the arguments

Sometimes you will need to change the margins in you're putting superscripts on the y-axis.

par(mar=c(5, 4.3, 4, 2) + 0.1)
plot(1:10, xlab = expression(xLab ~ x^2 ~ m^-2),
     ylab = expression(yLab ~ y^2 ~ m^-2),
     main="Plot 1")

enter image description here

plot(1:10, xlab = expression(xLab * x^2 * m^-2),
     ylab = expression(yLab * y^2 * m^-2),
     main="Plot 2")

enter image description here

plot(1:10, xlab = expression(xLab ~ x^2 * m^-2),
     ylab = expression(yLab ~ y^2 * m^-2),
     main="Plot 3")

enter image description here

Hopefully you can see the differences between plots 1, 2 and 3 with the different uses of the ~ and * symbols. An extra note, you can use other symbols such as plotting the degree symbol for temperatures for or mu, phi. If you want to add a subscript use the square brackets.

plot(1:10, xlab = expression('Your x label' ~ mu[3] * phi),
     ylab = expression("Temperature (" * degree * C *")"))

enter image description here

Here is a ggplot example using expression with a nonsense example

require(ggplot2)

Or if you have the pacman library installed you can use p_load to automatically download and load and attach add-on packages

# require(pacman)
# p_load(ggplot2)

data = data.frame(x = 1:10, y = 1:10)

ggplot(data, aes(x,y)) + geom_point() + 
  xlab(expression(bar(yourUnits) ~ g ~ m^-2 ~ OR ~ integral(f(x)*dx, a,b))) + 
  ylab(expression("Biomass (g per" ~ m^3 *")")) + theme_bw()

enter image description here

How to get absolute path to file in /resources folder of your project

The proper way that actually works:

URL resource = YourClass.class.getResource("abc");
Paths.get(resource.toURI()).toFile();

It doesn't matter now where the file in the classpath physically is, it will be found as long as the resource is actually a file and not a JAR entry.

(The seemingly obvious new File(resource.getPath()) doesn't work for all paths! The path is still URL-encoded!)

Why do I keep getting Delete 'cr' [prettier/prettier]?

I upgraded to "prettier": "^2.2.0" and error went away

How to include another XHTML in XHTML using JSF 2.0 Facelets?

<ui:include>

Most basic way is <ui:include>. The included content must be placed inside <ui:composition>.

Kickoff example of the master page /page.xhtml:

<!DOCTYPE html>
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h:head>
        <title>Include demo</title>
    </h:head>
    <h:body>
        <h1>Master page</h1>
        <p>Master page blah blah lorem ipsum</p>
        <ui:include src="/WEB-INF/include.xhtml" />
    </h:body>
</html>

The include page /WEB-INF/include.xhtml (yes, this is the file in its entirety, any tags outside <ui:composition> are unnecessary as they are ignored by Facelets anyway):

<ui:composition 
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h2>Include page</h2>
    <p>Include page blah blah lorem ipsum</p>
</ui:composition>
  

This needs to be opened by /page.xhtml. Do note that you don't need to repeat <html>, <h:head> and <h:body> inside the include file as that would otherwise result in invalid HTML.

You can use a dynamic EL expression in <ui:include src>. See also How to ajax-refresh dynamic include content by navigation menu? (JSF SPA).


<ui:define>/<ui:insert>

A more advanced way of including is templating. This includes basically the other way round. The master template page should use <ui:insert> to declare places to insert defined template content. The template client page which is using the master template page should use <ui:define> to define the template content which is to be inserted.

Master template page /WEB-INF/template.xhtml (as a design hint: the header, menu and footer can in turn even be <ui:include> files):

<!DOCTYPE html>
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h:head>
        <title><ui:insert name="title">Default title</ui:insert></title>
    </h:head>
    <h:body>
        <div id="header">Header</div>
        <div id="menu">Menu</div>
        <div id="content"><ui:insert name="content">Default content</ui:insert></div>
        <div id="footer">Footer</div>
    </h:body>
</html>

Template client page /page.xhtml (note the template attribute; also here, this is the file in its entirety):

<ui:composition template="/WEB-INF/template.xhtml"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">

    <ui:define name="title">
        New page title here
    </ui:define>

    <ui:define name="content">
        <h1>New content here</h1>
        <p>Blah blah</p>
    </ui:define>
</ui:composition>

This needs to be opened by /page.xhtml. If there is no <ui:define>, then the default content inside <ui:insert> will be displayed instead, if any.


<ui:param>

You can pass parameters to <ui:include> or <ui:composition template> by <ui:param>.

<ui:include ...>
    <ui:param name="foo" value="#{bean.foo}" />
</ui:include>
<ui:composition template="...">
    <ui:param name="foo" value="#{bean.foo}" />
    ...
</ui:composition >

Inside the include/template file, it'll be available as #{foo}. In case you need to pass "many" parameters to <ui:include>, then you'd better consider registering the include file as a tagfile, so that you can ultimately use it like so <my:tagname foo="#{bean.foo}">. See also When to use <ui:include>, tag files, composite components and/or custom components?

You can even pass whole beans, methods and parameters via <ui:param>. See also JSF 2: how to pass an action including an argument to be invoked to a Facelets sub view (using ui:include and ui:param)?


Design hints

The files which aren't supposed to be publicly accessible by just entering/guessing its URL, need to be placed in /WEB-INF folder, like as the include file and the template file in above example. See also Which XHTML files do I need to put in /WEB-INF and which not?

There doesn't need to be any markup (HTML code) outside <ui:composition> and <ui:define>. You can put any, but they will be ignored by Facelets. Putting markup in there is only useful for web designers. See also Is there a way to run a JSF page without building the whole project?

The HTML5 doctype is the recommended doctype these days, "in spite of" that it's a XHTML file. You should see XHTML as a language which allows you to produce HTML output using a XML based tool. See also Is it possible to use JSF+Facelets with HTML 4/5? and JavaServer Faces 2.2 and HTML5 support, why is XHTML still being used.

CSS/JS/image files can be included as dynamically relocatable/localized/versioned resources. See also How to reference CSS / JS / image resource in Facelets template?

You can put Facelets files in a reusable JAR file. See also Structure for multiple JSF projects with shared code.

For real world examples of advanced Facelets templating, check the src/main/webapp folder of Java EE Kickoff App source code and OmniFaces showcase site source code.

Python 3 print without parenthesis

You can't, because the only way you could do it without parentheses is having it be a keyword, like in Python 2. You can't manually define a keyword, so no.

Loop through a comma-separated shell variable

#/bin/bash   
TESTSTR="abc,def,ghij"

for i in $(echo $TESTSTR | tr ',' '\n')
do
echo $i
done

I prefer to use tr instead of sed, becouse sed have problems with special chars like \r \n in some cases.

other solution is to set IFS to certain separator

How to redirect from one URL to another URL?

you can also use a meta tag to redirect to another url.

<meta http-equiv="refresh" content="2;url=http://webdesign.about.com/">

http://webdesign.about.com/od/metataglibraries/a/aa080300a.htm

How to get param from url in angular 4?

You can try this:

this.activatedRoute.paramMap.subscribe(x => {
    let id = x.get('id');
    console.log(id);  
});

Adding click event handler to iframe

iframe doesn't have onclick event but we can implement this by using iframe's onload event and javascript like this...

function iframeclick() {
document.getElementById("theiframe").contentWindow.document.body.onclick = function() {
        document.getElementById("theiframe").contentWindow.location.reload();
    }
}


<iframe id="theiframe" src="youriframe.html" style="width: 100px; height: 100px;" onload="iframeclick()"></iframe>

I hope it will helpful to you....

How can I compare time in SQL Server?

TL;DR

Separate the time value from the date value if you want to use indexes in your search (you probably should, for performance). You can: (1) use function-based indexes or (2) create a new column for time only, index this column and use it in you SELECT clause.


Keep in mind you will lose any index performance boost if you use functions in a SQL's WHERE clause, the engine has to do a scan search. Just run your query with EXPLAIN SELECT... to confirm this. This happens because the engine has to process EVERY value in the field for EACH comparison, and the converted value is not indexed.

Most answers say to use float(), convert(), cast(), addtime(), etc.. Again, your database won't use indexes if you do this. For small tables that may be OK.

It is OK to use functions in WHERE params though (where field = func(value)), because you won't be changing EACH field's value in the table.

In case you want to keep use of indexes, you can create a function-based index for the time value. The proper way to do this (and support for it) may depend on your database engine. Another option is adding a column to store only the time value and index this column, but try the former approach first.


Edit 06-02

Do some performance tests before updating your database to have a new time column or whatever to make use of indexes. In my tests, I found out the performance boost was minimal (when I could see some improvement) and wouldn't be worth the trouble and overhead of adding a new index.

Iterating through a List Object in JSP

change the code to the following

<%! List eList = (ArrayList)session.getAttribute("empList");%>
....
<table>
    <%
    for(int i=0; i<eList.length;i++){%>
        <tr>
            <td><%= ((Employee)eList[i]).getEid() %></td>
            <td><%= ((Employee)eList[i]).getEname() %></td>  
        </tr>
      <%}%>
</table>

How to delete a specific file from folder using asp.net

Check the GridView1.SelectedRow is not null:

if (GridView1.SelectedRow == null) return;
string DeleteThis = GridView1.SelectedRow.Cells[0].Text;

How to make all controls resize accordingly proportionally when window is maximized?

Just thought i'd share this with anyone who needs more clarity on how to achieve this:

myCanvas is a Canvas control and Parent to all other controllers. This code works to neatly resize to any resolution from 1366 x 768 upward. Tested up to 4k resolution 4096 x 2160

Take note of all the MainWindow property settings (WindowStartupLocation, SizeToContent and WindowState) - important for this to work correctly - WindowState for my user case requirement was Maximized

xaml

<Window x:Name="mainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyApp" 
    xmlns:ed="http://schemas.microsoft.com/expression/2010/drawing"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
    x:Class="MyApp.MainWindow" 
     Title="MainWindow"  SizeChanged="MainWindow_SizeChanged"
    Width="1366" Height="768" WindowState="Maximized" WindowStartupLocation="CenterOwner" SizeToContent="WidthAndHeight">
  
    <Canvas x:Name="myCanvas" HorizontalAlignment="Left" Height="768" VerticalAlignment="Top" Width="1356">
        <Image x:Name="maxresdefault_1_1__jpg" Source="maxresdefault-1[1].jpg" Stretch="Fill" Opacity="0.6" Height="767" Canvas.Left="-6" Width="1366"/>

        <Separator Margin="0" Background="#FF302D2D" Foreground="#FF111010" Height="0" Canvas.Left="-811" Canvas.Top="148" Width="766"/>
        <Separator Margin="0" Background="#FF302D2D" Foreground="#FF111010" HorizontalAlignment="Right" Width="210" Height="0" Canvas.Left="1653" Canvas.Top="102"/>
        <Image x:Name="imgscroll" Source="BcaKKb47i[1].png" Stretch="Fill" RenderTransformOrigin="0.5,0.5" Height="523" Canvas.Left="-3" Canvas.Top="122" Width="580">
            <Image.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform/>
                    <RotateTransform Angle="89.093"/>
                    <TranslateTransform/>
                </TransformGroup>
            </Image.RenderTransform>
        </Image>

.cs

 private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        myCanvas.Width = e.NewSize.Width;
        myCanvas.Height = e.NewSize.Height;

        double xChange = 1, yChange = 1;

        if (e.PreviousSize.Width != 0)
            xChange = (e.NewSize.Width / e.PreviousSize.Width);

        if (e.PreviousSize.Height != 0)
            yChange = (e.NewSize.Height / e.PreviousSize.Height);

        ScaleTransform scale = new ScaleTransform(myCanvas.LayoutTransform.Value.M11 * xChange, myCanvas.LayoutTransform.Value.M22 * yChange);
        myCanvas.LayoutTransform = scale;
        myCanvas.UpdateLayout();
    }

Could not find main class HelloWorld

I have also faced same problem....

Actually this problem is raised due to the fact that your program .class files are not saved in that directory. Remove your CLASSPATH from your environment variable (you do no need to set classpath for simple Java programs) and reopen cmd prompt, then compile and execute.

If you observe carefully your .class file will save in the same location. (I am not an expert, I am also basic programer if there is any mistake in my sentences please ignore it :-))

Printing string variable in Java

You're getting the toString() value returned by the Scanner object itself which is not what you want and not how you use a Scanner object. What you want instead is the data obtained by the Scanner object. For example,

Scanner input = new Scanner(System.in);
String data = input.nextLine();
System.out.println(data);

Please read the tutorial on how to use it as it will explain all.

Edit
Please look here: Scanner tutorial

Also have a look at the Scanner API which will explain some of the finer points of Scanner's methods and properties.

How to set bot's status

setGame has been discontinued. You must use client.user.setActivity.

Don't forget, if you are setting a streaming status, you MUST specify a Twitch URL

An example is here:

client.user.setActivity("with depression", {
  type: "STREAMING",
  url: "https://www.twitch.tv/example-url"
});

Fastest Convert from Collection to List<T>

You could try:

List<ManagementObject> managementList = new List<ManagementObject>(managementObjects.ToArray());

Not sure if .ToArray() is available for the collection. If you do use the code you posted, make sure you initialize the List with the number of existing elements:

List<ManagementObject> managementList = new List<ManagementObject>(managementObjects.Count);  // or .Length

What can cause intermittent ORA-12519 (TNS: no appropriate handler found) errors

Don't know if this will be everybody's answer, but after some digging, here's what we came up with.

The error is obviously caused by the fact that the listener was not accepting connections, but why would we get that error when other tests could connect fine (we could also connect no problem through sqlplus)? The key to the issue wasn't that we couldn't connect, but that it was intermittent

After some investigation, we found that there was some static data created during the class setup that would keep open connections for the life of the test class, creating new ones as it went. Now, even though all of the resources were properly released when this class went out of scope (via a finally{} block, of course), there were some cases during the run when this class would swallow up all available connections (okay, bad practice alert - this was unit test code that connected directly rather than using a pool, so the same problem could not happen in production).

The fix was to not make that class static and run in the class setup, but instead use it in the per method setUp and tearDown methods.

So if you get this error in your own apps, slap a profiler on that bad boy and see if you might have a connection leak. Hope that helps.

Android design support library for API 28 (P) not working

First of all, you should look gradle.properties and these values have to be true. If you cannot see them you have to write.

android.useAndroidX=true
android.enableJetifier=true

After that you can use AndroidX dependencies in your build.gradle (Module: app). Also, you have to check compileSDKVersion and targetVersion. They should be minimum 28. For example I am using 29.

So, an androidx dependency example:

implementation 'androidx.cardview:cardview:1.0.0'

However be careful because everything is not start with androidx like cardview dependency. For example, old design dependency is:

implementation 'com.android.support:design:27.1.1'

But new design dependency is:

implementation 'com.google.android.material:material:1.3.0'

RecyclerView is:

implementation 'androidx.recyclerview:recyclerview:1.1.0'

So, you have to search and read carefully. Happy code.

@canerkaseler

How to disable scrolling the document body?

I know this is an ancient question, but I just thought that I'd weigh in.

I'm using disableScroll. Simple and it works like in a dream.

I have had some trouble disabling scroll on body, but allowing it on child elements (like a modal or a sidebar). It looks like that something can be done using disableScroll.on([element], [options]);, but I haven't gotten that to work just yet.


The reason that this is prefered compared to overflow: hidden; on body is that the overflow-hidden can get nasty, since some things might add overflow: hidden; like this:

... This is good for preloaders and such, since that is rendered before the CSS is finished loading.

But it gives problems, when an open navigation should add a class to the body-tag (like <body class="body__nav-open">). And then it turns into one big tug-of-war with overflow: hidden; !important and all kinds of crap.

Efficiently test if a port is open on Linux?

There's a very short with "fast answer" here : How to test if remote TCP port is opened from Shell script?

nc -z <host> <port>; echo $?

I use it with 127.0.0.1 as "remote" address.

this returns "0" if the port is open and "1" if the port is closed

e.g.

nc -z 127.0.0.1 80; echo $?

-z Specifies that nc should just scan for listening daemons, without sending any data to them. It is an error to use this option in conjunc- tion with the -l option.

Bootstrap 3: pull-right for col-lg only

There is no need to create your own class with media queries. Bootstrap 3 already has float ordering for media breakpoints under Column Ordering: http://getbootstrap.com/css/#grid-column-ordering

The syntax for the class is col-<#grid-size>-(push|pull)-<#cols> where <#grid-size> is xs, sm, md or lg and <#cols> is how far you want the column to move for that grid size. Push or pull is left or right of course.

I use it all the time so I know it works well.

Combining "LIKE" and "IN" for SQL Server

No, MSSQL doesn't allow such queries. You should use col LIKE '...' OR col LIKE '...' etc.

Closing Excel Application Process in C# after Data Access

         wb.Close();
         app.Quit();

         System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("Excel");
         foreach (System.Diagnostics.Process p in process)
         {
             if (!string.IsNullOrEmpty(p.ProcessName) && p.StartTime.AddSeconds(+10) > DateTime.Now)
             {
                 try
                 {
                     p.Kill();
                 }
                 catch { }
             }
         }

It Closes last 10 sec process with name "Excel"

Java - How to access an ArrayList of another class?

Put them in an arrayList in your first class like:

import java.util.ArrayList;
    public class numbers {

    private int number1 = 50;
    private int number2 = 100;

    public ArrayList<int> getNumberList() {
        ArrayList<int> numbersList= new ArrayList<int>();
        numbersList.add(number1);
        numberList.add(number2);
        ....
        return numberList;
    }
}

Then, in your test class you can call numbers.getNumberList() to get your arrayList. In addition, you might want to create methods like addToList / removeFromList in your numbers class so you can handle it the way you need it.

You can also access a variable declared in one class from another simply like

numbers.numberList;

if you have it declared there as public.

But it isn't such a good practice in my opinion, since you probably need to modify this list in your code later. Note that you have to add your class to the import list.

If you can tell me what your app requirements are, i'll be able tell you more precise what i think it's best to do.

Print a list in reverse order with range()?

range(9,-1,-1)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

SMTP connect() failed PHPmailer - PHP

<?php

use PHPMailer\PHPMailer\PHPMailer;

require_once "PHPMailer/src/Exception.php";
require_once "PHPMailer/src/PHPMailer.php";
require_once "PHPMailer/src/SMTP.php";



$mail = new PHPMailer();

$mail ->isSMTP();
$mail ->Host ="smtp.gmail.com";
$mail -> SMTPAuth = true;
$mail ->Username = '[email protected]';
$mail ->Password = 'password';
//$mail ->SMTPSecure=PHPMailer::ENCRYPTION_STARTTLS;
$mail ->Port = '587';
$mail ->SMTPSecure ='tls';
$mail ->isHTML(true);

$mail ->setFrom('[email protected]','email send name');

$mail ->addAddress('[email protected]');
$mail ->Subject = 'HelloWorld';
$mail ->Body = 'a test email';


$mail->SMTPOptions = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    )
);



if ($mail->send()){
    echo "Message has been sent successfully";
}else{
    echo "Mailer Error: " . $mail->ErrorInfo;
}

?>

make sure that you configure less secure app settings in gmail using this link https://www.google.com/settings/security/lesssecureapps and make sure you downloaded PHPMailer-master.zip from github

working fine with MAMP server locally :)

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

ffprobe or avprobe not found. Please install one

What worked for me (youtube-dl version 2018.03.03, ffprobe 0.5, no avprobe, 3.4.1-tessus, in Hi-Sierra/iMac) was:

brew install libav

(thanks to marciovsena's post on GitHub).

I saw elsewhere that libav might be deprecated in the future, but I'll worry about it when we get there.

Side-by-side plots with ggplot2

Update: This answer is very old. gridExtra::grid.arrange() is now the recommended approach. I leave this here in case it might be useful.


Stephen Turner posted the arrange() function on Getting Genetics Done blog (see post for application instructions)

vp.layout <- function(x, y) viewport(layout.pos.row=x, layout.pos.col=y)
arrange <- function(..., nrow=NULL, ncol=NULL, as.table=FALSE) {
 dots <- list(...)
 n <- length(dots)
 if(is.null(nrow) & is.null(ncol)) { nrow = floor(n/2) ; ncol = ceiling(n/nrow)}
 if(is.null(nrow)) { nrow = ceiling(n/ncol)}
 if(is.null(ncol)) { ncol = ceiling(n/nrow)}
        ## NOTE see n2mfrow in grDevices for possible alternative
grid.newpage()
pushViewport(viewport(layout=grid.layout(nrow,ncol) ) )
 ii.p <- 1
 for(ii.row in seq(1, nrow)){
 ii.table.row <- ii.row 
 if(as.table) {ii.table.row <- nrow - ii.table.row + 1}
  for(ii.col in seq(1, ncol)){
   ii.table <- ii.p
   if(ii.p > n) break
   print(dots[[ii.table]], vp=vp.layout(ii.table.row, ii.col))
   ii.p <- ii.p + 1
  }
 }
}

Comments in .gitignore?

Yes, you may put comments in there. They however must start at the beginning of a line.

cf. http://git-scm.com/book/en/Git-Basics-Recording-Changes-to-the-Repository#Ignoring-Files

The rules for the patterns you can put in the .gitignore file are as follows:
- Blank lines or lines starting with # are ignored.
[…]

The comment character is #, example:

# no .a files
*.a

How can I copy network files using Robocopy?

I use the following format and works well.

robocopy \\SourceServer\Path \\TargetServer\Path filename.txt

to copy everything you can replace filename.txt with *.* and there are plenty of other switches to copy subfolders etc... see here: http://ss64.com/nt/robocopy.html

How to sort a HashSet?

You can use a TreeSet instead.

HTML Table cellspacing or padding just top / bottom

CSS?

td {
  padding-top: 2px;
  padding-bottom: 2px;
}

Notice: Undefined variable: _SESSION in "" on line 9

Add

session_start();

at the beginning of your page before any HTML

You will have something like :

<?php session_start();
include("inc/incfiles/header.inc.php")?>
<html>
<head>
<meta http-equiv="Content-Type" conte...

Don't forget to remove the space you have before

Python: Find in list

If you are going to check if value exist in the collectible once then using 'in' operator is fine. However, if you are going to check for more than once then I recommend using bisect module. Keep in mind that using bisect module data must be sorted. So you sort data once and then you can use bisect. Using bisect module on my machine is about 12 times faster than using 'in' operator.

Here is an example of code using Python 3.8 and above syntax:

import bisect
from timeit import timeit

def bisect_search(container, value):
    return (
      (index := bisect.bisect_left(container, value)) < len(container) 
      and container[index] == value
    )

data = list(range(1000))
# value to search
true_value = 666
false_value = 66666

# times to test
ttt = 1000

print(f"{bisect_search(data, true_value)=} {bisect_search(data, false_value)=}")

t1 = timeit(lambda: true_value in data, number=ttt)
t2 = timeit(lambda: bisect_search(data, true_value), number=ttt)

print("Performance:", f"{t1=:.4f}, {t2=:.4f}, diffs {t1/t2=:.2f}")

Output:

bisect_search(data, true_value)=True bisect_search(data, false_value)=False
Performance: t1=0.0220, t2=0.0019, diffs t1/t2=11.71

Cannot find control with name: formControlName in angular reactive form

For me even with [formGroup] the error was popping up "Cannot find control with name:''".
It got fixed when I added ngModel Value to the input box along with formControlName="fileName"

  <form class="upload-form" [formGroup]="UploadForm">
  <div class="row">
    <div class="form-group col-sm-6">
      <label for="fileName">File Name</label>
      <!-- *** *** *** Adding [(ngModel)]="FileName" fixed the issue-->
      <input type="text" class="form-control" id="fileName" [(ngModel)]="FileName"
        placeholder="Enter file name" formControlName="fileName"> 
    </div>
    <div class="form-group col-sm-6">
      <label for="selectedType">File Type</label>
      <select class="form-control" formControlName="selectedType" id="selectedType" 
        (change)="TypeChanged(selectedType)" name="selectedType" disabled="true">
        <option>Type 1</option>
        <option>Type 2</option>
      </select>
    </div>
  </div>
  <div class="form-group">
    <label for="fileUploader">Select {{selectedType}} file</label>
    <input type="file" class="form-control-file" id="fileUploader" (change)="onFileSelected($event)">
  </div>
  <div class="w-80 text-right mt-3">
    <button class="btn btn-primary mb-2 search-button cancel-button" (click)="cancelUpload()">Cancel</button>
    <button class="btn btn-primary mb-2 search-button" (click)="uploadFrmwrFile()">Upload</button>
  </div>
 </form>

And in the controller

ngOnInit() {
this.UploadForm= new FormGroup({
  fileName: new FormControl({value: this.FileName}),
  selectedType: new FormControl({value: this.selectedType, disabled: true}, Validators.required),
  frmwareFile: new FormControl({value: ['']})
});
}

What does "exited with code 9009" mean during this build?

You need to make sure you have installed grunt globally

How to extract the first two characters of a string in shell scripting?

Just grep:

echo 'abcdef' | grep -Po "^.."        # ab

Missing Maven dependencies in Eclipse project

I also encountered this problem. It confused me several hours. I tried many of solutions which were suggested in this topic. At last, I found it was due to the Java Element Filters.

Java Element Filters.

Python safe method to get value of nested dictionary

A solution I've used that is similar to the double get but with the additional ability to avoid a TypeError using if else logic:

    value = example_dict['key1']['key2'] if example_dict.get('key1') and example_dict['key1'].get('key2') else default_value

However, the more nested the dictionary the more cumbersome this becomes.

Export a list into a CSV or TXT file in R

cat(capture.output(print(my.list), file="test.txt"))

from R: Export and import a list to .txt file https://stackoverflow.com/users/1855677/42 is the only thing that worked for me. This outputs the list of lists as it is in the text file

PHP Fatal error: Call to undefined function json_decode()

If you're using phpbrew try to install json extension to fix error with undefined function json_decode():

phpbrew ext install json

How do you count the elements of an array in java

You can declare an array of booleans with the same length of your array:

true: is used
false: is not used

and change the value of the same cell number to true. Then you can count how many cells are used by using a for loop.

How do I fetch only one branch of a remote Git repository?

git fetch <remote_name> <branch_name>

Worked for me.

Using an authorization header with Fetch in React Native

I had this identical problem, I was using django-rest-knox for authentication tokens. It turns out that nothing was wrong with my fetch method which looked like this:

...
    let headers = {"Content-Type": "application/json"};
    if (token) {
      headers["Authorization"] = `Token ${token}`;
    }
    return fetch("/api/instruments/", {headers,})
      .then(res => {
...

I was running apache.

What solved this problem for me was changing WSGIPassAuthorization to 'On' in wsgi.conf.

I had a Django app deployed on AWS EC2, and I used Elastic Beanstalk to manage my application, so in the django.config, I did this:

container_commands:
  01wsgipass:
    command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'

Upload video files via PHP and save them in appropriate folder and have a database entry

HTML Code

<html>
<body>

<head>
<title></title>
</head>

<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
    <label for="file"><span>Filename:</span></label>
    <input type="file" name="file" id="file" /> 
    <br />
<input type="submit" name="submit" value="Submit" />
</form>



<?php

    //============================= DATABASE CONNECTIVITY d ====================
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "test";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
    else

    //============================= DATABASE CONNECTIVITY u ====================
    //============================= Retrieve data from DB d ====================
    $sql = "SELECT name, size, type FROM videos";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) 
        {
        $path = "uploaded/" . $row["name"];

            echo $path . "<br>";

        }
    } else {
        echo "0 results";
    }
    $conn->close();
    //============================= Retrieve data from DB d ====================

?>


</body>
</html>

Using Rsync include and exclude options to include directory and file by pattern

Here's my "teach a person to fish" answer:

Rsync's syntax is definitely non-intuitive, but it is worth understanding.

  1. First, use -vvv to see the debug info for rsync.
$ rsync -nr -vvv --include="**/file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/

[sender] hiding directory 1280000000 because of pattern *
[sender] hiding directory 1260000000 because of pattern *
[sender] hiding directory 1270000000 because of pattern *

The key concept here is that rsync applies the include/exclude patterns for each directory recursively. As soon as the first include/exclude is matched, the processing stops.

The first directory it evaluates is /Storage/uploads. Storage/uploads has 1280000000/, 1260000000/, 1270000000/ dirs/files. None of them match file_11*.jpg to include. All of them match * to exclude. So they are excluded, and rsync ends.

  1. The solution is to include all dirs (*/) first. Then the first dir component will be 1260000000/, 1270000000/, 1280000000/ since they match */. The next dir component will be 1260000000/. In 1260000000/, file_11_00.jpg matches --include="file_11*.jpg", so it is included. And so forth.
$ rsync -nrv --include='*/' --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/

./
1260000000/
1260000000/file_11_00.jpg
1260000000/file_11_01.jpg
1270000000/
1270000000/file_11_00.jpg
1270000000/file_11_01.jpg
1280000000/
1280000000/file_11_00.jpg
1280000000/file_11_01.jpg

https://download.samba.org/pub/rsync/rsync.1

How do I pass a value from a child back to the parent form?

Many ways to skin the cat here and @Mitch's suggestion is a good way. If you want the client form to have more 'control', you may want to pass the instance of the parent to the child when created and then you can call any public parent method on the child.

Format date and time in a Windows batch script

Here is how I generate a log filename (based on http://ss64.com/nt/syntax-getdate.html):

@ECHO OFF
:: Check WMIC is available
WMIC.EXE Alias /? >NUL 2>&1 || GOTO s_error

:: Use WMIC to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
   IF "%%~L"=="" goto s_done
      Set _yyyy=%%L
      Set _mm=00%%J
      Set _dd=00%%G
      Set _hour=00%%H
      SET _minute=00%%I
      SET _second=00%%K
)
:s_done

:: Pad digits with leading zeros
      Set _mm=%_mm:~-2%
      Set _dd=%_dd:~-2%
      Set _hour=%_hour:~-2%
      Set _minute=%_minute:~-2%
      Set _second=%_second:~-2%

Set logtimestamp=%_yyyy%-%_mm%-%_dd%_%_hour%_%_minute%_%_second%
goto make_dump

:s_error
echo WMIC is not available, using default log filename
Set logtimestamp=_

:make_dump
set FILENAME=database_dump_%logtimestamp%.sql
...

How to URL encode in Python 3?

You’re looking for urllib.parse.urlencode

import urllib.parse

params = {'username': 'administrator', 'password': 'xyz'}
encoded = urllib.parse.urlencode(params)
# Returns: 'username=administrator&password=xyz'

Difference between HashMap and Map in Java..?

Map is an interface; HashMap is a particular implementation of that interface.

HashMap uses a collection of hashed key values to do its lookup. TreeMap will use a red-black tree as its underlying data store.

SQL Server - An expression of non-boolean type specified in a context where a condition is expected, near 'RETURN'

Your problem might be here:

OR
                        (
                            SELECT m.ResourceNo FROM JobMember m
                            JOIN JobTask t ON t.JobTaskNo = m.JobTaskNo
                            WHERE t.TaskManagerNo = @UserResourceNo
                            OR
                            t.AlternateTaskManagerNo = @UserResourceNo
                        )

try changing to

OR r.ResourceNo IN
                        (
                            SELECT m.ResourceNo FROM JobMember m
                            JOIN JobTask t ON t.JobTaskNo = m.JobTaskNo
                            WHERE t.TaskManagerNo = @UserResourceNo
                            OR
                            t.AlternateTaskManagerNo = @UserResourceNo
                        )

Angular.js ng-repeat filter by property having one of multiple values (OR of values)

I thing ng-if should work:

<div ng-repeat="product in products" ng-if="product.color === 'red' 
|| product.color === 'blue'">

File to byte[] in Java

Simplest Way for reading bytes from file

import java.io.*;

class ReadBytesFromFile {
    public static void main(String args[]) throws Exception {
        // getBytes from anyWhere
        // I'm getting byte array from File
        File file = null;
        FileInputStream fileStream = new FileInputStream(file = new File("ByteArrayInputStreamClass.java"));

        // Instantiate array
        byte[] arr = new byte[(int) file.length()];

        // read All bytes of File stream
        fileStream.read(arr, 0, arr.length);

        for (int X : arr) {
            System.out.print((char) X);
        }
    }
}

How Connect to remote host from Aptana Studio 3

From the Project Explorer, expand the project you want to hook up to a remote site (or just right click and create a new Web project that's empty if you just want to explore a remote site from there). There's a "Connections" node, right click it and select "Add New connection...". A dialog will appear, at bottom you can select the destination as Remote and then click the "New..." button. There you can set up an FTP/FTPS/SFTP connection.

That's how you set up a connection that's tied to a project, typically for upload/download/sync between it and a project.

You can also do Window > Show View > Remote. From that view, you can click the globe icon in the upper right to add connections and in this view you can just browse your remote connections.

How to apply CSS to iframe?

There is a wonderful script that replaces a node with an iframe version of itself. CodePen Demo

enter image description here

Usage Examples:

// Single node
var component = document.querySelector('.component');
var iframe = iframify(component);

// Collection of nodes
var components = document.querySelectorAll('.component');
var iframes = Array.prototype.map.call(components, function (component) {
  return iframify(component, {});
});

// With options
var component = document.querySelector('.component');
var iframe = iframify(component, {
  headExtra: '<style>.component { color: red; }</style>',
  metaViewport: '<meta name="viewport" content="width=device-width">'
});

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

You need jackson dependency for this serialization and deserialization.

Add this dependency:

Gradle:

compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.4")

Maven:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

After that, You need to tell Jackson ObjectMapper to use JavaTimeModule. To do that, Autowire ObjectMapper in the main class and register JavaTimeModule to it.

import javax.annotation.PostConstruct;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

@SpringBootApplication
public class MockEmployeeApplication {

  @Autowired
  private ObjectMapper objectMapper;

  public static void main(String[] args) {
    SpringApplication.run(MockEmployeeApplication.class, args);

  }

  @PostConstruct
  public void setUp() {
    objectMapper.registerModule(new JavaTimeModule());
  }
}

After that, Your LocalDate and LocalDateTime should be serialized and deserialized correctly.

How do ACID and database transactions work?

I slightly modified the printer example to make it more explainable

1 document which had 2 pages content was sent to printer

Transaction - document sent to printer

  • atomicity - printer prints 2 pages of a document or none
  • consistency - printer prints half page and the page gets stuck. The printer restarts itself and prints 2 pages with all content
  • isolation - while there were too many print outs in progress - printer prints the right content of the document
  • durability - while printing, there was a power cut- printer again prints documents without any errors

Hope this helps someone to get the hang of the concept of ACID

Export to CSV via PHP

Just for the record, concatenation is waaaaaay faster (I mean it) than fputcsv or even implode; And the file size is smaller:

// The data from Eternal Oblivion is an object, always
$values = (array) fetchDataFromEternalOblivion($userId, $limit = 1000);

// ----- fputcsv (slow)
// The code of @Alain Tiemblo is the best implementation
ob_start();
$csv = fopen("php://output", 'w');
fputcsv($csv, array_keys(reset($values)));
foreach ($values as $row) {
    fputcsv($csv, $row);
}
fclose($csv);
return ob_get_clean();

// ----- implode (slow, but file size is smaller)
$csv = implode(",", array_keys(reset($values))) . PHP_EOL;
foreach ($values as $row) {
    $csv .= '"' . implode('","', $row) . '"' . PHP_EOL;
}
return $csv;
// ----- concatenation (fast, file size is smaller)
// We can use one implode for the headers =D
$csv = implode(",", array_keys(reset($values))) . PHP_EOL;
$i = 1;
// This is less flexible, but we have more control over the formatting
foreach ($values as $row) {
    $csv .= '"' . $row['id'] . '",';
    $csv .= '"' . $row['name'] . '",';
    $csv .= '"' . date('d-m-Y', strtotime($row['date'])) . '",';
    $csv .= '"' . ($row['pet_name'] ?: '-' ) . '",';
    $csv .= PHP_EOL;
}
return $csv;

This is the conclusion of the optimization of several reports, from ten to thousands rows. The three examples worked fine under 1000 rows, but fails when the data was bigger.

Javascript geocoding from address to latitude and longitude numbers not working

You're accessing the latitude and longitude incorrectly.

Try

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">

var geocoder = new google.maps.Geocoder();
var address = "new york";

geocoder.geocode( { 'address': address}, function(results, status) {

  if (status == google.maps.GeocoderStatus.OK) {
    var latitude = results[0].geometry.location.lat();
    var longitude = results[0].geometry.location.lng();
    alert(latitude);
  } 
}); 
</script>

How to delete columns in a CSV file?

Off the top of my head, this will do it without any sort of error checking nor ability to configure anything. That is "left to the reader".

outFile = open( 'newFile', 'w' )
for line in open( 'oldFile' ):
   items = line.split( ',' )
   outFile.write( ','.join( items[:2] + items[ 3: ] ) )
outFile.close()

How to dynamically create a class?

Yes, you can use System.Reflection.Emit namespace for this. It is not straight forward if you have no experience with it, but it is certainly possible.

Edit: This code might be flawed, but it will give you the general idea and hopefully off to a good start towards the goal.

using System;
using System.Reflection;
using System.Reflection.Emit;

namespace TypeBuilderNamespace
{
    public static class MyTypeBuilder
    {
        public static void CreateNewObject()
        {
            var myType = CompileResultType();
            var myObject = Activator.CreateInstance(myType);
        }
        public static Type CompileResultType()
        {
            TypeBuilder tb = GetTypeBuilder();
            ConstructorBuilder constructor = tb.DefineDefaultConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            // NOTE: assuming your list contains Field objects with fields FieldName(string) and FieldType(Type)
            foreach (var field in yourListOfFields)
                CreateProperty(tb, field.FieldName, field.FieldType);

            Type objectType = tb.CreateType();
            return objectType;
        }

        private static TypeBuilder GetTypeBuilder()
        {
            var typeSignature = "MyDynamicType";
            var an = new AssemblyName(typeSignature);
            AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
            TypeBuilder tb = moduleBuilder.DefineType(typeSignature,
                    TypeAttributes.Public |
                    TypeAttributes.Class |
                    TypeAttributes.AutoClass |
                    TypeAttributes.AnsiClass |
                    TypeAttributes.BeforeFieldInit |
                    TypeAttributes.AutoLayout,
                    null);
            return tb;
        }

        private static void CreateProperty(TypeBuilder tb, string propertyName, Type propertyType)
        {
            FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);

            PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);
            MethodBuilder getPropMthdBldr = tb.DefineMethod("get_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, propertyType, Type.EmptyTypes);
            ILGenerator getIl = getPropMthdBldr.GetILGenerator();

            getIl.Emit(OpCodes.Ldarg_0);
            getIl.Emit(OpCodes.Ldfld, fieldBuilder);
            getIl.Emit(OpCodes.Ret);

            MethodBuilder setPropMthdBldr =
                tb.DefineMethod("set_" + propertyName,
                  MethodAttributes.Public |
                  MethodAttributes.SpecialName |
                  MethodAttributes.HideBySig,
                  null, new[] { propertyType });

            ILGenerator setIl = setPropMthdBldr.GetILGenerator();
            Label modifyProperty = setIl.DefineLabel();
            Label exitSet = setIl.DefineLabel();

            setIl.MarkLabel(modifyProperty);
            setIl.Emit(OpCodes.Ldarg_0);
            setIl.Emit(OpCodes.Ldarg_1);
            setIl.Emit(OpCodes.Stfld, fieldBuilder);

            setIl.Emit(OpCodes.Nop);
            setIl.MarkLabel(exitSet);
            setIl.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(getPropMthdBldr);
            propertyBuilder.SetSetMethod(setPropMthdBldr);
        }
    }
}

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

Laravel, sync() - how to sync an array and also pass additional pivot fields?

$data = array();
foreach ($request->planes as $plan) {
 $data_plan = array($plan => array('dia' => $request->dia[$plan] ) );                
 array_push($data,$data_plan);    
}
$user->planes()->sync($data);

Pick a random value from an enum?

Single line

return Letter.values()[new Random().nextInt(Letter.values().length)];

How to check if a key exists in Json Object and get its value

containerObject = new JSONObject(container);
if (containerObject.has("video")) { 
   //get Value of video
}

Frequency table for a single variable

Maybe .value_counts()?

>>> import pandas
>>> my_series = pandas.Series([1,2,2,3,3,3, "fred", 1.8, 1.8])
>>> my_series
0       1
1       2
2       2
3       3
4       3
5       3
6    fred
7     1.8
8     1.8
>>> counts = my_series.value_counts()
>>> counts
3       3
2       2
1.8     2
fred    1
1       1
>>> len(counts)
5
>>> sum(counts)
9
>>> counts["fred"]
1
>>> dict(counts)
{1.8: 2, 2: 2, 3: 3, 1: 1, 'fred': 1}

Export html table data to Excel using JavaScript / JQuery is not working properly in chrome browser

_x000D_
_x000D_
 function exportToExcel() {_x000D_
        var tab_text = "<tr bgcolor='#87AFC6'>";_x000D_
        var textRange; var j = 0, rows = '';_x000D_
        tab = document.getElementById('student-detail');_x000D_
        tab_text = tab_text + tab.rows[0].innerHTML + "</tr>";_x000D_
        var tableData = $('#student-detail').DataTable().rows().data();_x000D_
        for (var i = 0; i < tableData.length; i++) {_x000D_
            rows += '<tr>'_x000D_
                + '<td>' + tableData[i].value1 + '</td>'_x000D_
                + '<td>' + tableData[i].value2 + '</td>'_x000D_
                + '<td>' + tableData[i].value3 + '</td>'_x000D_
                + '<td>' + tableData[i].value4 + '</td>'_x000D_
                + '<td>' + tableData[i].value5 + '</td>'_x000D_
                + '<td>' + tableData[i].value6 + '</td>'_x000D_
                + '<td>' + tableData[i].value7 + '</td>'_x000D_
                + '<td>' +  tableData[i].value8 + '</td>'_x000D_
                + '<td>' + tableData[i].value9 + '</td>'_x000D_
                + '<td>' + tableData[i].value10 + '</td>'_x000D_
                + '</tr>';_x000D_
        }_x000D_
        tab_text += rows;_x000D_
        var data_type = 'data:application/vnd.ms-excel;base64,',_x000D_
            template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table border="2px">{table}</table></body></html>',_x000D_
            base64 = function (s) {_x000D_
                return window.btoa(unescape(encodeURIComponent(s)))_x000D_
            },_x000D_
            format = function (s, c) {_x000D_
                return s.replace(/{(\w+)}/g, function (m, p) {_x000D_
                    return c[p];_x000D_
                })_x000D_
            }_x000D_
_x000D_
        var ctx = {_x000D_
            worksheet: "Sheet 1" || 'Worksheet',_x000D_
            table: tab_text_x000D_
        }_x000D_
        document.getElementById("dlink").href = data_type + base64(format(template, ctx));_x000D_
        document.getElementById("dlink").download = "StudentDetails.xls";_x000D_
        document.getElementById("dlink").traget = "_blank";_x000D_
        document.getElementById("dlink").click();_x000D_
    }
_x000D_
_x000D_
_x000D_

Here Value 1 to 10 are column names that you are getting

This Activity already has an action bar supplied by the window decor

I had toolbar added in my xml. Then in my activity i was adding this statement:

setSupportActionBar(toolbar);

Removing this worked for me. I hope it helps someone.

How do I get the SQLSRV extension to work with PHP, since MSSQL is deprecated?

Quoting http://php.net/manual/en/intro.mssql.php:

The MSSQL extension is not available anymore on Windows with PHP 5.3 or later. SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

Once you downloaded that, follow the instructions at this page:

In a nutshell:

Put the driver file in your PHP extension directory.
Modify the php.ini file to include the driver. For example:

extension=php_sqlsrv_53_nts_vc9.dll  

Restart the Web server.

See Also (copied from that page)

The PHP Manual for the SQLSRV extension is located at http://php.net/manual/en/sqlsrv.installation.php and offers the following for Installation:

The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.

The drivers can also be used with PDO.

How to call code behind server method from a client side JavaScript function?

Ajax is the way to go. The easiest (and probably the best) approach is jQuery ajax()

You'll end up writing something like this:

$.ajax({
  url: "test.html",
  context: document.body,
  success: function(){
    // do something when done
  }
});

Show hide fragment in android

public void showHideFragment(final Fragment fragment){

    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.setCustomAnimations(android.R.animator.fade_in,
                    android.R.animator.fade_out);

    if (fragment.isHidden()) {
        ft.show(fragment);
        Log.d("hidden","Show");
    } else {
        ft.hide(fragment);
        Log.d("Shown","Hide");                        
    }

    ft.commit();
}

mysqldump Error 1045 Access denied despite correct passwords etc

mysqldump -h hostname -u username -P port -B database --no-create-info -p > output.sql

I think you should specify the args

How to finish Activity when starting other activity in Android?

Intent i = new Intent(this,Here is your first activity.Class);
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(i);
    finish();

How to fix a locale setting warning from Perl

perl: warning: Falling back to the standard locale ("C").
locale: Cannot set LC_ALL to default locale: No such file or directory

Solution:

Try this (uk_UA.UTF-8 is my current locale. Write your locale, for example en_US.UTF-8 !)

sudo locale-gen uk_UA.UTF-8

and this.

sudo dpkg-reconfigure locales

Shortcut to Apply a Formula to an Entire Column in Excel

Try double-clicking on the bottom right hand corner of the cell (ie on the box that you would otherwise drag).

When is del useful in Python?

Using "del" explicitly is also better practice than assigning a variable to None. If you attempt to del a variable that doesn't exist, you'll get a runtime error but if you attempt to set a variable that doesn't exist to None, Python will silently set a new variable to None, leaving the variable you wanted deleted where it was. So del will help you catch your mistakes earlier

unexpected T_VARIABLE, expecting T_FUNCTION

You cannot use function calls in a class construction, you should initialize that value in the constructor function.

From the PHP Manual on class properties:

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

A working code sample:

<?php
    class UserDatabaseConnection
    {
        public $connection;
        public function __construct()
        {
            $this->connection = sqlite_open("[path]/data/users.sqlite", 0666);
        }
        public function lookupUser($username)
        {
            // rest of my code...
            // example usage (procedural way):
            $query = sqlite_exec($this->connection, "SELECT ...", $error);
            // object oriented way:
            $query = $this->connection->queryExec("SELECT ...", $error);
        }
    }

    $udb = new UserDatabaseConnection;
?>

Depending on your needs, protected or private might be a better choice for $connection. That protects you from accidentally closing or messing with the connection.

How to replace unicode characters in string with something else python?

Encode string as unicode.

>>> special = u"\u2022"
>>> abc = u'ABC•def'
>>> abc.replace(special,'X')
u'ABCXdef'

How can I calculate divide and modulo for integers in C#?

Division is performed using the / operator:

result = a / b;

Modulo division is done using the % operator:

result = a % b;

Redeploy alternatives to JRebel

JRebel is free. Don't buy it. Select the "free" option (radio button) on the "buy" page. Then select "Social". After you sign up, you will get a fully functional JRebel license key. You can then download JRebel or use the key in your IDEs embedded version. The catch, (yes, there is a catch), you have to allow them to post on your behalf (advertise) once a month on your FB timeline or Twitter account. I gave them my twitter account, no biggie, I never use it and no one I know really uses it. So save $260.

Mailx send html message

There are many different versions of mail around. When you go beyond mail -s subject to1@address1 to2@address2

  • With some mailx implementations, e.g. from mailutils on Ubuntu or Debian's bsd-mailx, it's easy, because there's an option for that.

    mailx -a 'Content-Type: text/html' -s "Subject" to@address <test.html
    
  • With the Heirloom mailx, there's no convenient way. One possibility to insert arbitrary headers is to set editheaders=1 and use an external editor (which can be a script).

    ## Prepare a temporary script that will serve as an editor.
    
    ## This script will be passed to ed.
    temp_script=$(mktemp)
    cat <<'EOF' >>"$temp_script"
    1a
    Content-Type: text/html
    .
    $r test.html
    w
    q
    EOF
    ## Call mailx, and tell it to invoke the editor script
    EDITOR="ed -s $temp_script" heirloom-mailx -S editheaders=1 -s "Subject" to@address <<EOF
    ~e
    .
    EOF
    rm -f "$temp_script"
    
  • With a general POSIX mailx, I don't know how to get at headers.

If you're going to use any mail or mailx, keep in mind that

  • This isn't portable even within a given Linux distribution. For example, both Ubuntu and Debian have several alternatives for mail and mailx.

  • When composing a message, mail and mailx treats lines beginning with ~ as commands. If you pipe text into mail, you need to arrange for this text not to contain lines beginning with ~.

If you're going to install software anyway, you might as well install something more predictable than mail/Mail/mailx. For example, mutt. With Mutt, you can supply most headers in the input with the -H option, but not Content-Type, which needs to be set via a mutt option.

mutt -e 'set content_type=text/html' -s 'hello' 'to@address' <test.html

Or you can invoke sendmail directly. There are several versions of sendmail out there, but they all support sendmail -t to send a mail in the simplest fashion, reading the list of recipients from the mail. (I think they don't all support Bcc:.) On most systems, sendmail isn't in the usual $PATH, it's in /usr/sbin or /usr/lib.

cat <<'EOF' - test.html | /usr/sbin/sendmail -t
To: to@address
Subject: hello
Content-Type: text/html

EOF

How to submit a form on enter when the textarea has focus?

You can't do this without JavaScript. Stackoverflow is using the jQuery JavaScript library which attachs functions to HTML elements on page load.

Here's how you could do it with vanilla JavaScript:

<textarea onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }"></textarea>

Keycode 13 is the enter key.

Here's how you could do it with jQuery like as Stackoverflow does:

<textarea class="commentarea"></textarea>

with

$(document).ready(function() {
    $('.commentarea').keydown(function(event) {
        if (event.which == 13) {
            this.form.submit();
            event.preventDefault();
         }
    });
});

How to initialize a nested struct?

One gotcha arises when you want to instantiate a public type defined in an external package and that type embeds other types that are private.

Example:

package animals

type otherProps{
  Name string
  Width int
}

type Duck{
  Weight int
  otherProps
}

How do you instantiate a Duck in your own program? Here's the best I could come up with:

package main

import "github.com/someone/animals"

func main(){
  var duck animals.Duck
  // Can't instantiate a duck with something.Duck{Weight: 2, Name: "Henry"} because `Name` is part of the private type `otherProps`
  duck.Weight = 2
  duck.Width = 30
  duck.Name = "Henry"
}

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

AS per point 1, your PEAR path is c:\xampplite\php\pear\

However, your path is pointing to \xampplite\php\pear\PEAR

Putting the two one above the other you can clearly see one is too long:

c:\xampplite\php\pear\

\xampplite\php\pear\PEAR

Your include path is set to go one PEAR too deep into the pear tree. The PEAR subfolder of the pear folder includes the PEAR component. You need to adjust your include path up one level.

(you don't need the c: by the way, your path is fine as is, just too deep)

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

I finally solved!! It's a Web Clip feature on Mac Devices. If a user want to add your website in Dock o Desktop it requests this icon.

You may want users to be able to add your web application 
or webpage link to the Home screen. These links, represented 
by an icon, are called Web Clips. Follow these simple steps 
to specify an icon to represent your web application or webpage
on iOS.

more info: https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html

how to solve?: Add a icon to solve problem.

Bring element to front using CSS

In my case i had to move the html code of the element i wanted at the front at the end of the html file, because if one element has z-index and the other doesn't have z index it doesn't work.

Launching an application (.EXE) from C#?

System.Diagnostics.Process.Start("PathToExe.exe");

Firebase (FCM) how to get token

FASTEST AND GOOD FOR PROTOTYPE

The quick solution is to store it in sharedPrefs and add this logic to onCreate method in your MainActivity or class which is extending Application.

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(this, instanceIdResult -> {
    String newToken = instanceIdResult.getToken();
    Log.e("newToken", newToken);
    getActivity().getPreferences(Context.MODE_PRIVATE).edit().putString("fb", newToken).apply();
});

Log.d("newToken", getActivity().getPreferences(Context.MODE_PRIVATE).getString("fb", "empty :("));

CLEANER WAY

A better option is to create a service and keep inside a similar logic. Firstly create new Service

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        Log.e("newToken", s);
        getSharedPreferences("_", MODE_PRIVATE).edit().putString("fb", s).apply();
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
    }

    public static String getToken(Context context) {
        return context.getSharedPreferences("_", MODE_PRIVATE).getString("fb", "empty");
    }
}

And then add it to AndroidManifest file

<service
        android:name=".MyFirebaseMessagingService"
        android:stopWithTask="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
</service>

Finally, you are able to use a static method from your Service MyFirebaseMessagingService.getToken(Context);

THE FASTEST BUT DEPRECATED

Log.d("Firebase", "token "+ FirebaseInstanceId.getInstance().getToken());

It's still working when you are using older firebase library than version 17.x.x

How do you change library location in R?

I'm late to the party but I encountered the same thing when I tried to get fancy and move my library and then had files being saved to a folder that was outdated:

.libloc <<- "C:/Program Files/rest_of_your_Library_FileName"

One other point to mention is that for Windows Computers, if you copy the address from Windows Explorer, you have to manually change the '\' to a '/' for the directory to be recognized.

Finding the second highest number in array

My idea is that you assume that first and second members of the array are your first max and second max. Then you take each new member of an array and compare it with the 2nd max. Don't forget to compare 2nd max with the 1st one. If it's bigger, just swap them.

   public static int getMax22(int[] arr){
    int max1 = arr[0];
    int max2 = arr[1];
    for (int i = 2; i < arr.length; i++){
        if (arr[i] > max2)
        {
            max2 = arr[i];
        }

        if (max2 > max1)
        {
            int temp = max1;
            max1 = max2;
            max2 = temp;
        }
    }
     return max2;
}

Check if a variable is a string in JavaScript

var a = new String('')
var b = ''
var c = []

function isString(x) {
  return x !== null && x !== undefined && x.constructor === String
}

console.log(isString(a))
console.log(isString(b))
console.log(isString(c))

How do you get AngularJS to bind to the title attribute of an A tag?

The issue here is your version of AngularJS; ng-attr is not working due to the fact that it was introduced in version 1.1.4. I am unsure as to why title="{{product.shortDesc}}" isn't working for you, but I imagine it is for similar reasons (old Angular version). I tested this on 1.2.9 and it is working for me.

As for the other answers here, this is NOT among the few use cases for ng-attr! This is a simple double-curly-bracket situation:

<a title="{{product.shortDesc}}" ng-bind="product.shortDesc" />

Pipe subprocess standard output to a variable

With a = subprocess.Popen("cdrecord --help",stdout = subprocess.PIPE) , you need to either use a list or use shell=True;

Either of these will work. The former is preferable.

a = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE)

a = subprocess.Popen('cdrecord --help', shell=True, stdout=subprocess.PIPE)

Also, instead of using Popen.stdout.read/Popen.stderr.read, you should use .communicate() (refer to the subprocess documentation for why).

proc = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()

Opening a CHM file produces: "navigation to the webpage was canceled"

other way is to use different third party software. This link shows more third party software to view chm files...

I tried with SumatraPDF and it work fine.

How to replace NaN values by Zeroes in a column of a Pandas Dataframe?

It is not guaranteed that the slicing returns a view or a copy. You can do

df['column'] = df['column'].fillna(value)

Bootstrap 4: responsive sidebar menu to top navbar

It could be done in Bootstrap 4 using the responsive grid columns. One column for the sidebar and one for the main content.

Bootstrap 4 Sidebar switch to Top Navbar on mobile

<div class="container-fluid h-100">
    <div class="row h-100">
        <aside class="col-12 col-md-2 p-0 bg-dark">
            <nav class="navbar navbar-expand navbar-dark bg-dark flex-md-column flex-row align-items-start">
                <div class="collapse navbar-collapse">
                    <ul class="flex-md-column flex-row navbar-nav w-100 justify-content-between">
                        <li class="nav-item">
                            <a class="nav-link pl-0" href="#">Link</a>
                        </li>
                        ..
                    </ul>
                </div>
            </nav>
        </aside>
        <main class="col">
            ..
        </main>
    </div>
</div>

Alternate sidebar to top
Fixed sidebar to top

For the reverse (Top Navbar that becomes a Sidebar), can be done like this example

How to dynamically add and remove form fields in Angular 2

addAccordian(type, data) { console.log(type, data);

let form = this.form;

if (!form.controls[type]) {
  let ownerAccordian = new FormArray([]);
  const group = new FormGroup({});
  ownerAccordian.push(
    this.applicationService.createControlWithGroup(data, group)
  );
  form.controls[type] = ownerAccordian;
} else {
  const group = new FormGroup({});
  (<FormArray>form.get(type)).push(
    this.applicationService.createControlWithGroup(data, group)
  );
}
console.log(this.form);

}

Display alert message and redirect after click on accept

echo "<script>
window.location.href='admin/ahm/panel';
alert('There are no fields to generate a report');
</script>";

Try out this way it works...

First assign the window with the new page where the alert box must be displayed then show the alert box.

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

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

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

for (Method method: clazz.getMethods())

to

for (Field field: clazz.getFields())

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

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

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

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

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

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

    return "";
}

Possible cases for Javascript error: "Expected identifier, string or number"

Had the same issue with a different configuration. This was in an angular factory definition, but I assume it could happen elsewhere as well:

angular.module("myModule").factory("myFactory", function(){
    return
    {
        myMethod : function() // <--- error showing up here
        {
            // method definition
        } 
    }
});

Fix is very exotic:

angular.module("myModule").factory("myFactory", function(){
    return { // <--- notice the absence of the return line
        myMethod : function()
        {
            // method definition
        } 
    }
});

convert iso date to milliseconds in javascript

Try this

_x000D_
_x000D_
var date = new Date("11/21/1987 16:00:00"); // some mock date_x000D_
var milliseconds = date.getTime(); _x000D_
// This will return you the number of milliseconds_x000D_
// elapsed from January 1, 1970 _x000D_
// if your date is less than that date, the value will be negative_x000D_
_x000D_
console.log(milliseconds);
_x000D_
_x000D_
_x000D_

EDIT

You've provided an ISO date. It is also accepted by the constructor of the Date object

_x000D_
_x000D_
var myDate = new Date("2012-02-10T13:19:11+0000");_x000D_
var result = myDate.getTime();_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

Edit

The best I've found is to get rid of the offset manually.

_x000D_
_x000D_
var myDate = new Date("2012-02-10T13:19:11+0000");_x000D_
var offset = myDate.getTimezoneOffset() * 60 * 1000;_x000D_
_x000D_
var withOffset = myDate.getTime();_x000D_
var withoutOffset = withOffset - offset;_x000D_
console.log(withOffset);_x000D_
console.log(withoutOffset);
_x000D_
_x000D_
_x000D_

Seems working. As far as problems with converting ISO string into the Date object you may refer to the links provided.

EDIT

Fixed the bug with incorrect conversion to milliseconds according to Prasad19sara's comment.

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

Javascript's String.fromCharCode(code1, code2, ..., codeN) takes an infinite number of arguments and returns a string of letters whose corresponding ASCII values are code1, code2, ... codeN. Since 97 is 'a' in ASCII, we can adjust for your indexing by adding 97 to your index.

function indexToChar(i) {
  return String.fromCharCode(i+97); //97 in ASCII is 'a', so i=0 returns 'a', 
                                    // i=1 returns 'b', etc
}

unix sort descending order

The presence of the n option attached to the -k5 causes the global -r option to be ignored for that field. You have to specify both n and r at the same level (globally or locally).

sort -t $'\t' -k5,5rn

or

sort -rn -t $'\t' -k5,5

How do I merge a specific commit from one branch into another in Git?

If BranchA has not been pushed to a remote then you can reorder the commits using rebase and then simply merge. It's preferable to use merge over rebase when possible because it doesn't create duplicate commits.

git checkout BranchA
git rebase -i HEAD~113
... reorder the commits so the 10 you want are first ...
git checkout BranchB
git merge [the 10th commit]

Read a variable in bash with a default value

The -e and -t parameter does not work together. i tried some expressions and the result was the following code snippet :

QMESSAGE="SHOULD I DO YES OR NO"
YMESSAGE="I DO"
NMESSAGE="I DO NOT"
FMESSAGE="PLEASE ENTER Y or N"
COUNTDOWN=2
DEFAULTVALUE=n
#----------------------------------------------------------------#
function REQUEST ()
{
read -n1 -t$COUNTDOWN -p "$QMESSAGE ? Y/N " INPUT
    INPUT=${INPUT:-$DEFAULTVALUE}
    if  [ "$INPUT" = "y" -o "$INPUT" = "Y" ] ;then
        echo -e "\n$YMESSAGE\n"
        #COMMANDEXECUTION
    elif    [ "$INPUT" = "n" -o "$INPUT" = "N" ] ;then
        echo -e "\n$NMESSAGE\n"
        #COMMANDEXECUTION
    else
        echo -e "\n$FMESSAGE\n"
    REQUEST
    fi
}
REQUEST

Android TextView padding between lines

You can use lineSpacingExtra and lineSpacingMultiplier in your XML file.

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

The only way to have multiple, separately accessible functions in a single file is to define STATIC METHODS using object-oriented programming. You'd access the function as myClass.static1(), myClass.static2() etc.

OOP functionality is only officially supported since R2008a, so unless you want to use the old, undocumented OOP syntax, the answer for you is no, as explained by @gnovice.

EDIT

One more way to define multiple functions inside a file that are accessible from the outside is to create a function that returns multiple function handles. In other words, you'd call your defining function as [fun1,fun2,fun3]=defineMyFunctions, after which you could use out1=fun1(inputs) etc.

SQL how to make null values come last when sorting ascending

I also just stumbled across this and the following seems to do the trick for me, on MySQL and PostgreSQL:

ORDER BY date IS NULL, date DESC

as found at https://stackoverflow.com/a/7055259/496209

Broken references in Virtualenvs

I was facing the same issue after upgrading brew on my OSX Catalina.

After trying bunch of stuffs, I find the following is the best and easy solution.

At first, delete the virtual env. (Optional)

find myvirtualenv -type l -delete

then recreate a new virtualenv

virtualenv myvirtualenv

Reference: https://www.jeremycade.com/python/osx/homebrew/2015/03/02/fixing-virtualenv-after-a-python-upgrade/

RegEx to extract all matches from string using RegExp.exec

Iterables are nicer:

const matches = (text, pattern) => ({
  [Symbol.iterator]: function * () {
    const clone = new RegExp(pattern.source, pattern.flags);
    let match = null;
    do {
      match = clone.exec(text);
      if (match) {
        yield match;
      }
    } while (match);
  }
});

Usage in a loop:

for (const match of matches('abcdefabcdef', /ab/g)) {
  console.log(match);
}

Or if you want an array:

[ ...matches('abcdefabcdef', /ab/g) ]

Centering controls within a form in .NET (Winforms)?

myControl.Left = (this.ClientSize.Width - myControl.Width) / 2 ;
myControl.Top = (this.ClientSize.Height - myControl.Height) / 2;

How to define an enum with string value?

You can't - enum values have to be integral values. You can either use attributes to associate a string value with each enum value, or in this case if every separator is a single character you could just use the char value:

enum Separator
{
    Comma = ',',
    Tab = '\t',
    Space = ' '
}

(EDIT: Just to clarify, you can't make char the underlying type of the enum, but you can use char constants to assign the integral value corresponding to each enum value. The underlying type of the above enum is int.)

Then an extension method if you need one:

public string ToSeparatorString(this Separator separator)
{
    // TODO: validation
    return ((char) separator).ToString();
}

Targeting .NET Framework 4.5 via Visual Studio 2010

There are pretty limited scenarios that I can think of where this would be useful, but let's assume you can't get funds to purchase VS2012 or something to that effect. If that's the case and you have Windows 7+ and VS 2010 you may be able to use the following hack I put together which seems to work (but I haven't fully deployed an application using this method yet).

  1. Backup your project file!!!

  2. Download and install the Windows 8 SDK which includes the .NET 4.5 SDK.

  3. Open your project in VS2010.

  4. Create a text file in your project named Compile_4_5_CSharp.targets with the following contents. (Or just download it here - Make sure to remove the ".txt" extension from the file name):

    <Project DefaultTargets="Build"
     xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    
        <!-- Change the target framework to 4.5 if using the ".NET 4.5" configuration -->
        <PropertyGroup Condition=" '$(Platform)' == '.NET 4.5' ">
            <DefineConstants Condition="'$(DefineConstants)'==''">
                TARGETTING_FX_4_5
            </DefineConstants>
            <DefineConstants Condition="'$(DefineConstants)'!='' and '$(DefineConstants)'!='TARGETTING_FX_4_5'">
                $(DefineConstants);TARGETTING_FX_4_5
            </DefineConstants>
            <PlatformTarget Condition="'$(PlatformTarget)'!=''"/>
            <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
        </PropertyGroup>
    
        <!-- Import the standard C# targets -->
        <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
    
        <!-- Add .NET 4.5 as an available platform -->
        <PropertyGroup>
           <AvailablePlatforms>$(AvailablePlatforms),.NET 4.5</AvailablePlatforms>
        </PropertyGroup>
    </Project>
    
  5. Unload your project (right click -> unload).

  6. Edit the project file (right click -> Edit *.csproj).

  7. Make the following changes in the project file:

    a. Replace the default Microsoft.CSharp.targets with the target file created in step 4

    <!-- Old Import Entry -->
    <!-- <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> -->
    
    <!-- New Import Entry -->
    <Import Project="Compile_4_5_CSharp.targets" />
    

    b. Change the default platform to .NET 4.5

    <!-- Old default platform entry -->
    <!-- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> -->
    
    <!-- New default platform entry -->
    <Platform Condition=" '$(Platform)' == '' ">.NET 4.5</Platform>
    

    c. Add AnyCPU platform to allow targeting other frameworks as specified in the project properties. This should be added just before the first <ItemGroup> tag in the file

    <PropertyGroup Condition="'$(Platform)' == 'AnyCPU'">
        <PlatformTarget>AnyCPU</PlatformTarget>
    </PropertyGroup>
    
    .
    .
    .
    <ItemGroup>
    .
    .
    .
    
  8. Save your changes and close the *.csproj file.

  9. Reload your project (right click -> Reload Project).

  10. In the configuration manager (Build -> Configuration Manager) make sure the ".NET 4.5" platform is selected for your project.

  11. Still in the configuration manager, create a new solution platform for ".NET 4.5" (you can base it off "Any CPU") and make sure ".NET 4.5" is selected for the solution.

  12. Build your project and check for errors.

  13. Assuming the build completed you can verify that you are indeed targeting 4.5 by adding a reference to a 4.5 specific class to your source code:

    using System;
    using System.Text;
    
    namespace testing
    {
        using net45check = System.Reflection.ReflectionContext;
    }
    
  14. When you compile using the ".NET 4.5" platform the build should succeed. When you compile under the "Any CPU" platform you should get a compiler error:

    Error 6: The type or namespace name 'ReflectionContext' does not exist in
    the namespace 'System.Reflection' (are you missing an assembly reference?)
    

On - window.location.hash - Change?

A decent implementation can be found at http://code.google.com/p/reallysimplehistory/. The only (but also) problem and bug it has is: in Internet Explorer modifying the location hash manually will reset the entire history stack (this is a browser issue and it cannot be solved).

Note, Internet Explorer 8 does have support for the "hashchange" event, and since it is becoming part of HTML5 you may expect other browsers to catch up.

"This project is incompatible with the current version of Visual Studio"

I checked if i could create a new solution and was unable because SSAS,SSIS and SSRS weren't there as options.

I downloaded SSDT from here and installed and it worked...

https://docs.microsoft.com/en-us/sql/ssdt/download-sql-server-data-tools-ssdt?view=sql-server-2017

Send XML data to webservice using php curl

Check this one. It will work.

function fetch($i1,$i2,$i3,$i4)
{
$input_data = '<I> 
                <i1>'.$i1.'</i1> 
                <i2>'.$i2.'</i2> 
                <i3>'.$i2.'</i3> 
                <i4>'.$i3.'</i4> 
              </I>';
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_PORT => "8080",
  CURLOPT_URL => "http://192.168.1.100:8080/avaliablity",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $input_data,
  CURLOPT_HTTPHEADER => array(
    "Cache-Control: no-cache",
    "Content-Type: application/xml"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
}

fetch('i1','i2','i3','i4');

How to determine if a decimal/double is an integer?

You can use String formatting for the double type. Here is an example:

double val = 58.6547;
String.Format("{0:0.##}", val);      
//Output: "58.65"

double val = 58.6;
String.Format("{0:0.##}", val);      
//Output: "58.6"

double val = 58.0;
String.Format("{0:0.##}", val);      
//Output: "58"

Let me know if this doesn't help.

Proper usage of Java -D command-line parameters

That should be:

java -Dtest="true" -jar myApplication.jar

Then the following will return the value:

System.getProperty("test");

The value could be null, though, so guard against an exception using a Boolean:

boolean b = Boolean.parseBoolean( System.getProperty( "test" ) );

Note that the getBoolean method delegates the system property value, simplifying the code to:

if( Boolean.getBoolean( "test" ) ) {
   // ...
}

Effective method to hide email from spam bots

If you have php support, you can do something like this:

<img src="scriptname.php">

And the scriptname.php:

<?php
header("Content-type: image/png");
// Your email address which will be shown in the image
$email    =    "[email protected]";
$length    =    (strlen($email)*8);
$im = @ImageCreate ($length, 20)
     or die ("Kann keinen neuen GD-Bild-Stream erzeugen");
$background_color = ImageColorAllocate ($im, 255, 255, 255); // White: 255,255,255
$text_color = ImageColorAllocate ($im, 55, 103, 122);
imagestring($im, 3,5,2,$email, $text_color);
imagepng ($im);
?>

Remove ALL styling/formatting from hyperlinks

if you state a.redLink{color:red;} then to keep this on hover and such add a.redLink:hover{color:red;} This will make sure no other hover states will change the color of your links

Form Submission without page refresh

<!-- index.php -->
    <!DOCTYPE html>
    <html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    </head>
    <body>
    <form id="myForm">
        <input type="text" name="fname" id="fname"/>
        <input type="submit" name="click" value="button" />
    </form>
    <script>
    $(document).ready(function(){

         $(function(){
            $("#myForm").submit(function(event){
                event.preventDefault();
                $.ajax({
                    method: 'POST',
                    url: 'submit.php',
                    dataType: "json",
                    contentType: "application/json",
                    data : $('#myForm').serialize(),
                    success: function(data){
                        alert(data);
                    },
                    error: function(xhr, desc, err){
                        console.log(err);
                    }
                });
            });
        });
    });
    </script>
    </body>
    </html>
<!-- submit.php -->
<?php
$value ="call";
header('Content-Type: application/json');
echo json_encode($value);
?>

How do I create a custom Error in JavaScript?

If anyone is curious on how to create a custom error and get the stack trace:

function CustomError(message) {
  this.name = 'CustomError';
  this.message = message || '';
  var error = new Error(this.message);
  error.name = this.name;
  this.stack = error.stack;
}
CustomError.prototype = Object.create(Error.prototype);

try {
  throw new CustomError('foobar');
}
catch (e) {
  console.log('name:', e.name);
  console.log('message:', e.message);
  console.log('stack:', e.stack);
}

Can someone give an example of cosine similarity, in a very simple, graphical way?

This is a simple Python code which implements cosine similarity.

from scipy import linalg, mat, dot
import numpy as np

In [12]: matrix = mat( [[2, 1, 0, 2, 0, 1, 1, 1],[2, 1, 1, 1, 1, 0, 1, 1]] )

In [13]: matrix
Out[13]: 
matrix([[2, 1, 0, 2, 0, 1, 1, 1],
        [2, 1, 1, 1, 1, 0, 1, 1]])
In [14]: dot(matrix[0],matrix[1].T)/np.linalg.norm(matrix[0])/np.linalg.norm(matrix[1])
Out[14]: matrix([[ 0.82158384]])

How to use in jQuery :not and hasClass() to get a specific element without a class

I don't know if this was true at the time of the original posting, but the siblings method allows selectors, so a reduction of what the OP listed should work.

 $(this).siblings(':not(.closedTab)');

C# adding a character in a string

I had to do something similar, trying to convert a string of numbers into a timespan by adding in : and .. Basically I was taking 235959999 and needing to convert it to 23:59:59.999. For me it was easy because I knew where I needed to "insert" said characters.

ts = ts.Insert(6,".");
ts = ts.Insert(4,":");
ts = ts.Insert(2,":");

Basically reassigning ts to itself with the inserted character. I worked my way from the back to front, because I was lazy and didn't want to do additional math for the other inserted characters.

You could try something similar by doing:

alpha = alpha.Insert(5,"-");
alpha = alpha.Insert(11,"-"); //add 1 to account for 1 -
alpha = alpha.Insert(17,"-"); //add 2 to account for 2 -
...

What is android:ems attribute in Edit Text?

An "em" is a typographical unit of width, the width of a wide-ish letter like "m" pronounced "em". Similarly there is an "en". Similarly "en-dash" and "em-dash" for – and —

-Tim Bray

S3 - Access-Control-Allow-Origin Header

Most of the answers above didn't work. I was trying to upload image to S3 bucket using react-s3 and I got this

Cross-Origin Request Blocked

error.

All you have to do is add CORS Config in s3 Bucket Go to S3 Bucket -> Persmission -> CORS Configuration And paste the below

<CORSConfiguration>
 <CORSRule>
   <AllowedOrigin>*</AllowedOrigin>

   <AllowedMethod>PUT</AllowedMethod>
   <AllowedMethod>POST</AllowedMethod>
   <AllowedMethod>DELETE</AllowedMethod>

   <AllowedHeader>*</AllowedHeader>
 </CORSRule>
 <CORSRule>
   <AllowedOrigin>*</AllowedOrigin>

   <AllowedMethod>PUT</AllowedMethod>
   <AllowedMethod>POST</AllowedMethod>
   <AllowedMethod>DELETE</AllowedMethod>

   <AllowedHeader>*</AllowedHeader>
 </CORSRule>
 <CORSRule>
   <AllowedOrigin>*</AllowedOrigin>
   <AllowedMethod>GET</AllowedMethod>
 </CORSRule>
</CORSConfiguration>

Replace * with your website url. Reference : AWS CORS Settings

What is tail call optimization?

Note first of all that not all languages support it.

TCO applys to a special case of recursion. The gist of it is, if the last thing you do in a function is call itself (e.g. it is calling itself from the "tail" position), this can be optimized by the compiler to act like iteration instead of standard recursion.

You see, normally during recursion, the runtime needs to keep track of all the recursive calls, so that when one returns it can resume at the previous call and so on. (Try manually writing out the result of a recursive call to get a visual idea of how this works.) Keeping track of all the calls takes up space, which gets significant when the function calls itself a lot. But with TCO, it can just say "go back to the beginning, only this time change the parameter values to these new ones." It can do that because nothing after the recursive call refers to those values.

Parsing JSON from URL

You could use org.apache.commons.io.IOUtils for downloading and org.json.JSONTokener for parsing:

JSONObject jo = (JSONObject) new JSONTokener(IOUtils.toString(new URL("http://gdata.youtube.com/feeds/api/videos/SIFL9qfmu5U?alt=json"))).nextValue();
System.out.println(jo.getString("version"));

remove duplicates from sql union

Others have already answered your direct question, but perhaps you could simplify the query to eliminate the question (or have I missed something, and a query like the following will really produce substantially different results?):

select * 
    from calls c join users u
        on c.assigned_to = u.user_id 
        or c.requestor_id = u.user_id
    where u.dept = 4

Pad a number with leading zeros in JavaScript

Try:

String.prototype.lpad = function(padString, length) {
    var str = this;
    while (str.length < length)
        str = padString + str;
    return str;
}

Now test:

var str = "5";
alert(str.lpad("0", 4)); //result "0005"
var str = "10"; // note this is string type
alert(str.lpad("0", 4)); //result "0010"

DEMO


In ECMAScript 2017 , we have new method padStart and padEnd which has below syntax.

"string".padStart(targetLength [,padString]):

So now we can use

const str = "5";
str.padStart(4, "0"); // "0005"

Creating a left-arrow button (like UINavigationBar's "back" style) on a UIToolbar

Why are you doing this? If you want something that looks like a navigation bar, use UINavigationBar.

Toolbars have specific visual style associated with them. The Human Interface Guidelines for the iPhone state:

A toolbar appears at the bottom edge of the screen and contains buttons that perform actions related to objects in the current view.

It then gives several visual examples of roughly square icons with no text. I would urge you to follow the HIG on this.

How can I kill whatever process is using port 8080 so that I can vagrant up?

I needed to run this command

sudo lsof -i :80 # checks port 8080

Then i got

COMMAND   PID USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
acwebseca 312 root   36u  IPv4 0x34ae935da20560c1      0t0  TCP 192.168.1.3:50585->104.25.53.12:http (ESTABLISHED)

show which service is using the PID

ps -ef 312

Then I got this

  UID   PID  PPID   C STIME   TTY           TIME CMD
    0   312    58   0  9:32PM ??         0:02.70 /opt/cisco/anyconnect/bin/acwebsecagent -console

To uninstall cisco web security agent run

sudo /opt/cisco/anyconnect/bin/websecurity_uninstall.sh

credits to: http://tobyaw.livejournal.com/315396.html

SQL MERGE statement to update data

Assuming you want an actual SQL Server MERGE statement:

MERGE INTO dbo.energydata WITH (HOLDLOCK) AS target
USING dbo.temp_energydata AS source
    ON target.webmeterID = source.webmeterID
    AND target.DateTime = source.DateTime
WHEN MATCHED THEN 
    UPDATE SET target.kWh = source.kWh
WHEN NOT MATCHED BY TARGET THEN
    INSERT (webmeterID, DateTime, kWh)
    VALUES (source.webmeterID, source.DateTime, source.kWh);

If you also want to delete records in the target that aren't in the source:

MERGE INTO dbo.energydata WITH (HOLDLOCK) AS target
USING dbo.temp_energydata AS source
    ON target.webmeterID = source.webmeterID
    AND target.DateTime = source.DateTime
WHEN MATCHED THEN 
    UPDATE SET target.kWh = source.kWh
WHEN NOT MATCHED BY TARGET THEN
    INSERT (webmeterID, DateTime, kWh)
    VALUES (source.webmeterID, source.DateTime, source.kWh)
WHEN NOT MATCHED BY SOURCE THEN
    DELETE;

Because this has become a bit more popular, I feel like I should expand this answer a bit with some caveats to be aware of.

First, there are several blogs which report concurrency issues with the MERGE statement in older versions of SQL Server. I do not know if this issue has ever been addressed in later editions. Either way, this can largely be worked around by specifying the HOLDLOCK or SERIALIZABLE lock hint:

MERGE INTO dbo.energydata WITH (HOLDLOCK) AS target
[...]

You can also accomplish the same thing with more restrictive transaction isolation levels.

There are several other known issues with MERGE. (Note that since Microsoft nuked Connect and didn't link issues in the old system to issues in the new system, these older issues are hard to track down. Thanks, Microsoft!) From what I can tell, most of them are not common problems or can be worked around with the same locking hints as above, but I haven't tested them.

As it is, even though I've never had any problems with the MERGE statement myself, I always use the WITH (HOLDLOCK) hint now, and I prefer to use the statement only in the most straightforward of cases.

JavaScript OR (||) variable assignment explanation

It's setting the new variable (z) to either the value of x if it's "truthy" (non-zero, a valid object/array/function/whatever it is) or y otherwise. It's a relatively common way of providing a default value in case x doesn't exist.

For example, if you have a function that takes an optional callback parameter, you could provide a default callback that doesn't do anything:

function doSomething(data, callback) {
    callback = callback || function() {};
    // do stuff with data
    callback(); // callback will always exist
}

Converting float to char*

char array[10];
snprintf(array, sizeof(array), "%f", 3.333333);

Kill a postgresql session/connection

OSX, Postgres 9.2 (installed with homebrew)

$ launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
$ pg_ctl restart -D /usr/local/var/postgres
$ launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist


If your datadir is elsewhere you can find out where it is by examining the output of ps aux | grep postgres

Instagram how to get my user id from username?

I tried all the aforementioned solutions and none works. I guess Instagram has accelerated their changes. I tried, however, the browser console method and played around a bit and found this command that gave me the user ID.

window._sharedData.entry_data.ProfilePage[0].graphql.user.id

You just visit a profile's page and enter this command in the console. You might need to refresh the page for this to work though. (I had to post this as an answer, because of my low reputation)

Importing JSON into an Eclipse project

Download json from java2s website then include in your project. In your class add these package java_basic;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

Sorting Python list based on the length of the string

The same as in Eli's answer - just using a shorter form, because you can skip a lambda part here.

Creating new list:

>>> xs = ['dddd','a','bb','ccc']
>>> sorted(xs, key=len)
['a', 'bb', 'ccc', 'dddd']

In-place sorting:

>>> xs.sort(key=len)
>>> xs
['a', 'bb', 'ccc', 'dddd']

Run a Command Prompt command from Desktop Shortcut

You can also create a shortcut on desktop that can run a specific command or even a batch file by just typing the command in "Type the Location of Item" bar in create shortcut wizard

  1. Right click on Desktop.
  2. Enter the command in "Type the Location of Item" bar.
  3. Double click the shortcut to run the command.

Found detailed Instructions here

Disable mouse scroll wheel zoom on embedded Google Maps

if you have an iframe using Google map embedded API like this :

 <iframe width="320" height="400" frameborder="0" src="https://www.google.com/maps/embed/v1/place?q=Cagli ... "></iframe>

you can add this css style: pointer-event:none; ES.

<iframe width="320" height="400" frameborder="0" style="pointer-event:none;" src="https://www.google.com/maps/embed/v1/place?q=Cagli ... "></iframe>

How to run jenkins as a different user

If you really want to run Jenkins as you, I suggest you check out my Jenkins.app. An alternative, easy way to run Jenkins on Mac.

See https://github.com/stisti/jenkins-app/

Download it from https://github.com/stisti/jenkins-app/downloads

How to convert existing non-empty directory into a Git working directory and push files to a remote repository

This is how I do. I have added explanation to understand what the heck is going on.

Initialize Local Repository

  • first initialize Git with

    git init

  • Add all Files for version control with

    git add .

  • Create a commit with message of your choice

    git commit -m 'AddingBaseCode'

Initialize Remote Repository

  • Create a project on GitHub and copy the URL of your project . as shown below:

    enter image description here

Link Remote repo with Local repo

  • Now use copied URL to link your local repo with remote GitHub repo. When you clone a repository with git clone, it automatically creates a remote connection called origin pointing back to the cloned repository. The command remote is used to manage set of tracked repositories.

    git remote add origin https://github.com/hiteshsahu/Hassium-Word.git

Synchronize

  • Now we need to merge local code with remote code. This step is critical otherwise we won't be able to push code on GitHub. You must call 'git pull' before pushing your code.

    git pull origin master --allow-unrelated-histories

Commit your code

  • Finally push all changes on GitHub

    git push -u origin master

iOS - UIImageView - how to handle UIImage image orientation

This method first checks the current orientation of UIImage and then it changes the orientation in a clockwise way and return UIImage.You can show this image as

self.imageView.image = rotateImage(currentUIImage)

   func rotateImage(image:UIImage)->UIImage
    {
        var rotatedImage = UIImage();
        switch image.imageOrientation
        {
            case UIImageOrientation.Right:
            rotatedImage = UIImage(CGImage:image.CGImage!, scale: 1, orientation:UIImageOrientation.Down);

           case UIImageOrientation.Down:
            rotatedImage = UIImage(CGImage:image.CGImage!, scale: 1, orientation:UIImageOrientation.Left);

            case UIImageOrientation.Left:
            rotatedImage = UIImage(CGImage:image.CGImage!, scale: 1, orientation:UIImageOrientation.Up);

             default:
            rotatedImage = UIImage(CGImage:image.CGImage!, scale: 1, orientation:UIImageOrientation.Right);
        }
        return rotatedImage;
    }

Swift 4 version

func rotateImage(image:UIImage) -> UIImage
    {
        var rotatedImage = UIImage()
        switch image.imageOrientation
        {
        case .right:
            rotatedImage = UIImage(cgImage: image.cgImage!, scale: 1.0, orientation: .down)

        case .down:
            rotatedImage = UIImage(cgImage: image.cgImage!, scale: 1.0, orientation: .left)

        case .left:
            rotatedImage = UIImage(cgImage: image.cgImage!, scale: 1.0, orientation: .up)

        default:
            rotatedImage = UIImage(cgImage: image.cgImage!, scale: 1.0, orientation: .right)
        }

        return rotatedImage
    }

How to concatenate properties from multiple JavaScript objects

ECMAscript 6 introduced Object.assign() to achieve this natively in Javascript.

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

MDN documentation on Object.assign()

_x000D_
_x000D_
var o1 = { a: 1 };_x000D_
var o2 = { b: 2 };_x000D_
var o3 = { c: 3 };_x000D_
_x000D_
var obj = Object.assign({}, o1, o2, o3);_x000D_
console.log(obj); // { a: 1, b: 2, c: 3 }
_x000D_
_x000D_
_x000D_

Object.assign is supported in many modern browsers but not yet all of them. Use a transpiler like Babel and Traceur to generate backwards-compatible ES5 JavaScript.

Override element.style using CSS

Of course the !important trick is decisive here, but targeting more specifically may help not only to have your override actually applied (weight criteria can rule over !important) but also to avoid overriding unintended elements.

With the developer tools of your browser, identify the exact value of the offending style attribute; e.g.:

"font-family: arial, helvetica, sans-serif;"

or

"display: block;"

Then, decide which branch of selectors you will override; you can broaden or narrow your choice to fit your needs, e.g.:

p span

or

section.article-into.clearfix p span

Finally, in your custom.css, use the [attribute^=value] selector and the !important declaration:

p span[style^="font-family: arial"] {
  font-family: "Times New Roman", Times, serif !important;
}

Note you don't have to quote the whole style attribute value, just enough to unambigously match the string.

Find all files with name containing string

Use grep as follows:

grep -R "touch" .

-R means recurse. If you would rather not go into the subdirectories, then skip it.

-i means "ignore case". You might find this worth a try as well.

Call a Subroutine from a different Module in VBA

Prefix the call with Module2 (ex. Module2.IDLE). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.

Android Studio Google JAR file causing GC overhead limit exceeded error

I disable my Instant Run by:

Menu Preference ? Build ? Instant Run "Enable Instant Run to hot swap code"

I guess it is the Instant Run that makes the build slow and creates a large size pidXXX.hprof file which causes the AndroidStudio gc overhead limit exceeded.

(My device SDK is 19.)

How to filter by IP address in Wireshark?

in our use we have to capture with host x.x.x.x. or (vlan and host x.x.x.x)

anything less will not capture? I am not sure why but that is the way it works!

Count how many files in directory PHP

You can simply do the following :

$fi = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);
printf("There were %d Files", iterator_count($fi));

WPF checkbox binding

This works for me (essential code only included, fill more for your needs):

In XAML a user control is defined:

<UserControl x:Class="Mockup.TestTab" ......>
    <!-- a checkbox somewhere within the control -->
    <!-- IsChecked is bound to Property C1 of the DataContext -->
    <CheckBox Content="CheckBox 1" IsChecked="{Binding C1, Mode=TwoWay}" />
</UserControl>

In code behind for UserControl

public partial class TestTab : UserControl
{
    public TestTab()
    {
        InitializeComponent();  // the standard bit

    // then we set the DataContex of TestTab Control to a MyViewModel object
    // this MyViewModel object becomes the DataContext for all controls
         // within TestTab ... including our CheckBox
         DataContext = new MyViewModel(....);
    }

}

Somewhere in solution class MyViewModel is defined

public class MyViewModel : INotifyPropertyChanged 
{
    public event PropertyChangedEventHandler PropertyChanged;
    private bool m_c1 = true;

    public bool C1 {
        get { return m_c1; }
        set {
            if (m_c1 != value) {
                m_c1 = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("C1"));
            }
        }
    }
}

How do I get the path of the current executed file in Python?

The short answer is that there is no guaranteed way to get the information you want, however there are heuristics that work almost always in practice. You might look at How do I find the location of the executable in C?. It discusses the problem from a C point of view, but the proposed solutions are easily transcribed into Python.

Why does python use 'else' after for and while loops?

Because they didn't want to introduce a new keyword to the language. Each one steals an identifier and causes backwards compatibility problems, so it's usually a last resort.

400 BAD request HTTP error code meaning?

As a complementary, for those who might meet the same issue as mine, I'm using $.ajax to post form data to server and I also got the 400 error at first.

Assume I have a javascript variable,

var formData = {
    "name":"Gearon",
    "hobby":"Be different"
    }; 

Do not use variable formData directly as the value of key data like below:

$.ajax({
    type: "post",
    dataType: "json",
    url: "http://localhost/user/add",
    contentType: "application/json",
    data: formData,
    success: function(data, textStatus){
        alert("Data: " + data + "\nStatus: " + status); 
    }
});

Instead, use JSON.stringify to encapsulate the formData as below:

$.ajax({
    type: "post",
    dataType: "json",
    url: "http://localhost/user/add",
    contentType: "application/json",
    data: JSON.stringify(formData),
    success: function(data, textStatus){
        alert("Data: " + data + "\nStatus: " + status); 
    }
});

Anyway, as others have illustrated, the error is because the server could not recognize the request cause malformed syntax, I'm just raising a instance at practice. Hope it would be helpful to someone.

jQuery add blank option to top of list and make selected to existing dropdown

This worked:

$("#theSelectId").prepend("<option value='' selected='selected'></option>");

Firebug Output:

<select id="theSelectId">
  <option selected="selected" value=""/>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

You could also use .prependTo if you wanted to reverse the order:

?$("<option>", { value: '', selected: true }).prependTo("#theSelectId");???????????

Error inflating class android.support.design.widget.NavigationView

As Parag Naik correctly mentions (and L?ng Hoàng expands on), the problem arises when setting textColorPrimary to something other than a color state list. So you could set textColorPrimary as a state list. There is an issue in the android bug tracker about colorPrimary being a state list with only one color: https://code.google.com/p/android/issues/detail?id=172353

So for your theme in styles.xml:

<style name="Base.Theme.Hopster" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_dark</item>
    <item name="colorAccent">@color/accent</item>

    <item name="android:textColorPrimary">@color/primary_color_statelist</item>
</style>

And the actual primary_color_statelist.xml file:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- This is used when the Navigation Item is checked -->
    <item android:color="@color/primary_text_selected" android:state_checked="true" />
    <!-- This is the default text color -->
    <item android:color="@color/primary_text" />
</selector>

Remove all constraints affecting a UIView

There are two ways of on how to achieve that according to Apple Developer Documentation

1. NSLayoutConstraint.deactivateConstraints

This is a convenience method that provides an easy way to deactivate a set of constraints with one call. The effect of this method is the same as setting the isActive property of each constraint to false. Typically, using this method is more efficient than deactivating each constraint individually.

// Declaration
class func deactivate(_ constraints: [NSLayoutConstraint])

// Usage
NSLayoutConstraint.deactivate(yourView.constraints)

2. UIView.removeConstraints (Deprecated for >= iOS 8.0)

When developing for iOS 8.0 or later, use the NSLayoutConstraint class’s deactivateConstraints: method instead of calling the removeConstraints: method directly. The deactivateConstraints: method automatically removes the constraints from the correct views.

// Declaration
func removeConstraints(_ constraints: [NSLayoutConstraint])`

// Usage
yourView.removeConstraints(yourView.constraints)

Tips

Using Storyboards or XIBs can be such a pain at configuring the constraints as mentioned on your scenario, you have to create IBOutlets for each ones you want to remove. Even so, most of the time Interface Builder creates more trouble than it solves.

Therefore when having very dynamic content and different states of the view, I would suggest:

  1. Creating your views programmatically
  2. Layout them and using NSLayoutAnchor
  3. Append each constraint that might get removed later to an array
  4. Clear them every time before applying the new state

Simple Code

private var customConstraints = [NSLayoutConstraint]()

private func activate(constraints: [NSLayoutConstraint]) {
    customConstraints.append(contentsOf: constraints)
    customConstraints.forEach { $0.isActive = true }
}

private func clearConstraints() {
    customConstraints.forEach { $0.isActive = false }
    customConstraints.removeAll()
}

private func updateViewState() {
    clearConstraints()

    let constraints = [
        view.leadingAnchor.constraint(equalTo: parentView.leadingAnchor),
        view.trailingAnchor.constraint(equalTo: parentView.trailingAnchor),
        view.topAnchor.constraint(equalTo: parentView.topAnchor),
        view.bottomAnchor.constraint(equalTo: parentView.bottomAnchor)
    ]

    activate(constraints: constraints)

    view.layoutIfNeeded()
}

References

  1. NSLayoutConstraint
  2. UIView

What are the differences between LinearLayout, RelativeLayout, and AbsoluteLayout?

LinearLayout - In LinearLayout, views are organized either in vertical or horizontal orientation.

RelativeLayout - RelativeLayout is way more complex than LinearLayout, hence provides much more functionalities. Views are placed, as the name suggests, relative to each other.

FrameLayout - It behaves as a single object and its child views are overlapped over each other. FrameLayout takes the size of as per the biggest child element.

Coordinator Layout - This is the most powerful ViewGroup introduced in Android support library. It behaves as FrameLayout and has a lot of functionalities to coordinate amongst its child views, for example, floating button and snackbar, Toolbar with scrollable view.

Ruby, Difference between exec, system and %x() or Backticks

system

The system method calls a system program. You have to provide the command as a string argument to this method. For example:

>> system("date")
Wed Sep 4 22:03:44 CEST 2013
=> true

The invoked program will use the current STDIN, STDOUT and STDERR objects of your Ruby program. In fact, the actual return value is either true, false or nil. In the example the date was printed through the IO object of STDIN. The method will return true if the process exited with a zero status, false if the process exited with a non-zero status and nil if the execution failed.

As of Ruby 2.6, passing exception: true will raise an exception instead of returning false or nil:

>> system('invalid')
=> nil

>> system('invalid', exception: true)
Traceback (most recent call last):
...
Errno::ENOENT (No such file or directory - invalid)

Another side effect is that the global variable $? is set to a Process::Status object. This object will contain information about the call itself, including the process identifier (PID) of the invoked process and the exit status.

>> system("date")
Wed Sep 4 22:11:02 CEST 2013
=> true
>> $?
=> #<Process::Status: pid 15470 exit 0>

Backticks

Backticks (``) call a system program and return its output. As opposed to the first approach, the command is not provided through a string, but by putting it inside a backticks pair.

>> `date`
=> Wed Sep 4 22:22:51 CEST 2013   

The global variable $? is set through the backticks, too. With backticks you can also make use string interpolation.

%x()

Using %x is an alternative to the backticks style. It will return the output, too. Like its relatives %w and %q (among others), any delimiter will suffice as long as bracket-style delimiters match. This means %x(date), %x{date} and %x-date- are all synonyms. Like backticks %x can make use of string interpolation.

exec

By using Kernel#exec the current process (your Ruby script) is replaced with the process invoked through exec. The method can take a string as argument. In this case the string will be subject to shell expansion. When using more than one argument, then the first one is used to execute a program and the following are provided as arguments to the program to be invoked.

Open3.popen3

Sometimes the required information is written to standard input or standard error and you need to get control over those as well. Here Open3.popen3 comes in handy:

require 'open3'

Open3.popen3("curl http://example.com") do |stdin, stdout, stderr, thread|
   pid = thread.pid
   puts stdout.read.chomp
end

Stretch and scale CSS background

I would like to point out that this is equivalent to doing:

html { width: 100%; height: 100%; }
body { width: 100%; height: 100%; /* Add background image or gradient to stretch here. */}

How to select the Date Picker In Selenium WebDriver

From Java 8 you can use this simple method for picking a random date from the date picker

List<WebElement> datePickerDays = driver.findElements(By.tagName("td"));
datePickerDays.stream().filter(e->e.getText().equals(whichDateYouWantToClick)).findFirst().get().click();

How to rename a directory/folder on GitHub website?

If you have GitHub Desktop, change the names of the directories on your computer and then push the update from your desktop to your github account and it changes them there. :)

Hope it helps!

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

As others pointed out, this message is coming from your shell prompt. The problem is that in a freshly created repository HEAD (.git/HEAD) points to a ref that doesn't exist yet.

% git init test
Initialized empty shared Git repository in /Users/jhelwig/tmp/test/.git/
% cd test
% cat .git/HEAD
ref: refs/heads/master
% ls -l .git/refs/heads
total 0
% git rev-parse HEAD
HEAD
fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions

It looks like rev-parse is being used without sufficient error checking before-hand. After the first commit has been created .git/refs/heads looks a bit different and git rev-parse HEAD will no longer fail.

% ls -l .git/refs/heads
total 4
-rw------- 1 jhelwig staff 41 Oct 14 16:07 master
% git rev-parse HEAD
af0f70f8962f8b88eef679a1854991cb0f337f89

In the function that updates the Git information for the rest of my shell prompt (heavily modified version of wunjo prompt theme for ZSH), I have the following to get around this:

zgit_info_update() {
    zgit_info=()

    local gitdir=$(git rev-parse --git-dir 2>/dev/null)
    if [ $? -ne 0 ] || [ -z "$gitdir" ]; then
        return
    fi

    # More code ...
}

Concat a string to SELECT * MySql

If you want to concatenate the fields using / as a separator, you can use concat_ws:

select concat_ws('/', col1, col2, col3) from mytable

You cannot escape listing the columns in the query though. The *-syntax works only in "select * from". You can list the columns and construct the query dynamically though.

Github "Updates were rejected because the remote contains work that you do not have locally."

I followed these steps:

Pull the master:

git pull origin master

This will sync your local repo with the Github repo. Add your new file and then:

git add .

Commit the changes:

git commit -m "adding new file  Xyz"

Finally, push the origin master:

git push origin master

Refresh your Github repo, you will see the newly added files.