Programs & Examples On #Accelerate framework

The Accelerate.framework is a set of high-performance numerical libraries provided by Apple for iOS and OS X. It provides APIs for signal and image processing, linear algebra, and mathematical operations on vector data.

Best way to write to the console in PowerShell

The middle one writes to the pipeline. Write-Host and Out-Host writes to the console. 'echo' is an alias for Write-Output which writes to the pipeline as well. The best way to write to the console would be using the Write-Host cmdlet.

When an object is written to the pipeline it can be consumed by other commands in the chain. For example:

"hello world" | Do-Something

but this won't work since Write-Host writes to the console, not to the pipeline (Do-Something will not get the string):

Write-Host "hello world" | Do-Something

How to display a "busy" indicator with jQuery?

I did it in my project ,

make a div with back ground url as gif , which is nothing but animation gif

<div class="busyindicatorClass"> </div>

.busyindicatorClass
{
background-url///give animation here
}

in your ajax call , add this class to the div and in ajax success remove the class.

it will do the trick thatsit.

let me know if you need antthing else , i can give you more details

in the ajax success remove the class

success: function(data) {
    remove class using jquery
  }

Get spinner selected items text?

TextView textView = (TextView)mySpinner.getSelectedView();
String result = textView.getText().toString();

Hide Command Window of .BAT file that Executes Another .EXE File

I haven't really found a good way to do that natively, so I just use a utility called hstart which does it for me. If there's a neater way to do it, that would be nice.

JTable won't show column headers

    public table2() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 485, 218);
    setTitle("jtable");
    getContentPane().setLayout(null);

    String data[][] = { { "Row1/1", "Row1/2", "Row1/3" },
            { "Row2/1", "Row2/2", "Row2/3" },
            { "Row3/1", "Row3/2", "Row3/3" },
            { "Row4/1", "Row4/2", "Row4/3" }, };

    String header[] = { "Column 1", "Column 2", "Column 3" };

    // Table
    JTable table = new JTable(data,header);


    // ScrollPane
    JScrollPane scrollPane = new JScrollPane(table);
    scrollPane.setBounds(36, 37, 407, 79);
    getContentPane().add(scrollPane);

   }

}

try this!!

How do you get the file size in C#?

It returns the file contents length

Ignore python multiple return value

One common convention is to use a "_" as a variable name for the elements of the tuple you wish to ignore. For instance:

def f():
    return 1, 2, 3

_, _, x = f()

Why does writeObject throw java.io.NotSerializableException and how do I fix it?

Make the class serializable by implementing the interface java.io.Serializable.

  • java.io.Serializable - Marker Interface which does not have any methods in it.
  • Purpose of Marker Interface - to tell the ObjectOutputStream that this object is a serializable object.

How to add a custom Ribbon tab using VBA?

The answers on here are specific to using the custom UI Editor. I spent some time creating the interface without that wonderful program, so I am documenting the solution here to help anyone else decide if they need that custom UI editor or not.

I came across the following microsoft help webpage - https://msdn.microsoft.com/en-us/library/office/ff861787.aspx. This shows how to set up the interface manually, but I had some trouble when pointing to my custom add-in code.

To get the buttons to work with your custom macros, setup the macro in your .xlam subs to be called as described in this SO answer - Calling an excel macro from the ribbon. Basically, you'll need to add that "control As IRibbonControl" paramter to any module pointed from your ribbon xml. Also, your ribbon xml should have the onAction="myaddin!mymodule.mysub" syntax to properly call any modules loaded by the add in.

Using those instructions I was able to create an excel add in (.xlam file) that has a custom tab loaded when my VBA gets loaded into Excel along with the add in. The buttons execute code from the add in and the custom tab uninstalls when I remove the add in.

Default keystore file does not exist?

In macOS, open the Terminal and type below command

~/.android

It will navigate to the folder that containing Keystore file (You can confirm it with 'ls' command)

In my case, there is a file named 'debug.keystore'. Then type below command in the terminal from the ~/.android directory.

keytool -list -v -keystore debug.keystore

You will get the expected output.

How to replace NaN value with zero in a huge data frame?

It would seem that is.nan doesn't actually have a method for data frames, unlike is.na. So, let's fix that!

is.nan.data.frame <- function(x)
do.call(cbind, lapply(x, is.nan))

data123[is.nan(data123)] <- 0

How to loop and render elements in React.js without an array of objects to map?

Here is more functional example with some ES6 features:

'use strict';

const React = require('react');

function renderArticles(articles) {
    if (articles.length > 0) {      
        return articles.map((article, index) => (
            <Article key={index} article={article} />
        ));
    }
    else return [];
}

const Article = ({article}) => {
    return ( 
        <article key={article.id}>
            <a href={article.link}>{article.title}</a>
            <p>{article.description}</p>
        </article>
    );
};

const Articles = React.createClass({
    render() {
        const articles = renderArticles(this.props.articles);

        return (
            <section>
                { articles }
            </section>
        );
    }
});

module.exports = Articles;

How do I store the select column in a variable?

This is how to assign a value to a variable:

SELECT @EmpID = Id
  FROM dbo.Employee

However, the above query is returning more than one value. You'll need to add a WHERE clause in order to return a single Id value.

Android: converting String to int

Use regular expression:

String s="your1string2contain3with4number";
int i=Integer.parseInt(s.replaceAll("[\\D]", ""))

output: i=1234;

If you need first number combination then you should try below code:

String s="abc123xyz456";
int i=((Number)NumberFormat.getInstance().parse(s)).intValue()

output: i=123;

Read the current full URL with React?

window.location.href is what you're looking for.

HTML5 iFrame Seamless Attribute

Updated: October 2016

The seamless attribute no longer exists. It was originally pitched to be included in the first HTML5 spec, but subsequently dropped. An unrelated attribute of the same name made a brief cameo in the HTML5.1 draft, but that too was ditched mid-2016:

So I think the gist of it all both from the implementor side and the web-dev side is that seamless as-specced doesn’t seem to be what anybody wanted to begin with. Or at least it’s more than anybody actually wanted. And anyway like @annevk says, it’s seems a lot of it’s since been “overcome by events” in light of Shadow DOM.

In other words: purge the seamless attribute from your memory, and pretend it never existed.

For posterity's sake, here's my original answer from five years ago:

Original answer: April 2011

The attribute is in draft mode at the moment. For that reason, none of the current browsers are supporting it yet (as the implementation is subject to change). In the meantime, it's best just to use CSS to strip the borders/scrollbars from the iframe:

iframe[seamless]{
    background-color: transparent;
    border: 0px none transparent;
    padding: 0px;
    overflow: hidden;
}

There's more to the seamless attribute than what can be added with CSS: part of the reasoning behind the attribute was to allow nested content to inherit the same styles applied to the iframe (acting as though the embedded document was one big nested inside the element, for example).

Lastly, versions of Internet Explorer (8 and earlier) require additional attributes in order to remove the borders, scrollbars and background colour:

<iframe frameborder="0" allowtransparency="true" scrolling="no" src="..."></iframe>

Naturally, this doesn't validate. So it's up to you how to handle it. My (picky) approach would be to sniff the agent string and add the attributes for IE versions earlier than 9.

Hope that helps. :)

Reverse colormap in matplotlib

There is no built-in way (yet) of reversing arbitrary colormaps, but one simple solution is to actually not modify the colorbar but to create an inverting Normalize object:

from matplotlib.colors import Normalize

class InvertedNormalize(Normalize):
    def __call__(self, *args, **kwargs):
        return 1 - super(InvertedNormalize, self).__call__(*args, **kwargs)

You can then use this with plot_surface and other Matplotlib plotting functions by doing e.g.

inverted_norm = InvertedNormalize(vmin=10, vmax=100)
ax.plot_surface(..., cmap=<your colormap>, norm=inverted_norm)

This will work with any Matplotlib colormap.

Turn on torch/flash on iPhone

Swift 2.0 version:

func setTorchLevel(torchLevel: Float)
{
    self.captureSession?.beginConfiguration()
    defer {
        self.captureSession?.commitConfiguration()
    }

    if let device = backCamera?.device where device.hasTorch && device.torchAvailable {
        do {
            try device.lockForConfiguration()
            defer {
                device.unlockForConfiguration()
            }

            if torchLevel <= 0.0 {
                device.torchMode = .Off
            }
            else if torchLevel >= 1.0 {
                try device.setTorchModeOnWithLevel(min(torchLevel, AVCaptureMaxAvailableTorchLevel))
            }
        }
        catch let error {
            print("Failed to set up torch level with error \(error)")
            return
        }
    }
}

finding multiples of a number in Python

If this is what you are looking for -

To find all the multiples between a given number and a limit

def find_multiples(integer, limit):
    return list(range(integer,limit+1, integer))

This should return -

Test.assert_equals(find_multiples(5, 25), [5, 10, 15, 20, 25])

How to change values in a tuple?

It is possible with a one liner:

values = ('275', '54000', '0.0', '5000.0', '0.0')
values = ('300', *values[1:])

Unable to execute dex: Multiple dex files define

I found below solution in eclipse...hope it works for you :)

Right click on the Project Name

Select Java Build Path, go to the tab Order and Export

Unchecked your .jar library's

How to determine the number of days in a month in SQL Server?

--Last Day of Previous Month
SELECT DATEPART(day, DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)))

--Last Day of Current Month
SELECT DATEPART(day, DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)))

--Last Day of Next Month
SELECT DATEPART(day, DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0)))

Personally though, I would make a UDF for it if there is not a built in function...

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

How do I move focus to next input with jQuery?

Here is what worked in my case. Might be less performance intensive.

$('#myelement').siblings('input').first().focus();

What's a decent SFTP command-line client for windows?

LFTP is great, however it is Linux only. You can find the Windows port here. Never tried though.

Achtunq, it uses Cygwin, but everything is included in the bundle.

How do you import a large MS SQL .sql file?

From the command prompt, start up sqlcmd:

sqlcmd -S <server> -i C:\<your file here>.sql 

Just replace <server> with the location of your SQL box and <your file here> with the name of your script. Don't forget, if you're using a SQL instance the syntax is:

sqlcmd -S <server>\instance.

Here is the list of all arguments you can pass sqlcmd:

Sqlcmd            [-U login id]          [-P password]
  [-S server]            [-H hostname]          [-E trusted connection]
  [-d use database name] [-l login timeout]     [-t query timeout] 
  [-h headers]           [-s colseparator]      [-w screen width]
  [-a packetsize]        [-e echo input]        [-I Enable Quoted Identifiers]
  [-c cmdend]            [-L[c] list servers[clean output]]
  [-q "cmdline query"]   [-Q "cmdline query" and exit] 
  [-m errorlevel]        [-V severitylevel]     [-W remove trailing spaces]
  [-u unicode output]    [-r[0|1] msgs to stderr]
  [-i inputfile]         [-o outputfile]        [-z new password]
  [-f  | i:[,o:]] [-Z new password and exit] 
  [-k[1|2] remove[replace] control characters]
  [-y variable length type display width]
  [-Y fixed length type display width]
  [-p[1] print statistics[colon format]]
  [-R use client regional setting]
  [-b On error batch abort]
  [-v var = "value"...]  [-A dedicated admin connection]
  [-X[1] disable commands, startup script, environment variables [and exit]]
  [-x disable variable substitution]
  [-? show syntax summary] 

Skipping error in for-loop

Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction() function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!

Get full URL and query string in Servlet for both HTTP and HTTPS requests

The fact that a HTTPS request becomes HTTP when you tried to construct the URL on server side indicates that you might have a proxy/load balancer (nginx, pound, etc.) offloading SSL encryption in front and forward to your back end service in plain HTTP.

If that's case, check,

  1. whether your proxy has been set up to forward headers correctly (Host, X-forwarded-proto, X-forwarded-for, etc).
  2. whether your service container (E.g. Tomcat) is set up to recognize the proxy in front. For example, Tomcat requires adding secure="true" scheme="https" proxyPort="443" attributes to its Connector
  3. whether your code, or service container is processing the headers correctly. For example, Tomcat automatically replaces scheme, remoteAddr, etc. values when you add RemoteIpValve to its Engine. (see Configuration guide, JavaDoc) so you don't have to process these headers in your code manually.

Incorrect proxy header values could result in incorrect output when request.getRequestURI() or request.getRequestURL() attempts to construct the originating URL.

Trigger an action after selection select2

//when a Department selecting
$('#department_id').on('select2-selecting', function (e) {
    console.log("Action Before Selected");
    var deptid=e.choice.id;
    var depttext=e.choice.text;
    console.log("Department ID "+deptid);
    console.log("Department Text "+depttext);
});

//when a Department removing
$('#department_id').on('select2-removing', function (e) {
    console.log("Action Before Deleted");
    var deptid=e.choice.id;
    var depttext=e.choice.text;
    console.log("Department ID "+deptid);
    console.log("Department Text "+depttext);
});

Installed Java 7 on Mac OS X but Terminal is still using version 6

http://www.java.com/en/download/faq/java_mac.xml is a nice place to understand, while Apple is stopping support to Java, why Java Preferences doesn't exist anymore and rely on System_Preferences => Java => Java if Java 7 from Oracle is installed.

Console output in a Qt GUI app?

One solution is to run powershell and redirect the output to whatever stream you want.

Below is an example of running powershell from cmd.exe and redirecting my_exec.exe output to both the console and an output.txt file:

powershell ".\my_exec.exe | tee output.txt"

How to use a class object in C++ as a function parameter

class is a keyword that is used only* to introduce class definitions. When you declare new class instances either as local objects or as function parameters you use only the name of the class (which must be in scope) and not the keyword class itself.

e.g.

class ANewType
{
    // ... details
};

This defines a new type called ANewType which is a class type.

You can then use this in function declarations:

void function(ANewType object);

You can then pass objects of type ANewType into the function. The object will be copied into the function parameter so, much like basic types, any attempt to modify the parameter will modify only the parameter in the function and won't affect the object that was originally passed in.

If you want to modify the object outside the function as indicated by the comments in your function body you would need to take the object by reference (or pointer). E.g.

void function(ANewType& object); // object passed by reference

This syntax means that any use of object in the function body refers to the actual object which was passed into the function and not a copy. All modifications will modify this object and be visible once the function has completed.

[* The class keyword is also used in template definitions, but that's a different subject.]

Convert a double to a QString

You can use arg(), as follow:

double dbl = 0.25874601;
QString str = QString("%1").arg(dbl);

This overcomes the problem of: "Fixed precision" at the other functions like: setNum() and number(), which will generate random numbers to complete the defined precision

selectOneMenu ajax events

I'd rather use more convenient itemSelect event. With this event you can use org.primefaces.event.SelectEvent objects in your listener.

<p:selectOneMenu ...>
    <p:ajax event="itemSelect" 
        update="messages"
        listener="#{beanMB.onItemSelectedListener}"/>
</p:selectOneMenu>

With such listener:

public void onItemSelectedListener(SelectEvent event){
    MyItem selectedItem = (MyItem) event.getObject();
    //do something with selected value
}

Eclipse Indigo - Cannot install Android ADT Plugin

I had the same problem. This helped for me:

  1. Go to Help->Install Software
  2. Click on "Available Software Sites"
  3. Click on Add: Name: "Helios" Location: "http://download.eclipse.org/releases/helios"
  4. Try to install Android Development Tools

How to remove the last character from a string?

if you have special character like ; in json just use String.replace(";", "") otherwise you must rewrite all character in string minus the last.

Is there a way to call a stored procedure with Dapper?

With multiple return and multi parameter

string ConnectionString = CommonFunctions.GetConnectionString();
using (IDbConnection conn = new SqlConnection(ConnectionString))
{
    IEnumerable<dynamic> results = conn.Query(sql: "ProductSearch", 
        param: new { CategoryID = 1, SubCategoryID="", PageNumber=1 }, 
        commandType: CommandType.StoredProcedure);.  // single result

    var reader = conn.QueryMultiple("ProductSearch", 
        param: new { CategoryID = 1, SubCategoryID = "", PageNumber = 1 }, 
        commandType: CommandType.StoredProcedure); // multiple result

    var userdetails = reader.Read<dynamic>().ToList(); // instead of dynamic, you can use your objects
    var salarydetails = reader.Read<dynamic>().ToList();
}

public static string GetConnectionString()
{
    // Put the name the Sqlconnection from WebConfig..
    return ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
}

Can enums be subclassed to add new elements?

Here is a way how I found how to extend a enum into other enum, is a very straighfoward approach:

Suposse you have a enum with common constants:

public interface ICommonInterface {

    String getName();

}


public enum CommonEnum implements ICommonInterface {
    P_EDITABLE("editable"),
    P_ACTIVE("active"),
    P_ID("id");

    private final String name;

    EnumCriteriaComun(String name) {
        name= name;
    }

    @Override
    public String getName() {
        return this.name;
    }
}

then you can try to do a manual extends in this way:

public enum SubEnum implements ICommonInterface {
    P_EDITABLE(CommonEnum.P_EDITABLE ),
    P_ACTIVE(CommonEnum.P_ACTIVE),
    P_ID(CommonEnum.P_ID),
    P_NEW_CONSTANT("new_constant");

    private final String name;

    EnumCriteriaComun(CommonEnum commonEnum) {
        name= commonEnum.name;
    }

    EnumCriteriaComun(String name) {
        name= name;
    }

    @Override
    public String getName() {
        return this.name;
    }
}

of course every time you need to extend a constant you have to modify your SubEnum files.

SSH Private Key Permissions using Git GUI or ssh-keygen are too open

Did you copy the key file from another machine?

I just created an id_rsa file on the client machine then pasted the key in I wanted. No permissions issues. Nothing to set. It just worked. It also works if you use PuTTYgen to create the private key.

Possibly some hidden group issue if you're copying it from another machine.

Tested on two Windows 8.1 machines. Using Sublime Text 3 to copy and paste the private key. Using Git Bash (Git-1.9.4-preview20140611).

How do I find the value of $CATALINA_HOME?

Just as a addition. You can find the Catalina Paths in

->RUN->RUN CONFIGURATIONS->APACHE TOMCAT->ARGUMENTS

In the VM Arguments the Paths are listed and changeable

How to initialize weights in PyTorch?

If you want some extra flexibility, you can also set the weights manually.

Say you have input of all ones:

import torch
import torch.nn as nn

input = torch.ones((8, 8))
print(input)
tensor([[1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1.]])

And you want to make a dense layer with no bias (so we can visualize):

d = nn.Linear(8, 8, bias=False)

Set all the weights to 0.5 (or anything else):

d.weight.data = torch.full((8, 8), 0.5)
print(d.weight.data)

The weights:

Out[14]: 
tensor([[0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
        [0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
        [0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
        [0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
        [0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
        [0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
        [0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
        [0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000]])

All your weights are now 0.5. Pass the data through:

d(input)
Out[13]: 
tensor([[4., 4., 4., 4., 4., 4., 4., 4.],
        [4., 4., 4., 4., 4., 4., 4., 4.],
        [4., 4., 4., 4., 4., 4., 4., 4.],
        [4., 4., 4., 4., 4., 4., 4., 4.],
        [4., 4., 4., 4., 4., 4., 4., 4.],
        [4., 4., 4., 4., 4., 4., 4., 4.],
        [4., 4., 4., 4., 4., 4., 4., 4.],
        [4., 4., 4., 4., 4., 4., 4., 4.]], grad_fn=<MmBackward>)

Remember that each neuron receives 8 inputs, all of which have weight 0.5 and value of 1 (and no bias), so it sums up to 4 for each.

How can I check the size of a collection within a Django template?

If you tried myList|length and myList|length_is and its not getting desired results, then you should use myList.count

How to remove a column from an existing table?

If you are using C# and the Identity column is int, create a new instance of int without providing any value to it.It worked for me.

[identity_column] = new int()

iOS change navigation bar title font and color

There is nothing wrong with the other answers. I'm just sharing the storyboard version for setting the font.

1. Select Your Navigation Bar within your Navigation Controller

navbar

2. Change the Title Font in the Attributes Inspector

title-font

(You will likely need to toggle the Bar Tint for the Navigation Bar before Xcode picks up the new font)

Notes (Caveats)

Verified that this does work on Xcode 7.1.1+. (See the Samples below)

  1. You do need to toggle the nav bar tint before the font takes effect (seems like a bug in Xcode; you can switch it back to default and font will stick)
  2. If you choose a system font ~ Be sure to make sure the size is not 0.0 (Otherwise the new font will be ignored)

size

  1. Seems like this works with no problem when only one NavBar is in the view hierarchy. It appears that secondary NavBars in the same stack are ignored. (Note that if you show the master navigation controller's navBar all the other custom navBar settings are ignored).

Gotchas (deux)

Some of these are repeated which means they are very likely worth noting.

  1. Sometimes the storyboard xml gets corrupt. This requires you to review the structure in Storyboard as Source Code mode (right click the storyboard file > Open As ...)
  2. In some cases the navigationItem tag associated with user defined runtime attribute was set as an xml child of the view tag instead of the view controller tag. If so remove it from between the tags for proper operation.
  3. Toggle the NavBar Tint to ensure the custom font is used.
  4. Verify the size parameter of the font unless using a dynamic font style
  5. View hierarchy will override the settings. It appears that one font per stack is possible.

Result

navbar-italic

Samples

Handling Custom Fonts

Note ~ A nice checklist can be found from the Code With Chris website and you can see the sample download project.

If you have your own font and want to use that in your storyboard, then there is a decent set of answers on the following SO Question. One answer identifies these steps.

  1. Get you custom font file(.ttf,.ttc)
  2. Import the font files to your Xcode project
  3. In the app-info.plist,add a key named Fonts provided by application.It's an array type , add all your font file names to the array,note:including the file extension.
  4. In the storyboard , on the NavigationBar go to the Attribute Inspector,click the right icon button of the Font select area.In the popup panel , choose Font to Custom, and choose the Family of you embeded font name.

Custom Font Workaround

So Xcode naturally looks like it can handle custom fonts on UINavigationItem but that feature is just not updating properly (The font selected is ignored).

UINavigationItem

To workaround this:

One way is to fix using the storyboard and adding a line of code: First add a UIView (UIButton, UILabel, or some other UIView subclass) to the View Controller (Not the Navigation Item...Xcode is not currently allowing one to do that). After you add the control you can modify the font in the storyboard and add a reference as an outlet to your View Controller. Just assign that view to the UINavigationItem.titleView. You could also set the text name in code if necessary. Reported Bug (23600285).

@IBOutlet var customFontTitleView: UIButton!

//Sometime later...    
self.navigationItem.titleView = customFontTitleView

Is there a difference between using a dict literal and a dict constructor?

There is no dict literal to create dict-inherited classes, custom dict classes with additional methods. In such case custom dict class constructor should be used, for example:

class NestedDict(dict):

    # ... skipped

state_type_map = NestedDict(**{
    'owns': 'Another',
    'uses': 'Another',
})

How can I stop a While loop?

def determine_period(universe_array):
    period=0
    tmp=universe_array
    while period<12:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        if numpy.array_equal(tmp,universe_array) is True:
            break 
        period+=1

    return period

Webdriver Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms

Just Restart the terminal. Terminal is hanged nothing else. Everything will work fine after that

How to compare two columns in Excel (from different sheets) and copy values from a corresponding column if the first two columns match?

Make a truth table and use SUMPRODUCT to get the values. Copy this into cell B1 on Sheet2 and copy down as far as you need:
=SUMPRODUCT(--($A1 = Sheet1!$A:$A), Sheet1!$B:$B)
the part that creates the truth table is:
--($A1 = Sheet1!$A:$A)
This returns an array of 0's and 1's. 1 when the values match and a 0 when they don't. Then the comma after that will basically do what I call "funny" matrix multiplication and will return the result. I may have misunderstood your question though, are there duplicate values in Column A of Sheet1?

How can I fix the Microsoft Visual Studio error: "package did not load correctly"?

I had a similar issue (Tizen Project type package did not load correctly) with Visual Studio 2017.

After trying all the answers above, and spending a few hours searching for a solution for the errors inside ActivityLog.XML, nothing worked for me.

Eventually, the solution was a Visual Studio Repair.

I assume that the repair process overrides some configurations that caused the problem.

Repair Visual Studio 2017
Repair Visual Studio 2019

When using a Settings.settings file in .NET, where is the config actually stored?

All your settings are stored in the respective .config file.

The .settings file simply provides a strongly typed class for a set of settings that belong together, but the actual settings are stored in app.config or a .config file in your application.

If you add a .settings file, an app.config will be automatically added to house the settings if you don't already have one.

Difference between CR LF, LF and CR line break types?

NL derived from EBCDIC NL = x'15' which would logically compare to CRLF x'odoa ascii... this becomes evident when physcally moving data from mainframes to midrange. Coloquially (as only arcane folks use ebcdic) NL has been equated with either CR or LF or CRLF

How to iterate through SparseArray?

For removing all the elements from SparseArray using the above looping leads to Exception.

To avoid this Follow the below code to remove all the elements from SparseArray using normal loops

private void getValues(){      
    for(int i=0; i<sparseArray.size(); i++){
          int key = sparseArray.keyAt(i);
          Log.d("Element at "+key, " is "+sparseArray.get(key));
          sparseArray.remove(key);
          i=-1;
    }
}

Scanner is skipping nextLine() after using next() or nextFoo()?

TL;DR Use scanner.skip("\\R") (since skip uses regex where \R represents line separators) before each scanner.newLine() call, which is executed after:

  • scanner.next()
  • scanner.next*TYPE*() method, like scanner.nextInt().

Things you need to know:

  • text which represents few lines also contains non-printable characters between lines (we call them line separators) like

  • carriage return (CR - in String literals represented as "\r")

  • line feed (LF - in String literals represented as "\n")

  • when you are reading data from the console, it allows the user to type his response and when he is done he needs to somehow confirm that fact. To do so, the user is required to press "enter"/"return" key on the keyboard.

What is important is that this key beside ensuring placing user data to standard input (represented by System.in which is read by Scanner) also sends OS dependant line separators (like for Windows \r\n) after it.

So when you are asking the user for value like age, and user types 42 and presses enter, standard input will contain "42\r\n".

Problem

Scanner#nextInt (and other Scanner#nextType methods) doesn't allow Scanner to consume these line separators. It will read them from System.in (how else Scanner would know that there are no more digits from the user which represent age value than facing whitespace?) which will remove them from standard input, but it will also cache those line separators internally. What we need to remember, is that all of the Scanner methods are always scanning starting from the cached text.

Now Scanner#nextLine() simply collects and returns all characters until it finds line separators (or end of stream). But since line separators after reading the number from the console are found immediately in Scanner's cache, it returns empty String, meaning that Scanner was not able to find any character before those line separators (or end of stream).
BTW nextLine also consumes those line separators.

Solution

So when you want to ask for number and then for entire line while avoiding that empty string as result of nextLine, either

  • consume line separator left by nextInt from Scanners cache by
  • calling nextLine,
  • or IMO more readable way would be by calling skip("\\R") or skip("\r\n|\r|\n") to let Scanner skip part matched by line separator (more info about \R: https://stackoverflow.com/a/31060125)
  • don't use nextInt (nor next, or any nextTYPE methods) at all. Instead read entire data line-by-line using nextLine and parse numbers from each line (assuming one line contains only one number) to proper type like int via Integer.parseInt.

BTW: Scanner#nextType methods can skip delimiters (by default all whitespaces like tabs, line separators) including those cached by scanner, until they will find next non-delimiter value (token). Thanks to that for input like "42\r\n\r\n321\r\n\r\n\r\nfoobar" code

int num1 = sc.nextInt();
int num2 = sc.nextInt();
String name = sc.next();

will be able to properly assign num1=42 num2=321 name=foobar.

How to link to part of the same document in Markdown?

yes, markdown does do this but you need to specify the name anchor <a name='xyx'>.

a full example,

this creates the link
[tasks](#tasks)

later in the document, you create the named anchor (whatever it is called).

<a name="tasks">
   my tasks
</a>

note that you could also wrap it around the header too.

<a name="tasks">
### Agile tasks (created by developer)
</a>

Serializing an object to JSON

Download https://github.com/douglascrockford/JSON-js/blob/master/json2.js, include it and do

var json_data = JSON.stringify(obj);

Iterate through string array in Java

As long as this question remains unsanswered the OP's problem and Java has evolved over the years, I have decided to put my own one.

Let's change for sake of clarity the input String array to have 5 unique items.

String[] elements = {"a", "b", "c", "d", "e"};

You want to access two siblings in the list with each iteration incremented by one index.

for (int i=0; i<elements.length-1; i++) {        // note the condition
    String left = elements[i];
    String right = elements[i+1];

    System.out.println(left + " " + right);      // prints 4 lines
}

Printing the pairs of left and right in four iterations result in the lines a b, b c, c d, d e in your console.

What can happen if the input string array has less than 2 elements? Nothing prints our as long as this for-loop extracts always two sibling nodes. With less than 2 elements the program doesn't enter to the loop itself.

As far as your snippet says you want to not discard the extracted values but add them an another variable, assuming outside the scope of the for-loop, you want to store them in either a list or an array. Let's say you want to concatenate the siblings with the + character.

List<String> list = new ArrayList<>();
String[] array = new String[elements.length-1];  // note the defined size

for (int i=0; i<elements.length-1; i++) {
    String left = elements[i];
    String right = elements[i+1];

    list.add(left + "+" + right);            // adds to the list
    array[i] = left + "+" + right;           // adds to the array
}

Printing the contents both of the list and the array (Arrays.toString(array)) results in:

[a+b, b+c, c+d, d+e]

Java 8

As of Java 8, you might be tempted to use the advantage of Stream API, however, it was made for procesing the individual elements from a source collection. There is no such method for processing 2 or more sibling nodes at once.

The only way is to use Stream API to process the indices instead and map them to the real value. As long as you start with a primitive Stream called IntStream you need to use IntStream::mapToObj method to get boxed Stream<T>:

String[] array = IntStream.range(0, elements.length-1)
    .mapToObj(i -> elements[i] + "+" + elements[i + 1])
    .toArray(String[]::new);                              // [a+b, b+c, c+d, d+e]

List<String> list = IntStream.range(0, elements.length-1)
    .mapToObj(i -> elements[i] + "+" + elements[i + 1])
    .collect(Collectors.toList());                        // [a+b, b+c, c+d, d+e]

Replacing &nbsp; from javascript dom text node

That first line is pretty messed up. It only needs to be:

var cleanText = text.replace(/\xA0/g,' ');

That should be all you need.

Using logging in multiple modules

Several of these answers suggest that at the top of a module you you do

import logging
logger = logging.getLogger(__name__)

It is my understanding that this is considered very bad practice. The reason is that the file config will disable all existing loggers by default. E.g.

#my_module
import logging

logger = logging.getLogger(__name__)

def foo():
    logger.info('Hi, foo')

class Bar(object):
    def bar(self):
        logger.info('Hi, bar')

And in your main module :

#main
import logging

# load my module - this now configures the logger
import my_module

# This will now disable the logger in my module by default, [see the docs][1] 
logging.config.fileConfig('logging.ini')

my_module.foo()
bar = my_module.Bar()
bar.bar()

Now the log specified in logging.ini will be empty, as the existing logger was disabled by fileconfig call.

While is is certainly possible to get around this (disable_existing_Loggers=False), realistically many clients of your library will not know about this behavior, and will not receive your logs. Make it easy for your clients by always calling logging.getLogger locally. Hat Tip : I learned about this behavior from Victor Lin's Website.

So good practice is instead to always call logging.getLogger locally. E.g.

#my_module
import logging

logger = logging.getLogger(__name__)

def foo():
    logging.getLogger(__name__).info('Hi, foo')

class Bar(object):
    def bar(self):
        logging.getLogger(__name__).info('Hi, bar')    

Also, if you use fileconfig in your main, set disable_existing_loggers=False, just in case your library designers use module level logger instances.

How do I query between two dates using MySQL?

You can do it manually, by comparing with greater than or equal and less than or equal.

 select * from table_name where created_at_column  >=   lower_date  and  created_at_column <= upper_date;

In our example, we need to retrieve data from a particular day to day. We will compare from the beginning of the day to the latest second in another day.

  select * from table_name where created_at_column  >=   '2018-09-01 00:00:00'  and  created_at_column <= '2018-09-05 23:59:59';

How do you decrease navbar height in Bootstrap 3?

bootstrap had 15px top padding and 15px bottom padding on .navbar-nav > li > a so you need to decrease it by overriding it in your css file and .navbar has min-height:50px; decrease it as much you want.

for example

.navbar-nav > li > a {padding-top:5px !important; padding-bottom:5px !important;}
.navbar {min-height:32px !important}

add these classes to your css and then check.

Batch file to split .csv file

Use the cgwin command SPLIT. Samples

To split a file every 500 lines counts:

split -l 500 [filename.ext]

by default, it adds xa,xb,xc... to filename after extension

To generate files with numbers and ending in correct extension, use following

split -l 1000 sourcefilename.ext destinationfilename -d --additional-suffix=.ext

the position of -d or -l does not matter,

  • "-d" is same as --numeric-suffixes
  • "-l" is same as --lines

For more: split --help

Sort Pandas Dataframe by Date

@JAB's answer is fast and concise. But it changes the DataFrame you are trying to sort, which you may or may not want.

(Note: You almost certainly will want it, because your date columns should be dates, not strings!)

In the unlikely event that you don't want to change the dates into dates, you can also do it a different way.

First, get the index from your sorted Date column:

In [25]: pd.to_datetime(df.Date).order().index
Out[25]: Int64Index([0, 2, 1], dtype='int64')

Then use it to index your original DataFrame, leaving it untouched:

In [26]: df.ix[pd.to_datetime(df.Date).order().index]
Out[26]: 
        Date Symbol
0 2015-02-20      A
2 2015-08-21      A
1 2016-01-15      A

Magic!

Note: for Pandas versions 0.20.0 and later, use loc instead of ix, which is now deprecated.

scrollTop jquery, scrolling to div with id?

if you want to scroll just only some div, can use the div id instead of 'html, body'

$('html, body').animate(...

use

$('#mydivid').animate(...

Bad Request - Invalid Hostname IIS7

Make sure IIS is listening to your port.

In my case this was the issue. So I had to change my port to something else like 8083 and it solved this issue.

How to add custom method to Spring Data JPA

Considering your code snippet, please note that you can only pass Native objects to the findBy### method, lets say you want to load a list of accounts that belongs certain costumers, one solution is to do this,

@Query("Select a from Account a where a."#nameoffield"=?1")
List<Account> findByCustomer(String "#nameoffield");

Make sue the name of the table to be queried is thesame as the Entity class. For further implementations please take a look at this

Why does CSS not support negative padding?

Padding by definition is a positive integer (including 0).

Negative padding would cause the border to collapse into the content (see the box-model page on w3) - this would make the content area smaller than the content, which doesn't make sense.

Best Way to do Columns in HTML/CSS

You should probably consider using css3 for this though it does include the use of vendor prefixes.

I've knocked up a quick fiddle to demo but the crux is this.

<style>
.3col
{
    -webkit-column-count: 3;
    -webkit-column-gap: 10px;
    -moz-column-count: 3;
    -moz-column-gap: 10px;
    column-count:3;
    column-gap:10px;
}
</style>
<div class="3col">
<p>col1</p>
<p>col2</p>
<p>col3</p>
</div>

Aligning a float:left div to center?

Perhaps this what you're looking for - https://www.w3schools.com/css/css3_flexbox.asp

CSS:

#container {
  display:                 flex;
  flex-wrap:               wrap;
  justify-content:         center;
}

.block {
  width:              150px;
  height:             150px;
  margin:             10px;        
}

HTML:

<div id="container">
  <div class="block">1</div>    
  <div class="block">2</div>    
  <div class="block">3</div>          
</div>

Restoring Nuget References?

You need to Enable NuGet package restore at the VS solution level for the restore missing package to work.

enter image description here

Python: Get the first character of the first string in a list?

Try mylist[0][0]. This should return the first character.

Save modifications in place with awk

In case you want an awk-only solution without creating a temporary file and usable with version!=(gawk 4.1.0):

awk '{a[b++]=$0} END {for(c=0;c<=b;c++)print a[c]>ARGV[1]}' file

CSS text-overflow in a table cell?

Specifying a max-width or fixed width doesn't work for all situations, and the table should be fluid and auto-space its cells. That's what tables are for. Works on IE9 and other browsers.

Use this: http://jsfiddle.net/maruxa1j/

_x000D_
_x000D_
table {
    width: 100%;
}
.first {
    width: 50%;
}
.ellipsis {
    position: relative;
}
.ellipsis:before {
    content: '&nbsp;';
    visibility: hidden;
}
.ellipsis span {
    position: absolute;
    left: 0;
    right: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
_x000D_
<table border="1">
    <thead>
        <tr>
            <th>Header 1</th>
            <th>Header 2</th>
            <th>Header 3</th>
            <th>Header 4</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class="ellipsis first"><span>This Text Overflows and is too large for its cell.</span></td>
            <td class="ellipsis"><span>This Text Overflows and is too large for its cell.</span></td>
            <td class="ellipsis"><span>This Text Overflows and is too large for its cell.</span></td>
            <td class="ellipsis"><span>This Text Overflows and is too large for its cell.</span></td>
        </tr>
    </tbody>
</table>
_x000D_
_x000D_
_x000D_

Perl read line by line

#!/usr/bin/perl
use utf8                       ;
use 5.10.1                     ;
use strict                     ;
use autodie                    ;
use warnings FATAL => q  ?all?;
binmode STDOUT     => q ?:utf8?;                  END {
close   STDOUT                 ;                     }
our    $FOLIO      =  q + SnPmaster.txt +            ;
open    FOLIO                  ;                 END {
close   FOLIO                  ;                     }
binmode FOLIO      => q{       :crlf
                               :encoding(CP-1252)    };
while (<FOLIO>)  { print       ;                     }
       continue  { ${.} ^015^  __LINE__  ||   exit   }
                                                                                                                                                                                                                                              __END__
unlink  $FOLIO                 ;
unlink ~$HOME ||
  clri ~$HOME                  ;
reboot                         ;

Convert ascii char[] to hexadecimal char[] in C

#include <stdio.h>
#include <string.h>

int main(void){
    char word[17], outword[33];//17:16+1, 33:16*2+1
    int i, len;

    printf("Intro word:");
    fgets(word, sizeof(word), stdin);
    len = strlen(word);
    if(word[len-1]=='\n')
        word[--len] = '\0';

    for(i = 0; i<len; i++){
        sprintf(outword+i*2, "%02X", word[i]);
    }
    printf("%s\n", outword);
    return 0;
}

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

In my case I'm using an external maven installation with m2e. I've added my proxy settings to the external maven installation's settings.xml file. These settings haven't been used by m2e even after I've set the external maven installation as default maven installation.

To solve the problem I've configured the global maven settings file within eclipse to be the settings.xml file from my external maven installation.

Now eclipse can download the required artifacts.

How to call a method daily, at specific time, in C#?

I created a simple scheduler that is easy to use and you do not need to use external library. TaskScheduler is a singleton that keeps references on the timers so timers will not be garbage collected, it can schedule multiple tasks. You can set the first run (hour and minute), if at the time of scheduling this time is over scheduling start on the next day this at that time. But it is easy to customize the code.

Scheduling a new task is so simple. Example: At 11:52 the first task is for every 15 secunds, the second example is for every 5 secunds. For daily execution set 24 to the 3 parameter.

TaskScheduler.Instance.ScheduleTask(11, 52, 0.00417, 
    () => 
    {
        Debug.WriteLine("task1: " + DateTime.Now);
        //here write the code that you want to schedule
    });

TaskScheduler.Instance.ScheduleTask(11, 52, 0.00139,
    () =>
    {
        Debug.WriteLine("task2: " + DateTime.Now);
        //here write the code that you want to schedule
    });

My debug window:

task2: 07.06.2017 11:52:00
task1: 07.06.2017 11:52:00
task2: 07.06.2017 11:52:05
task2: 07.06.2017 11:52:10
task1: 07.06.2017 11:52:15
task2: 07.06.2017 11:52:15
task2: 07.06.2017 11:52:20
task2: 07.06.2017 11:52:25
...

Just add this class to your project:

public class TaskScheduler
{
    private static TaskScheduler _instance;
    private List<Timer> timers = new List<Timer>();

    private TaskScheduler() { }

    public static TaskScheduler Instance => _instance ?? (_instance = new TaskScheduler());

    public void ScheduleTask(int hour, int min, double intervalInHour, Action task)
    {
        DateTime now = DateTime.Now;
        DateTime firstRun = new DateTime(now.Year, now.Month, now.Day, hour, min, 0, 0);
        if (now > firstRun)
        {
            firstRun = firstRun.AddDays(1);
        }

        TimeSpan timeToGo = firstRun - now;
        if (timeToGo <= TimeSpan.Zero)
        {
            timeToGo = TimeSpan.Zero;
        }

        var timer = new Timer(x =>
        {
            task.Invoke();
        }, null, timeToGo, TimeSpan.FromHours(intervalInHour));

        timers.Add(timer);
    }
}

How do I set up curl to permanently use a proxy?

Curl will look for a .curlrc file in your home folder when it starts. You can create (or edit) this file and add this line:

proxy = yourproxy.com:8080

Which is the default location for keystore/truststore of Java applications?

In Java, according to the JSSE Reference Guide, there is no default for the keystore, the default for the truststore is "jssecacerts, if it exists. Otherwise, cacerts".

A few applications use ~/.keystore as a default keystore, but this is not without problems (mainly because you might not want all the application run by the user to use that trust store).

I'd suggest using application-specific values that you bundle with your application instead, it would tend to be more applicable in general.

java SSL and cert keystore

you can also mention the path at runtime using -D properties as below

-Djavax.net.ssl.trustStore=/home/user/SSL/my-cacerts 
-Djavax.net.ssl.keyStore=/home/user/SSL/server_keystore.jks

In my apache spark application, I used to provide the path of certs and keystore using --conf option and extraJavaoptions in spark-submit as below

--conf 'spark.driver.extraJavaOptions= 
-Djavax.net.ssl.trustStore=/home/user/SSL/my-cacerts 
-Djavax.net.ssl.keyStore=/home/user/SSL/server_keystore.jks' 

Vue 'export default' vs 'new Vue'

Whenever you use

export someobject

and someobject is

{
 "prop1":"Property1",
 "prop2":"Property2",
}

the above you can import anywhere using import or module.js and there you can use someobject. This is not a restriction that someobject will be an object only it can be a function too, a class or an object.

When you say

new Object()

like you said

new Vue({
  el: '#app',
  data: []
)}

Here you are initiating an object of class Vue.

I hope my answer explains your query in general and more explicitly.

How to split a python string on new line characters

? Splitting line in Python:

Have you tried using str.splitlines() method?:

From the docs:

str.splitlines([keepends])

Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

For example:

>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()
['Line 1', '', 'Line 3', 'Line 4']

>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines(True)
['Line 1\n', '\n', 'Line 3\r', 'Line 4\r\n']

Which delimiters are considered?

This method uses the universal newlines approach to splitting lines.

The main difference between Python 2.X and Python 3.X is that the former uses the universal newlines approach to splitting lines, so "\r", "\n", and "\r\n" are considered line boundaries for 8-bit strings, while the latter uses a superset of it that also includes:

  • \v or \x0b: Line Tabulation (added in Python 3.2).
  • \f or \x0c: Form Feed (added in Python 3.2).
  • \x1c: File Separator.
  • \x1d: Group Separator.
  • \x1e: Record Separator.
  • \x85: Next Line (C1 Control Code).
  • \u2028: Line Separator.
  • \u2029: Paragraph Separator.

splitlines VS split:

Unlike str.split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:

>>> ''.splitlines()
[]

>>> 'Line 1\n'.splitlines()
['Line 1']

While str.split('\n') returns:

>>> ''.split('\n')
['']

>>> 'Line 1\n'.split('\n')
['Line 1', '']

?? Removing additional whitespace:

If you also need to remove additional leading or trailing whitespace, like spaces, that are ignored by str.splitlines(), you could use str.splitlines() together with str.strip():

>>> [str.strip() for str in 'Line 1  \n  \nLine 3 \rLine 4 \r\n'.splitlines()]
['Line 1', '', 'Line 3', 'Line 4']

? Removing empty strings (''):

Lastly, if you want to filter out the empty strings from the resulting list, you could use filter():

>>> # Python 2.X:
>>> filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines())
['Line 1', 'Line 3', 'Line 4']

>>> # Python 3.X:
>>> list(filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()))
['Line 1', 'Line 3', 'Line 4']

Additional comment regarding the original question:

As the error you posted indicates and Burhan suggested, the problem is from the print. There's a related question about that could be useful to you: UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

Force overwrite of local file with what's in origin repo?

Full sync has few tasks:

  • reverting changes
  • removing new files
  • get latest from remote repository

git reset HEAD --hard

git clean -f

git pull origin master

Or else, what I prefer is that, I may create a new branch with the latest from the remote using:

git checkout origin/master -b <new branch name>

origin is my remote repository reference, and master is my considered branch name. These may different from yours.

Google Drive as FTP Server

What about running the google-drive-ftp-adapter application in your local pc and then connect your filezilla client to that application? The google-drive-ftp-adapter application is not an online service, but its an alternative solution to connect to google drive through ftp.

The google-drive-ftp-adapter is an open source application hosted in github and it is a kind of standalone ftp-server java application that connects to your google drive in behalf of you, acting as a bridge (or adapter) between your ftp client and the google drive service. Once you have running the google-drive-ftp adapter, you can connect your preferred FTP client to the google-drive-ftp-adapter ftp server in your localhost (or wherever the app is running, like in a remote machine) to manage your files.

I use it in conjunction with beyond compare to synchronize my local files against the ones I have in the google drive and it serves well for the purpose.

This is the current github link hosting the google-drive-ftp-adapter repository: https://github.com/andresoviedo/google-drive-ftp-adapter

How to run crontab job every week on Sunday

When specifying your cron values you'll need to make sure that your values fall within the ranges. For instance, some cron's use a 0-7 range for the day of week where both 0 and 7 represent Sunday. We do not(check below).

Seconds: 0-59
Minutes: 0-59
Hours: 0-23
Day of Month: 1-31
Months: 0-11
Day of Week: 0-6

reference: https://github.com/ncb000gt/node-cron

C# how to use enum with switch

No need to convert. You can apply conditions on Enums inside a switch. Like so,

public enum Operator
{ 
    PLUS,
    MINUS,
    MULTIPLY,
    DIVIDE
}

public double Calculate(int left, int right, Operator op)
{
    switch (op)
    {
        case Operator.PLUS: return left + right; 
        case Operator.MINUS: return left - right; 
        case Operator.MULTIPLY: return left * right;
        case Operator.DIVIDE: return left / right;
        default: return 0.0; 
    }
}

Then, call it like this:

Console.WriteLine("The sum of 5 and 5 is " + Calculate(5, 5, Operator.PLUS));

Extract / Identify Tables from PDF python

After many fruitful hours of exploring OCR libraries, bounding boxes and clustering algorithms - I found a solution so simple it makes you want to cry!

I hope you are using Linux;

pdftotext -layout NAME_OF_PDF.pdf

AMAZING!!

Now you have a nice text file with all the information lined up in nice columns, now it is trivial to format into a csv etc..

It is for times like this that I love Linux, these guys came up with AMAZING solutions to everything, and put it there for FREE!

How to copy a file from remote server to local machine?

For example, your remote host is example.com and remote login name is user1:

scp [email protected]:/path/to/file /path/to/store/file

Add Whatsapp function to website, like sms, tel

I just posted an answer on a thread similiar to this here https://stackoverflow.com/a/43357241/3958617

The approach with:

<a href="whatsapp://send?abid=username&text=Hello%2C%20World!">whatsapp</a>

and with

<a href="intent://send/0123456789#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end">whatsapp</a>

Only works if the person who clicked on your link have your number on their contact list.

Since not everybody will have it, the other solution is to use Whatsapp API like this:

<a href="https://api.whatsapp.com/send?phone=15551234567">Send Message</a>

Apache won't follow symlinks (403 Forbidden)

First disable selinux (vim /etc/selinux/config)

vim /etc/httpd/conf/httpd.conf edit following lines for symlinks and directory indexing:

documentroot /var/www/html
<directory /var/www/html>
    Options Indexes FollowSymLinks
    AllowOverride None
</directory>

If .htaccess file then AllowOverride all

Declaring and initializing arrays in C

In C99 you can do it using a compound literal in combination with memcpy

memcpy(myarray, (int[]) { 1, 2, 3, 4 }, sizeof myarray);

(assuming that the size of the source and the size of the target is the same).

In C89/90 you can emulate that by declaring an additional "source" array

const int SOURCE[SIZE] = { 1, 2, 3, 4 }; /* maybe `static`? */
int myArray[SIZE];
...
memcpy(myarray, SOURCE, sizeof myarray);

Write output to a text file in PowerShell

Use the Out-File cmdlet

 Compare-Object ... | Out-File C:\filename.txt

Optionally, add -Encoding utf8 to Out-File as the default encoding is not really ideal for many uses.

Can Mysql Split a column?

Here is another variant I posted on related question. The REGEX check to see if you are out of bounds is useful, so for a table column you would put it in the where clause.

SET @Array = 'one,two,three,four';
SET @ArrayIndex = 2;
SELECT CASE 
    WHEN @Array REGEXP CONCAT('((,).*){',@ArrayIndex,'}') 
    THEN SUBSTRING_INDEX(SUBSTRING_INDEX(@Array,',',@ArrayIndex+1),',',-1) 
    ELSE NULL
END AS Result;
  • SUBSTRING_INDEX(string, delim, n) returns the first n
  • SUBSTRING_INDEX(string, delim, -1) returns the last only
  • REGEXP '((delim).*){n}' checks if there are n delimiters (i.e. you are in bounds)

-didSelectRowAtIndexPath: not being called

In my case, I dynamically calculate the height of the TableView's SuperView at load time. Due to a miscalculation, the TableView was positioned outside of the SuperView. The TableView was drawn fine, however all interaction was disabled (and didSelectRowAtIndexPath was never called). Very hard to detect, since there is no visual indication that the TableView is not "accessible".

MySQL joins and COUNT(*) from another table

MySQL use HAVING statement for this tasks.

Your query would look like this:

SELECT g.group_id, COUNT(m.member_id) AS members
FROM groups AS g
LEFT JOIN group_members AS m USING(group_id)
GROUP BY g.group_id
HAVING members > 4

example when references have different names

SELECT g.id, COUNT(m.member_id) AS members
FROM groups AS g
LEFT JOIN group_members AS m ON g.id = m.group_id
GROUP BY g.id
HAVING members > 4

Also, make sure that you set indexes inside your database schema for keys you are using in JOINS as it can affect your site performance.

Display HTML snippets in HTML

function escapeHTML(string)
    { 
        var pre = document.createElement('pre');
        var text = document.createTextNode(string);
        pre.appendChild(text);
        return pre.innerHTML;
}//end escapeHTML

it will return the escaped Html

Testing two JSON objects for equality ignoring child order in Java

You can use zjsonpatch library, which presents the diff information in accordance with RFC 6902 (JSON Patch). Its very easy to use. Please visit its description page for its usage

How does autowiring work in Spring?

@Autowired is an annotation introduced in Spring 2.5, and it's used only for injection.

For example:

class A {

    private int id;

    // With setter and getter method
}

class B {

    private String name;

    @Autowired // Here we are injecting instance of Class A into class B so that you can use 'a' for accessing A's instance variables and methods.
    A a;

    // With setter and getter method

    public void showDetail() {
        System.out.println("Value of id form A class" + a.getId(););
    }
}

SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known

First line of the error message describes the error type: "PDOException". The next line displays PDO::errorInfo, i.e:

  1. SQLSTATE error code (a five characters alphanumeric identifier defined in the ANSI SQL standard).
  2. Driver-specific error code.
  3. Driver-specific error message.
  • "HY000" is a general server error (see Server Error Codes and Messages in MySQL docs).
  • "2002" is MySQL Client Error Code meaning "Can't connect to local MySQL server through socket" (see (Client Error Codes and Messages in MySQL docs).
  • The driver specific error code and message ("php_network_getaddresses: getaddrinfo failed: Name or service not known") tell you that PDO is not able to resolve the host name.

The stack trace you attached, line 3, reveals that you did not specify the database connection parameters in the configuration file. The error show up when you test on local, right? You need to update /.env with the actual database connection parameters.

How do Python's any and all functions work?

The concept is simple:

M =[(1, 1), (5, 6), (0, 0)]

1) print([any(x) for x in M])
[True, True, False] #only the last tuple does not have any true element

2) print([all(x) for x in M])
[True, True, False] #all elements of the last tuple are not true

3) print([not all(x) for x in M])
[False, False, True] #NOT operator applied to 2)

4) print([any(x)  and not all(x) for x in M])
[False, False, False] #AND operator applied to 1) and 3)
# if we had M =[(1, 1), (5, 6), (1, 0)], we could get [False, False, True]  in 4)
# because the last tuple satisfies both conditions: any of its elements is TRUE 
#and not all elements are TRUE 

How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

I used the following on Mac OSX.

currDate=`date +%Y%m%d`
epochDate=$(date -j -f "%Y%m%d" "${currDate}" "+%s")

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

Here's an example of a reverse proxy (as a load balancer).

A client surfs to website.com and the server it hits has a reverse proxy running on it. The reverse proxy happens to be Pound. Pound takes the request and sends it to one of the three application servers sitting behind it. In this example, Pound is a load balancer. That is, it is balancing the load between three application servers.

The application servers serve up the website content back to the client.

Is it possible in Java to catch two exceptions in the same catch block?

Before the launch of Java SE 7 we were habitual of writing code with multiple catch statements associated with a try block. A very basic Example:

 try {
  // some instructions
} catch(ATypeException e) {
} catch(BTypeException e) {
} catch(CTypeException e) {
}

But now with the latest update on Java, instead of writing multiple catch statements we can handle multiple exceptions within a single catch clause. Here is an example showing how this feature can be achieved.

try {
// some instructions
} catch(ATypeException|BTypeException|CTypeException ex) {
   throw e;
}

So multiple Exceptions in a single catch clause not only simplifies the code but also reduce the redundancy of code. I found this article which explains this feature very well along with its implementation. Improved and Better Exception Handling from Java 7 This may help you too.

PHP Accessing Parent Class Variable

$bb has now become the private member of class B after extending class A where it was protected.

So you access $bb like it's an attribute of class B.

class A {
    private $aa;
    protected $bb = 'parent bb';

    function __construct($arg) {
       //do something..
    }

    private function parentmethod($arg2) {
       //do something..
    }
}

class B extends A {
    function __construct($arg) {
        parent::__construct($arg);
    }
    function childfunction() {
        echo $this->bb; 
    }
}

$test = new B($some);
$test->childfunction();

How to initialize java.util.date to empty

Instance of java.util.Date stores a date. So how can you store nothing in it or have it empty? It can only store references to instances of java.util.Date. If you make it null means that it is not referring any instance of java.util.Date.

You have tried date2=""; what you mean to do by this statement you want to reference the instance of String to a variable that is suppose to store java.util.Date. This is not possible as Java is Strongly Typed Language.

Edit

After seeing the comment posted to the answer of LastFreeNickname

I am having a form that the date textbox should be by default blank in the textbox, however while submitting the data if the user didn't enter anything, it should accept it

I would suggest you could check if the textbox is empty. And if it is empty, then you could store default date in your variable or current date or may be assign it null as shown below:

if(textBox.getText() == null || textBox.getText().equals(""){
    date2 = null; // For Null;
    // date2 = new Date(); For Current Date
    // date2 = new Date(0); For Default Date
}

Also I can assume since you are asking user to enter a date in a TextBox, you are using a DateFormat to parse the text that is entered in the TextBox. If this is the case you could simply call the dateFormat.parse() which throws a ParseException if the format in which the date was written is incorrect or is empty string. Here in the catch block you could put the above statements as show below:

try{
    date2 = dateFormat.parse(textBox.getText());
}catch(ParseException e){
    date2 = null; // For Null;
    // date2 = new Date(); For Current Date
    // date2 = new Date(0); For Default Date
}

How can I deploy an iPhone application from Xcode to a real iPhone device?

You can't, not if you are talking about applications built with the official SDK and deploying straight from xcode.

How to print out all the elements of a List in Java?

For loop to print the content of a list :

List<String> myList = new ArrayList<String>();
myList.add("AA");
myList.add("BB");

for ( String elem : myList ) {
  System.out.println("Element : "+elem);
}

Result :

Element : AA
Element : BB

If you want to print in a single line (just for information) :

String strList = String.join(", ", myList);
System.out.println("Elements : "+strList);

Result :

Elements : AA, BB

Sorting JSON by values

If you don't mind using an external library, Lodash has lots of wonderful utilities

var people = [
  {
     "f_name":"john",
     "l_name":"doe",
     "sequence":"0",
     "title":"president",
     "url":"google.com",
     "color":"333333"
  },
  {
     "f_name":"michael",
     "l_name":"goodyear",
     "sequence":"0",
     "title":"general manager",
     "url":"google.com",
     "color":"333333"
  }
];


var sorted = _.sortBy(people, "l_name")

You can also sort by multiple properties. Here's a plunk showing it in action

Prevent WebView from displaying "web page not available"

I would just change the webpage to whatever you are using for error handling:

getWindow().requestFeature(Window.FEATURE_PROGRESS);  
webview.getSettings().setJavaScriptEnabled(true);  
final Activity activity = this;  
webview.setWebChromeClient(new WebChromeClient() {  
public void onProgressChanged(WebView view, int progress) {  
 // Activities and WebViews measure progress with different scales.  
 // The progress meter will automatically disappear when we reach 100%  
 activity.setProgress(progress * 1000);  
 }  
});  
webview.setWebViewClient(new WebViewClient() {  
public void onReceivedError(WebView view, int errorCode, String description, String 
failingUrl) {  
 Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();  
}  
});  
webview.loadUrl("http://slashdot.org/");

this can all be found on http://developer.android.com/reference/android/webkit/WebView.html

Where will log4net create this log file?

I think your sample is saving to your project folders and unless the default iis, or .NET , user has create permission then it won't be able to create the logs folder.

I'd create the logs folder first and allow the iis user full permission and see if the log file is being created.

Whitespaces in java

boolean whitespaceSearchRegExp(String input) {

    return java.util.regex.Pattern.compile("\\s").matcher(input).find();

} 

Execute function after Ajax call is complete

You should set async = false in head. Use post/get instead of ajax.

jQuery.ajaxSetup({ async: false });

    $.post({
        url: 'api.php',
        data: 'id1=' + q + '',
        dataType: 'json',
        success: function (data) {

            id = data[0];
            vname = data[1];

        }
    });

Disabling vertical scrolling in UIScrollView

I updated the content size to disable vertical scrolling, and the ability to scroll still remained. Then I figured out that I needed to disable vertical bounce too, to disable completly the scroll.

Maybe there are people with this problem too.

Python: Assign Value if None Exists

This is a very different style of programming, but I always try to rewrite things that looked like

bar = None
if foo():
    bar = "Baz"

if bar is None:
    bar = "Quux"

into just:

if foo():
    bar = "Baz"
else:
    bar = "Quux"

That is to say, I try hard to avoid a situation where some code paths define variables but others don't. In my code, there is never a path which causes an ambiguity of the set of defined variables (In fact, I usually take it a step further and make sure that the types are the same regardless of code path). It may just be a matter of personal taste, but I find this pattern, though a little less obvious when I'm writing it, much easier to understand when I'm later reading it.

Convert String with Dot or Comma as decimal separator to number in JavaScript

You could replace all spaces by an empty string, all comas by dots and then parse it.

var str = "110 000,23";
var num = parseFloat(str.replace(/\s/g, "").replace(",", "."));
console.log(num);

I used a regex in the first one to be able to match all spaces, not just the first one.

How to make a flat list out of list of lists?

Simple code for underscore.py package fan

from underscore import _
_.flatten([[1, 2, 3], [4, 5, 6], [7], [8, 9]])
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

It solves all flatten problems (none list item or complex nesting)

from underscore import _
# 1 is none list item
# [2, [3]] is complex nesting
_.flatten([1, [2, [3]], [4, 5, 6], [7], [8, 9]])
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

You can install underscore.py with pip

pip install underscore.py

How do you check what version of SQL Server for a database using TSQL?

SELECT 
@@SERVERNAME AS ServerName,
CASE WHEN LEFT(CAST(serverproperty('productversion') as char), 1) = 9 THEN '2005'
 WHEN LEFT(CAST(serverproperty('productversion') as char), 2) = 10 THEN '2008'
 WHEN LEFT(CAST(serverproperty('productversion') as char), 2) = 11 THEN '2012'
END AS MajorVersion,
SERVERPROPERTY ('productlevel') AS MinorVersion, 
SERVERPROPERTY('productversion') AS FullVersion, 
SERVERPROPERTY ('edition') AS Edition

Common HTTPclient and proxy

For httpclient 4.1.x you can set the proxy like this (taken from this example):

    HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        HttpHost target = new HttpHost("issues.apache.org", 443, "https");
        HttpGet req = new HttpGet("/");

        System.out.println("executing request to " + target + " via " + proxy);
        HttpResponse rsp = httpclient.execute(target, req);
        ...
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

How do I clone into a non-empty directory?

In the following shell commands existing-dir is a directory whose contents match the tracked files in the repo-to-clone git repository.

# Clone just the repository's .git folder (excluding files as they are already in
# `existing-dir`) into an empty temporary directory
git clone --no-checkout repo-to-clone existing-dir/existing-dir.tmp # might want --no-hardlinks for cloning local repo

# Move the .git folder to the directory with the files.
# This makes `existing-dir` a git repo.
mv existing-dir/existing-dir.tmp/.git existing-dir/

# Delete the temporary directory
rmdir existing-dir/existing-dir.tmp
cd existing-dir

# git thinks all files are deleted, this reverts the state of the repo to HEAD.
# WARNING: any local changes to the files will be lost.
git reset --hard HEAD

'ng' is not recognized as an internal or external command, operable program or batch file

I was with the same problem and now discovered a working solution. After successful installation of node and angular CLI do the following steps.

Open C:\usr\local and copy the path or the path where angular CLI located on your machine.

enter image description here

Now open environment variable in your Windows, and add copied path in the following location:

Advanced > Environment Variable > User Variables and System Variables as below image:

enter image description here

That's all, now open cmd and try with any 'ng' command:

enter image description here

The data-toggle attributes in Twitter Bootstrap

It is a Bootstrap data attribute that automatically hooks up the element to the type of widget it is. Data-* is part of the html5 spec, and data-toggle is specific to Bootstrap.

Some Examples:

data-toggle="modal"
data-toggle="collapse"
data-toggle="dropdown"
data-toggle="tab"

Go through the Bootstrap JavaScript docs and search for data-toggle and you will see it used in the code examples.

One working example:

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="dropdown">_x000D_
  <a class="dropdown-toggle" data-toggle="dropdown" href="#">Dropdown trigger</a>_x000D_
  <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">_x000D_
    <li><a href="#">Item</a></li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to copy a directory structure but only include certain files (using windows batch files)

Similar to Paulius' solution, but the files you don't care about are not copied then deleted:

@echo OFF

:: Replace c:\temp with the directory where folder1 resides.
cd c:\temp

:: You can make this more generic by passing in args for the source and destination folders.
for /f "usebackq" %%I in (`dir /b /s /a:-d folder1`) do @echo %%~nxI | find /V "data.zip" | find /v "info.txt" >> exclude_list.txt
xcopy folder1 copy_of_folder1 /EXCLUDE:exclude_list.txt /E /I

How to add extension methods to Enums

All answers are great, but they are talking about adding extension method to a specific type of enum.

What if you want to add a method to all enums like returning an int of current value instead of explicit casting?

public static class EnumExtensions
{
    public static int ToInt<T>(this T soure) where T : IConvertible//enum
    {
        if (!typeof(T).IsEnum)
            throw new ArgumentException("T must be an enumerated type");

        return (int) (IConvertible) soure;
    }

    //ShawnFeatherly funtion (above answer) but as extention method
    public static int Count<T>(this T soure) where T : IConvertible//enum
    {
        if (!typeof(T).IsEnum)
            throw new ArgumentException("T must be an enumerated type");

        return Enum.GetNames(typeof(T)).Length;
    }
}

The trick behind IConvertible is its Inheritance Hierarchy see MDSN

Thanks to ShawnFeatherly for his answer

Does Android keep the .apk files? if so where?

In /data/app but for copy protection I don't think you can access it.

How to make unicode string with python3

In a Python 2 program that I used for many years there was this line:

ocd[i].namn=unicode(a[:b], 'utf-8')

This did not work in Python 3.

However, the program turned out to work with:

ocd[i].namn=a[:b]

I don't remember why I put unicode there in the first place, but I think it was because the name can contains Swedish letters åäöÅÄÖ. But even they work without "unicode".

How can I format my grep output to show line numbers at the end of the line, and also the hit count?

Just thought I'd something that might help you in the future. To search multiple string and output line numbers and browse thru the output, type:

egrep -ne 'null|three'

will show:

2:example two null,  
3:example three,  
4:example four null,   

egrep -ne 'null|three' | less

will display output in a less session

HTH Jun

Javascript: How to remove the last character from a div or a string?

var string = "Hello";
var str = string.substring(0, string.length-1);
alert(str);

http://jsfiddle.net/d72ML/

Set position / size of UI element as percentage of screen size

Use the PercentRelativeLayout or PercentFrameLayout from the Percent Supoort Library

<android.support.percent.PercentFrameLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
     <TextView
          android:layout_width="match_parent"
          app:layout_heightPercent="68%"/>
     <Gallery 
          android:id="@+id/gallery"
          android:layout_width="match_parent"
          app:layout_heightPercent="16%"/>
     <TextView
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:layout_width="match_parent"/>
</android.support.percent.PercentFrameLayout>

Onclick javascript to make browser go back to previous page?

For Going to previous page

First Method

<a href="javascript: history.go(-1)">Go Back</a>

Second Method

<a href="##" onClick="history.go(-1); return false;">Go back</a> 

if we want to more than one step back then increase

For going 2 steps back history.go(-2)
For going 3 steps back history.go(-3)
For going 4 steps back history.go(-4)
and so on.......

Switch statement with returns -- code correctness

I'd normally write the code without them. IMO, dead code tends to indicate sloppiness and/or lack of understanding.

Of course, I'd also consider something like:

char const *rets[] = {"blah", "foo", "bar"};

return rets[something];

Edit: even with the edited post, this general idea can work fine:

char const *rets[] = { "blah", "foo", "bar", "bar", "foo"};

if ((unsigned)something < 5)
    return rets[something]
return "foobar";

At some point, especially if the input values are sparse (e.g., 1, 100, 1000 and 10000), you want a sparse array instead. You can implement that as either a tree or a map reasonably well (though, of course, a switch still works in this case as well).

laravel 5 : Class 'input' not found

For laravel < 5.2:

Open config/app.php and add the Input class to aliases:

'aliases' => [
// ...
  'Input' => Illuminate\Support\Facades\Input::class,
// ...
],

For laravel >= 5.2

Change Input:: to Request::

Check if a radio button is checked jquery

Something like this:

 $("input[name=test]").is(":checked");

Using the jQuery is() function should work.

How to set image width to be 100% and height to be auto in react native?

You always have to set the width and height of an Image. It is not going to automatically size things for you. The React Native docs says so.

You should measure the total height of the ScrollView using onLayout and set the height of the Images based on it. If you use resizeMode of cover it will keep the aspect ratio of your Images but it will obviously crop them if it's bigger than the container.

Search for a string in Enum and return the Enum

check out System.Enum.Parse:


enum Colors {Red, Green, Blue}

// your code:
Colors color = (Colors)System.Enum.Parse(typeof(Colors), "Green");

How to get method parameter names?

In Python 3.+ with the Signature object at hand, an easy way to get a mapping between argument names to values, is using the Signature's bind() method!

For example, here is a decorator for printing a map like that:

import inspect

def decorator(f):
    def wrapper(*args, **kwargs):
        bound_args = inspect.signature(f).bind(*args, **kwargs)
        bound_args.apply_defaults()
        print(dict(bound_args.arguments))

        return f(*args, **kwargs)

    return wrapper

@decorator
def foo(x, y, param_with_default="bars", **kwargs):
    pass

foo(1, 2, extra="baz")
# This will print: {'kwargs': {'extra': 'baz'}, 'param_with_default': 'bars', 'y': 2, 'x': 1}

Serializing a list to JSON

building on an answer from another posting.. I've come up with a more generic way to build out a list, utilizing dynamic retrieval with Json.NET version 12.x

using Newtonsoft.Json;

static class JsonObj
{
    /// <summary>
    /// Deserializes a json file into an object list
    /// Author: Joseph Poirier 2/26/2019
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public static List<T> DeSerializeObject<T>(string fileName)
    {
        List<T> objectOut = new List<T>();

        if (string.IsNullOrEmpty(fileName)) { return objectOut; }

        try
        {
            // reading in full file as text
            string ss = File.ReadAllText(fileName);

            // went with <dynamic> over <T> or <List<T>> to avoid error..
            //  unexpected character at line 1 column 2
            var output = JsonConvert.DeserializeObject<dynamic>(ss);

            foreach (var Record in output)
            {
                foreach (T data in Record)
                {
                    objectOut.Add(data);
                }
            }
        }
        catch (Exception ex)
        {
            //Log exception here
            Console.Write(ex.Message);
        }

        return objectOut;
    }
}

call to process

{
        string fname = "../../Names.json"; // <- your json file path

        // for alternate types replace string with custom class below
        List<string> jsonFile = JsonObj.DeSerializeObject<string>(fname);
}

or this call to process

{
        string fname = "../../Names.json"; // <- your json file path

        // for alternate types replace string with custom class below
        List<string> jsonFile = new List<string>();
        jsonFile.AddRange(JsonObj.DeSerializeObject<string>(fname));
}

Is it possible to Turn page programmatically in UIPageViewController?

Here's another code example for a single paged view. Implementation for viewControllerAtIndex is omitted here, it should return the correct view controller for the given index.

- (void)changePage:(UIPageViewControllerNavigationDirection)direction {
    NSUInteger pageIndex = ((FooViewController *) [_pageViewController.viewControllers objectAtIndex:0]).pageIndex;

    if (direction == UIPageViewControllerNavigationDirectionForward) {
        pageIndex++;
    }
    else {
        pageIndex--;
    }

    FooViewController *viewController = [self viewControllerAtIndex:pageIndex];

    if (viewController == nil) {
        return;
    }

    [_pageViewController setViewControllers:@[viewController]
                                  direction:direction
                                   animated:YES
                                 completion:nil];
}

Pages can be changed by calling

[self changePage:UIPageViewControllerNavigationDirectionReverse];
[self changePage:UIPageViewControllerNavigationDirectionForward];

Clear and refresh jQuery Chosen dropdown list

Using .trigger("chosen:updated"); you can update the options list after appending.

Updating Chosen Dynamically: If you need to update the options in your select field and want Chosen to pick up the changes, you'll need to trigger the "chosen:updated" event on the field. Chosen will re-build itself based on the updated content.

Your code:

$("#refreshgallery").click(function(){
        $('#picturegallery').empty(); //remove all child nodes
        var newOption = $('<option value="1">test</option>');
        $('#picturegallery').append(newOption);
        $('#picturegallery').trigger("chosen:updated");
    });

CMake link to external library

One more alternative, in the case you are working with the Appstore, need "Entitlements" and as such need to link with an Apple-Framework.

For Entitlements to work (e.g. GameCenter) you need to have a "Link Binary with Libraries"-buildstep and then link with "GameKit.framework". CMake "injects" the libraries on a "low level" into the commandline, hence Xcode doesn't really know about it, and as such you will not get GameKit enabled in the Capabilities screen.

One way to use CMake and have a "Link with Binaries"-buildstep is to generate the xcodeproj with CMake, and then use 'sed' to 'search & replace' and add the GameKit in the way XCode likes it...

The script looks like this (for Xcode 6.3.1).

s#\/\* Begin PBXBuildFile section \*\/#\/\* Begin PBXBuildFile section \*\/\
    26B12AA11C10544700A9A2BA \/\* GameKit.framework in Frameworks \*\/ = {isa = PBXBuildFile; fileRef = 26B12AA01C10544700A9A2BA \/\* GameKit.framework xxx\*\/; };#g

s#\/\* Begin PBXFileReference section \*\/#\/\* Begin PBXFileReference section \*\/\
    26B12AA01C10544700A9A2BA \/\* GameKit.framework xxx\*\/ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = GameKit.framework; path = System\/Library\/Frameworks\/GameKit.framework; sourceTree = SDKROOT; };#g

s#\/\* End PBXFileReference section \*\/#\/\* End PBXFileReference section \*\/\
\
\/\* Begin PBXFrameworksBuildPhase section \*\/\
    26B12A9F1C10543B00A9A2BA \/\* Frameworks \*\/ = {\
        isa = PBXFrameworksBuildPhase;\
        buildActionMask = 2147483647;\
        files = (\
            26B12AA11C10544700A9A2BA \/\* GameKit.framework in Frameworks xxx\*\/,\
        );\
        runOnlyForDeploymentPostprocessing = 0;\
    };\
\/\* End PBXFrameworksBuildPhase section \*\/\
#g

s#\/\* CMake PostBuild Rules \*\/,#\/\* CMake PostBuild Rules \*\/,\
            26B12A9F1C10543B00A9A2BA \/\* Frameworks xxx\*\/,#g
s#\/\* Products \*\/,#\/\* Products \*\/,\
            26B12AA01C10544700A9A2BA \/\* GameKit.framework xxx\*\/,#g

save this to "gamecenter.sed" and then "apply" it like this ( it changes your xcodeproj! )

sed -i.pbxprojbak -f gamecenter.sed myproject.xcodeproj/project.pbxproj

You might have to change the script-commands to fit your need.

Warning: it's likely to break with different Xcode-version as the project-format could change, the (hardcoded) unique number might not really by unique - and generally the solutions by other people are better - so unless you need to Support the Appstore + Entitlements (and automated builds), don't do this.

This is a CMake bug, see http://cmake.org/Bug/view.php?id=14185 and http://gitlab.kitware.com/cmake/cmake/issues/14185

How to initialize a variable of date type in java?

Here's the Javadoc in Oracle's website for the Date class: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html
If you scroll down to "Constructor Summary," you'll see the different options for how a Date object can be instantiated. Like all objects in Java, you create a new one with the following:

Date firstDate = new Date(ConstructorArgsHere);

Now you have a bit of a choice. If you don't pass in any arguments, and just do this,

Date firstDate = new Date();

it will represent the exact date and time at which you called it. Here are some other constructors you may want to make use of:

Date firstDate1 = new Date(int year, int month, int date);
Date firstDate2 = new Date(int year, int month, int date, int hrs, int min);
Date firstDate3 = new Date(int year, int month, int date, int hrs, int min, int sec);

How can I count the number of children?

You can use .length, like this:

var count = $("ul li").length;

.length tells how many matches the selector found, so this counts how many <li> under <ul> elements you have...if there are sub-children, use "ul > li" instead to get only direct children. If you have other <ul> elements in your page, just change the selector to match only his one, for example if it has an ID you'd use "#myListID > li".

In other situations where you don't know the child type, you can use the * (wildcard) selector, or .children(), like this:

var count = $(".parentSelector > *").length;

or:

var count = $(".parentSelector").children().length;

Combating AngularJS executing controller twice

I tore my app and all its dependencies to bits over this issue (details here: AngularJS app initiating twice (tried the usual solutions..))

And in the end, it was all Batarang Chrome plugin's fault.

Resolution in this answer:

I'd strongly recommend the first thing on anyone's list is to disable it per the post before altering code.

How to symbolicate crash log Xcode?

From Apple's docs:

Symbolicating Crash Reports With Xcode Xcode will automatically attempt to symbolicate all crash reports that it encounters. All you need to do for symbolication is to add the crash report to the Xcode Organizer.

  • Connect an iOS device to your Mac
  • Choose "Devices" from the "Window" menu
  • Under the "DEVICES" section in the left column, choose a device
  • Click the "View Device Logs" button under the "Device Information" section on the right hand panel
  • Drag your crash report onto the left column of the presented panel
  • Xcode will automatically symbolicate the crash report and display the results To symbolicate a crash report, Xcode needs to be able to locate the following:

    1. The crashing application's binary and dSYM file.

    2. The binaries and dSYM files for all custom frameworks that the application links against. For frameworks that were built from source with the application, their dSYM files are copied into the archive alongside the application's dSYM file. For frameworks that were built by a third-party, you will need to ask the author for the dSYM file.

    3. Symbols for the OS that the that application was running on when it crashed. These symbols contain debug information for the frameworks included in a specific OS release (e.g, iOS 9.3.3). OS symbols are architecture specific - a release of iOS for 64-bit devices won't include armv7 symbols. Xcode will automatically copy OS symbols from each device that you connect to your Mac.

If any of these are missing Xcode may not be able to symbolicate the crash report, or may only partially symbolicate the crash report.

Days between two dates?

Do you mean full calendar days, or groups of 24 hours?

For simply 24 hours, assuming you're using Python's datetime, then the timedelta object already has a days property:

days = (a - b).days

For calendar days, you'll need to round a down to the nearest day, and b up to the nearest day, getting rid of the partial day on either side:

roundedA = a.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
roundedB = b.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
days = (roundedA - roundedB).days

500.21 Bad module "ManagedPipelineHandler" in its module list

I had this problem every time I deployed a new website or updated an existing one using MSDeploy.

I was able to fix this by unloading the app domain using MSDeploy with the following syntax:

msdeploy.exe -verb:sync -source:recycleApp -dest:recycleApp="Default Web Site/myAppName",recycleMode=UnloadAppDomain

You can also stop, start, or recycle the application pool - more details here: http://technet.microsoft.com/en-us/library/ee522997%28v=ws.10%29.aspx

While Armaan's solution helped get me unstuck, it did not make the problem go away permanently.

Slick.js: Get current and total slides (ie. 3/5)

This might help:

  • You don't need to enable dots or customPaging.
  • Position .slick-counter with CSS.

CSS

.slick-counter{
  position:absolute;
  top:5px;
  left:5px;
  background:yellow;
  padding:5px;
  opacity:0.8;
  border-radius:5px;
}

JavaScript

var $el = $('.slideshow');

$el.slick({
  slide: 'img',
  autoplay: true,
  onInit: function(e){
    $el.append('<div class="slick-counter">'+ parseInt(e.currentSlide + 1, 10) +' / '+ e.slideCount +'</div>');
  },
  onAfterChange: function(e){
    $el.find('.slick-counter').html(e.currentSlide + 1 +' / '+e.slideCount);
  }
});

http://jsfiddle.net/cpdqhdwy/6/

When to use If-else if-else over switch statements and vice versa

The tendency to avoid stuff because it takes longer to type is a bad thing, try to root it out. That said, overly verbose things are also difficult to read, so small and simple is important, but it's readability not writability that's important. Concise one-liners can often be more difficult to read than a simple well laid out 3 or 4 lines.

Use whichever construct best descibes the logic of the operation.

How to construct a set out of list items in python?

Simply put the line:

new_list = set(your_list)

How do I compare strings in GoLang?

For the Platform Independent Users or Windows users, what you can do is:

import runtime:

import (
    "runtime"
    "strings"
)

and then trim the string like this:

if runtime.GOOS == "windows" {
  input = strings.TrimRight(input, "\r\n")
} else {
  input = strings.TrimRight(input, "\n")
}

now you can compare it like that:

if strings.Compare(input, "a") == 0 {
  //....yourCode
}

This is a better approach when you're making use of STDIN on multiple platforms.

Explanation

This happens because on windows lines end with "\r\n" which is known as CRLF, but on UNIX lines end with "\n" which is known as LF and that's why we trim "\n" on unix based operating systems while we trim "\r\n" on windows.

Node JS Promise.all and forEach

I had through the same situation. I solved using two Promise.All().

I think was really good solution, so I published it on npm: https://www.npmjs.com/package/promise-foreach

I think your code will be something like this

var promiseForeach = require('promise-foreach')
var jsonItems = [];
promiseForeach.each(jsonItems,
    [function (jsonItems){
        return new Promise(function(resolve, reject){
            if(jsonItems.type === 'file'){
                jsonItems.getFile().then(function(file){ //or promise.all?
                    resolve(file.getSize())
                })
            }
        })
    }],
    function (result, current) {
        return {
            type: current.type,
            size: jsonItems.result[0]
        }
    },
    function (err, newList) {
        if (err) {
            console.error(err)
            return;
        }
        console.log('new jsonItems : ', newList)
    })

Angular2 get clicked element id

do like this simply: (as said in comment here is with example with two methods)

import {Component} from 'angular2/core';

@Component({
    selector: 'my-app', 
    template: `
      <button (click)="checkEvent($event,'a')" id="abc" class="def">Display Toastr</button>
      <button (click)="checkEvent($event,'b')" id="abc1" class="def1">Display Toastr1</button>
    `
})
export class AppComponent {
  checkEvent(event, id){
    console.log(event, id, event.srcElement.attributes.id);
  }
}

demo: http://plnkr.co/edit/5kJaj9D13srJxmod213r?p=preview

Tomcat is web server or application server?

Tomcat is a web server and a Servlet/JavaServer Pages container. It is often used as an application server for strictly web-based applications but does not include the entire suite of capabilities that a Java EE application server would supply.

Links:

Histogram with Logarithmic Scale and custom breaks

Dirk's answer is a great one. If you want an appearance like what hist produces, you can also try this:

buckets <- c(0,1,2,3,4,5,25)
mydata_hist <- hist(mydata$V3, breaks=buckets, plot=FALSE)
bp <- barplot(mydata_hist$count, log="y", col="white", names.arg=buckets)
text(bp, mydata_hist$counts, labels=mydata_hist$counts, pos=1)

The last line is optional, it adds value labels just under the top of each bar. This can be useful for log scale graphs, but can also be omitted.

I also pass main, xlab, and ylab parameters to provide a plot title, x-axis label, and y-axis label.

Soft Edges using CSS?

It depends on what type of fading you are looking for.

But with shadow and rounded corners you can get a nice result. Rounded corners because the bigger the shadow, the weirder it will look in the edges unless you balance it out with rounded corners.

http://jsfiddle.net/tLu7u/

also.. http://css3pie.com/

Set database from SINGLE USER mode to MULTI USER

You can add the option to rollback your change immediately.

ALTER DATABASE BARDABARD
SET MULTI_USER
WITH ROLLBACK IMMEDIATE
GO

Replacement for deprecated sizeWithFont: in iOS 7?

boundingRectWithSize:options:attributes:context:

Javascript: Setting location.href versus location

One difference to keep in mind, though.

Let's say you want to build some URL using the current URL. The following code will in fact redirect you, because it's not calling String.replace but Location.replace:

nextUrl = window.location.replace('/step1', '/step2');

The following codes work:

// cast to string
nextUrl = (window.location+'').replace('/step1', '/step2');

// href property
nextUrl = window.location.href.replace('/step1', '/step2');

Scala how can I count the number of occurrences in a list

If you want to use it like list.count(2) you have to implement it using an Implicit Class.

implicit class Count[T](list: List[T]) {
  def count(n: T): Int = list.count(_ == n)
}

List(1,2,4,2,4,7,3,2,4).count(2)  // returns 3
List(1,2,4,2,4,7,3,2,4).count(5)  // returns 0

Difference between int32, int, int32_t, int8 and int8_t

Between int32 and int32_t, (and likewise between int8 and int8_t) the difference is pretty simple: the C standard defines int8_t and int32_t, but does not define anything named int8 or int32 -- the latter (if they exist at all) is probably from some other header or library (most likely predates the addition of int8_t and int32_t in C99).

Plain int is quite a bit different from the others. Where int8_t and int32_t each have a specified size, int can be any size >= 16 bits. At different times, both 16 bits and 32 bits have been reasonably common (and for a 64-bit implementation, it should probably be 64 bits).

On the other hand, int is guaranteed to be present in every implementation of C, where int8_t and int32_t are not. It's probably open to question whether this matters to you though. If you use C on small embedded systems and/or older compilers, it may be a problem. If you use it primarily with a modern compiler on desktop/server machines, it probably won't be.

Oops -- missed the part about char. You'd use int8_t instead of char if (and only if) you want an integer type guaranteed to be exactly 8 bits in size. If you want to store characters, you probably want to use char instead. Its size can vary (in terms of number of bits) but it's guaranteed to be exactly one byte. One slight oddity though: there's no guarantee about whether a plain char is signed or unsigned (and many compilers can make it either one, depending on a compile-time flag). If you need to ensure its being either signed or unsigned, you need to specify that explicitly.

HTML: how to make 2 tables with different CSS

In your html

<table class="table1">
<tr>
<td>
...
</table>

<table class="table2">

<tr>
<td>
...
</table>

In your css:

table.table1 {...}
table.table1 tr {...}
table.table1 td {...}

table.table2 {...}
table.table2 tr {...}
table.table2 td {...}

How to print environment variables to the console in PowerShell?

In addition to Mathias answer.

Although not mentioned in OP, if you also need to see the Powershell specific/related internal variables, you need to use Get-Variable:

$ Get-Variable

Name                           Value
----                           -----
$                              name
?                              True
^                              gci
args                           {}
ChocolateyTabSettings          @{AllCommands=False}
ConfirmPreference              High
DebugPreference                SilentlyContinue
EnabledExperimentalFeatures    {}
Error                          {System.Management.Automation.ParseException: At line:1 char:1...
ErrorActionPreference          Continue
ErrorView                      NormalView
ExecutionContext               System.Management.Automation.EngineIntrinsics
false                          False
FormatEnumerationLimit         4
...

These also include stuff you may have set in your profile startup script.

How to extract text from the PDF document?

Download the class.pdf2text.php @ https://pastebin.com/dvwySU1a or http://www.phpclasses.org/browse/file/31030.html (Registration required)

Code:

include('class.pdf2text.php');
$a = new PDF2Text();
$a->setFilename('filename.pdf'); 
$a->decodePDF();
echo $a->output(); 

  • class.pdf2text.php Project Home

  • pdf2textclass doesn't work with all the PDF's I've tested, If it doesn't work for you, try PDF Parser


How to set the "Content-Type ... charset" in the request header using a HTML link

This is not possible from HTML on. The closest what you can get is the accept-charset attribute of the <form>. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.

To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).


Update: Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.

alt text

Getting the computer name in Java

I'm not so thrilled about the InetAddress.getLocalHost().getHostName() solution that you can find so many places on the Internet and indeed also here. That method will get you the hostname as seen from a network perspective. I can see two problems with this:

  1. What if the host has multiple network interfaces ? The host may be known on the network by multiple names. The one returned by said method is indeterminate afaik.

  2. What if the host is not connected to any network and has no network interfaces ?

All OS'es that I know of have the concept of naming a node/host irrespective of network. Sad that Java cannot return this in an easy way. This would be the environment variable COMPUTERNAME on all versions of Windows and the environment variable HOSTNAME on Unix/Linux/MacOS (or alternatively the output from host command hostname if the HOSTNAME environment variable is not available as is the case in old shells like Bourne and Korn).

I would write a method that would retrieve (depending on OS) those OS vars and only as a last resort use the InetAddress.getLocalHost().getHostName() method. But that's just me.

UPDATE (Unices)

As others have pointed out the HOSTNAME environment variable is typically not available to a Java application on Unix/Linux as it is not exported by default. Hence not a reliable method unless you are in control of the clients. This really sucks. Why isn't there a standard property with this information?

Alas, as far as I can see the only reliable way on Unix/Linux would be to make a JNI call to gethostname() or to use Runtime.exec() to capture the output from the hostname command. I don't particularly like any of these ideas but if anyone has a better idea I'm all ears. (update: I recently came across gethostname4j which seems to be the answer to my prayers).

Long read

I've created a long explanation in another answer on another post. In particular you may want to read it because it attempts to establish some terminology, gives concrete examples of when the InetAddress.getLocalHost().getHostName() solution will fail, and points to the only safe solution that I know of currently, namely gethostname4j.

It's sad that Java doesn't provide a method for obtaining the computername. Vote for JDK-8169296 if you are able to.

what do these symbolic strings mean: %02d %01d?

The answer from Alexander refers to complete docs...

Your simple example from the question simply prints out these values with 2 digits - appending leading 0 if necessary.

Multiple aggregate functions in HAVING clause

There is no need to do two checks, why not just check for count = 3:

GROUP BY meetingID
HAVING COUNT(caseID) = 3

If you want to use the multiple checks, then you can use:

GROUP BY meetingID
HAVING COUNT(caseID) > 2
 AND COUNT(caseID) < 4

How do I set the selected item in a drop down box

You mark the selected item on the <option> tag, not the <select> tag.

So your code should read something like this:

<select>
    <option value="January"<?php if ($row[month] == 'January') echo ' selected="selected"'; ?>>January</option>
    <option value="February"<?php if ($row[month] == 'February') echo ' selected="selected"'; ?>>February</option>
    ...
    ...
    <option value="December"<?php if ($row[month] == 'December') echo ' selected="selected"'; ?>>December</option>
</select>

You can make this less repetitive by putting all the month names in an array and using a basic foreach over them.

How to fix 'Notice: Undefined index:' in PHP form action

if(!empty($_POST['filename'])){
$filename = $_POST['filename'];

echo $filename;
}

Python string.join(list) on object array rather than string array

You could use a list comprehension or a generator expression instead:

', '.join([str(x) for x in list])  # list comprehension
', '.join(str(x) for x in list)    # generator expression

How do I change the default index page in Apache?

I recommend using .htaccess. You only need to add:

DirectoryIndex home.php

or whatever page name you want to have for it.

EDIT: basic htaccess tutorial.

1) Create .htaccess file in the directory where you want to change the index file.

  • no extension
  • . in front, to ensure it is a "hidden" file

Enter the line above in there. There will likely be many, many other things you will add to this (AddTypes for webfonts / media files, caching for headers, gzip declaration for compression, etc.), but that one line declares your new "home" page.

2) Set server to allow reading of .htaccess files (may only be needed on your localhost, if your hosting servce defaults to allow it as most do)

Assuming you have access, go to your server's enabled site location. I run a Debian server for development, and the default site setup is at /etc/apache2/sites-available/default for Debian / Ubuntu. Not sure what server you run, but just search for "sites-available" and go into the "default" document. In there you will see an entry for Directory. Modify it to look like this:

<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

Then restart your apache server. Again, not sure about your server, but the command on Debian / Ubuntu is:

sudo service apache2 restart

Technically you only need to reload, but I restart just because I feel safer with a full refresh like that.

Once that is done, your site should be reading from your .htaccess file, and you should have a new default home page! A side note, if you have a sub-directory that runs a site (like an admin section or something) and you want to have a different "home page" for that directory, you can just plop another .htaccess file in that sub-site's root and it will overwrite the declaration in the parent.

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

Try this:

sudo xcode-select --reset 
sudo xcodebuild -license

or this:

xcode-select --install

Align inline-block DIVs to top of container element

<style type="text/css">
        div {
  text-align: center;
         }

         .img1{
            width: 150px;
            height: 150px;
            border-radius: 50%;
         }

         span{
            display: block;
         }
    </style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type='password' class='secondInput mt-4 mr-1' placeholder="Password">
  <span class='dif'></span>
  <br>
  <button>ADD</button>
</div>

<script type="text/javascript">

$('button').click(function() {
  $('.dif').html("<img/>");

})

How do I print part of a rendered HTML page in JavaScript?

Try this JavaScript code:

function printout() {

    var newWindow = window.open();
    newWindow.document.write(document.getElementById("output").innerHTML);
    newWindow.print();
}

Make elasticsearch only return certain fields?

A REST API GET request could be made with '_source' parameter.

Example Request

http://localhost:9200/opt_pr/_search?q=SYMBOL:ITC AND OPTION_TYPE=CE AND TRADE_DATE=2017-02-10 AND EXPIRY_DATE=2017-02-23&_source=STRIKE_PRICE

Response

{
"took": 59,
"timed_out": false,
"_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
},
"hits": {
    "total": 104,
    "max_score": 7.3908954,
    "hits": [
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLc",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 160
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLh",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 185
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLi",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 190
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLm",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 210
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLp",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 225
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLr",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 235
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLw",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 260
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uL5",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 305
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLd",
            "_score": 7.381078,
            "_source": {
                "STRIKE_PRICE": 165
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLy",
            "_score": 7.381078,
            "_source": {
                "STRIKE_PRICE": 270
            }
        }
    ]
}

}

Unbound classpath container in Eclipse

I had a similar problem when I recreated my workspace that was fixed in the following way:

Go to Eclipse -> Preferences, under Java select "Installed JREs" and check one of the boxes to specify a default JRE. Click OK and then go back to your project's properties. Go to the "Java Build Path" section and choose the "Libraries" tab. Remove the unbound System Default library, then click the "Add Library" button. Select "JRE System Library" and you should be good to go!

Using Excel OleDb to get sheet names IN SHEET ORDER

This worked for me. Stolen from here: How do you get the name of the first page of an excel workbook?

object opt = System.Reflection.Missing.Value;
Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook workbook = app.Workbooks.Open(WorkBookToOpen,
                                         opt, opt, opt, opt, opt, opt, opt,
                                         opt, opt, opt, opt, opt, opt, opt);
Excel.Worksheet worksheet = workbook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
string firstSheetName = worksheet.Name;

Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"?

This enables you to write something like:

void doSomething() {
    List<String>list = new ArrayList<String>();
    //do something
}

Later on, you might want to change it to:

void doSomething() {
    List<String>list = new LinkedList<String>();
    //do something
}

without having to change the rest of the method.

However, if you want to use a CopyOnWriteArrayList for example, you would need to declare it as such, and not as a List if you wanted to use its extra methods (addIfAbsent for example):

void doSomething() {
    CopyOnWriteArrayList<String>list = new CopyOnWriteArrayList<String>();
    //do something, for example:
    list.addIfAbsent("abc");
}

Pandas concat: ValueError: Shape of passed values is blah, indices imply blah2

Your indexes probably contains duplicated values.

import pandas as pd

T1_INDEX = [
    0,
    1,  # <= !!! if I write e.g.: "0" here then it fails
    0.2,
]
T1_COLUMNS = [
    'A', 'B', 'C', 'D'
]
T1 = [
    [1.0, 1.1, 1.2, 1.3],
    [2.0, 2.1, 2.2, 2.3],
    [3.0, 3.1, 3.2, 3.3],
]

T2_INDEX = [
    1.2,
    2.11,
]

T2_COLUMNS = [
    'D', 'E', 'F',
]
T2 = [
    [54.0, 5324.1, 3234.2],
    [55.0, 14.5324, 2324.2],
    # [3.0, 3.1, 3.2],
]
df1 = pd.DataFrame(T1, columns=T1_COLUMNS, index=T1_INDEX)
df2 = pd.DataFrame(T2, columns=T2_COLUMNS, index=T2_INDEX)


print(pd.concat([pd.DataFrame({})] + [df2, df1], axis=1))

Change fill color on vector asset in Android Studio

To change vector image color you can directly use android:tint="@color/colorAccent"

<ImageView
        android:id="@+id/ivVectorImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_account_circle_black_24dp"
        android:tint="@color/colorAccent" />

To change color programatically

ImageView ivVectorImage = (ImageView) findViewById(R.id.ivVectorImage);
ivVectorImage.setColorFilter(getResources().getColor(R.color.colorPrimary));

Setting font on NSAttributedString on UITextView disregards line spacing

I found your question because I was also fighting with NSAttributedString. For me, the beginEditing and endEditing methods did the trick, like stated in Changing an Attributed String. Apart from that, the lineSpacing is set with setLineSpacing on the paragraphStyle.

So you might want to try changing your code to:

NSString *string = @" Hello \n world";
attrString = [[NSMutableAttributedString alloc] initWithString:string];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];

[paragraphStyle setLineSpacing:20]  // Or whatever (positive) value you like...    
[attrSting beginEditing];

[attrString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:20] range:NSMakeRange(0, string.length)];
[attrString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, string.length)];

[attrString endEditing];

mainTextView.attributedText = attrString;

Didn't test this exact code though, btw, but mine looks nearly the same.

EDIT:

Meanwhile, I've tested it, and, correct me if I'm wrong, the - beginEditing and - endEditing calls seem to be of quite an importance.

wildcard * in CSS for classes

An alternative solution:

div[class|='tocolor'] will match for values of the "class" attribute that begin with "tocolor-", including "tocolor-1", "tocolor-2", etc.

Beware that this won't match

<div class="foo tocolor-">

Reference: https://www.w3.org/TR/css3-selectors/#attribute-representation

[att|=val]

Represents an element with the att attribute, its value either being exactly "val" or beginning with "val" immediately followed by "-" (U+002D)

Hide the browse button on a input type=file

Just add negative text intent as so:

input[type=file] {
  text-indent: -120px;
}

before:

enter image description here

after:

enter image description here

Changing the cursor in WPF sometimes works, sometimes doesn't

The following worked for me:

ForceCursor = true;
Cursor = Cursors.Wait;

Error message 'java.net.SocketException: socket failed: EACCES (Permission denied)'

You may need to do AndroidStudio - Build - Clean

If you updated manifest through the filesystem or Git it won't pick up the changes.

Nested Git repositories?

Just for completeness:

There is another solution, I would recommend: subtree merging.

In contrast to submodules, it's easier to maintain. You would create each repository the normal way. While in your main repository, you want to merge the master (or any other branch) of another repository in a directory of your main directory.

$ git remote add -f OtherRepository /path/to/that/repo
$ git merge -s ours --no-commit OtherRepository/master
$ git read-tree --prefix=AnyDirectoryToPutItIn/ -u OtherRepository/master
$ git commit -m "Merge OtherRepository project as our subdirectory"`

Then, in order to pull the other repository into your directory (to update it), use the subtree merge strategy:

$ git pull -s subtree OtherRepository master

I'm using this method for years now, it works :-)

More about this way including comparing it with sub modules may be found in this git howto doc.

PackagesNotFoundError: The following packages are not available from current channels:

Try adding the conda-forge channel to your list of channels with this command:
conda config --append channels conda-forge. It tells conda to also look on the conda-forge channel when you search for packages. You can then simply install the two packages with conda install slycot control.

Channels are basically servers for people to host packages on and the community-driven conda-forge is usually a good place to start when packages are not available via the standard channels. I checked and both slycot and control seem to be available there.

How can I add new keys to a dictionary?

The conventional syntax is d[key] = value, but if your keyboard is missing the square bracket keys you could also do:

d.__setitem__(key, value)

In fact, defining __getitem__ and __setitem__ methods is how you can make your own class support the square bracket syntax. See https://python.developpez.com/cours/DiveIntoPython/php/endiveintopython/object_oriented_framework/special_class_methods.php

Solution to INSTALL_FAILED_INSUFFICIENT_STORAGE error on Android

If you are running your application on an emulator, and if this problem persists, check your notification manager. If it shows you an icon and notification about "Phone memory is full", that means you have already installed so many applications on your emulator. Uninstall several applications which you don't want currently from "Settings >> Manage Application >> Select Application >> Uninstall".
That Set.
Now re-run the program.

What is a constant reference? (not a reference to a constant)

First I think int&const icr=i; is just int& icr = i, Modifier 'const' makes no sense(It just means you cannot make the reference refer to other variable).

const int x = 10;
// int& const y = x; // Compiler error here

Second, constant reference just means you cannot change the value of variable through reference.

const int x = 10;
const int& y = x;
//y = 20; // Compiler error here

Third, Constant references can bind right-value. Compiler will create a temp variable to bind the reference.

float x = 10;
const int& y = x;
const int& z = y + 10;
cout << (long long)&x << endl; //print 348791766212
cout << (long long)&y << endl; //print 348791766276
cout << (long long)&z << endl; //print 348791766340

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

I had this issue when using the history API.

window.history.pushState(null, null, URL);

Even with a local server (localhost), you want to add 'http://' to your URL so that you have something similar to:

http://localhost...

list.clear() vs list = new ArrayList<Integer>();

If there is a good chance that the list will contain as much elements as it contains when clearing it, and if you're not in need for free memory, clearing the list is a better option. But my guess is that it probably doesn't matter. Don't try to optimize until you have detected a performance problem, and identified where it comes from.

Printing an array in C++?

My simple answer is:

#include <iostream>
using namespace std;

int main()
{
    int data[]{ 1, 2, 7 };
    for (int i = sizeof(data) / sizeof(data[0])-1; i >= 0; i--) {
        cout << data[i];
    }

    return 0;
}

Event on a disabled input

suggestion here looks like a good candidate for this question as well

Performing click event on a disabled element? Javascript jQuery

jQuery('input#submit').click(function(e) {
    if ( something ) {        
        return false;
    } 
});

How to exit a 'git status' list in a terminal?

Please try this steps in git bash, It may help you.

  1. CTRL + C
  2. :qa!

Changing an element's ID with jQuery

I'm not sure what your goal is, but might it be better to use addClass instead? I mean an objects ID in my opinion should be static and specific to that object. If you are just trying to change it from showing on the page or something like that I would put those details in a class and then add it to the object rather then trying to change it's ID. Again, I'm saying that without understand your underlining goal.

SQL Server query to find all current database names

For people where "sys.databases" does not work, You can use this aswell;

SELECT DISTINCT TABLE_SCHEMA from INFORMATION_SCHEMA.COLUMNS