Programs & Examples On #Jco

JCO is the short-cut for java connector. JCO refers to a java library used to connect to SAP systems through the SAP RFC protocol.

how to fix EXE4J_JAVA_HOME, No JVM could be found on your system error?

It worked for me, but the exe4j can leave a signature when you double click the .exe application

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

CSS selector:

Use a CSS selector of img[src='images/toolbar/b_edit.gif']

This says select element(s) with img tag with attribute src having value of 'images/toolbar/b_edit.gif'


CSS query:

CSS query


VBA:

You can apply the selector with the .querySelector method of document.

IE.document.querySelector("img[src='images/toolbar/b_edit.gif']").Click

pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"

-----> pip install gensim config --global http.sslVerify false

Just install any package with the "config --global http.sslVerify false" statement

You can ignore SSL errors by setting pypi.org and files.pythonhosted.org as trusted hosts.

$ pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org <package_name>

Note: Sometime during April 2018, the Python Package Index was migrated from pypi.python.org to pypi.org. This means "trusted-host" commands using the old domain no longer work.

Permanent Fix

Since the release of pip 10.0, you should be able to fix this permanently just by upgrading pip itself:

$ pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org pip setuptools

Or by just reinstalling it to get the latest version:

$ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

(… and then running get-pip.py with the relevant Python interpreter).

pip install <otherpackage> should just work after this. If not, then you will need to do more, as explained below.


You may want to add the trusted hosts and proxy to your config file.

pip.ini (Windows) or pip.conf (unix)

[global]
trusted-host = pypi.python.org
               pypi.org
               files.pythonhosted.org

Alternate Solutions (Less secure)

Most of the answers could pose a security issue.

Two of the workarounds that help in installing most of the python packages with ease would be:

  • Using easy_install: if you are really lazy and don't want to waste much time, use easy_install <package_name>. Note that some packages won't be found or will give small errors.
  • Using Wheel: download the Wheel of the python package and use the pip command pip install wheel_package_name.whl to install the package.

How to create JNDI context in Spring Boot with Embedded Tomcat Container

In SpringBoot 2.1, I found another solution. Extend standard factory class method getTomcatWebServer. And then return it as a bean from anywhere.

public class CustomTomcatServletWebServerFactory extends TomcatServletWebServerFactory {

    @Override
    protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
        System.setProperty("catalina.useNaming", "true");
        tomcat.enableNaming();
        return new TomcatWebServer(tomcat, getPort() >= 0);
    }
}

@Component
public class TomcatConfiguration {
    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new CustomTomcatServletWebServerFactory();

        return factory;
    }

Loading resources from context.xml doesn't work though. Will try to find out.

java IO Exception: Stream Closed

You call writer.close(); in writeToFile so the writer has been closed the second time you call writeToFile.

Why don't you merge FileStatus into writeToFile?

json: cannot unmarshal object into Go value of type

Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:

json: cannot unmarshal object into Go struct field Comment.author of type string

Getting Error 800a0e7a "Provider cannot be found. It may not be properly installed."

A couple of suggestions

The ACE driver isn't installed by default. It's also a 64 bit driver, so it might be worth disabling 32bit in your app pool. I've known 64 bit drivers not work when 32 bit is enabled.(eg the ISAPI filter which connects IIS to Tomcat).

The older JET driver is 32bit. It is included by default. If you could save a copy of your database as a .mdb file then using the JET driver might be a workaround

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

Near the top of the code with the Public Workshop(), I am assumeing this bit,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


suitButton = new JCheckBox("Denim Jeans");
suitButton.setMnemonic(KeyEvent.VK_U);

should maybe be,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


denimjeansButton = new JCheckBox("Denim Jeans");
denimjeansButton.setMnemonic(KeyEvent.VK_U);

How to add row of data to Jtable from values received from jtextfield and comboboxes

Peeskillet's lame tutorial for working with JTables in Netbeans GUI Builder

  • Set the table column headers
    1. Highglight the table in the design view then go to properties pane on the very right. Should be a tab that says "Properties". Make sure to highlight the table and not the scroll pane surrounding it, or the next step wont work
    2. Click on the ... button to the right of the property model. A dialog should appear.
    3. Set rows to 0, set the number of columns you want, and their names.
  • Add a button to the frame somwhere,. This button will be clicked when the user is ready to submit a row

    1. Right-click on the button and select Events -> Action -> actionPerformed
    2. You should see code like the following auto-generated

      private void jButton1ActionPerformed(java.awt.event.ActionEvent) {}
      
  • The jTable1 will have a DefaultTableModel. You can add rows to the model with your data

    private void jButton1ActionPerformed(java.awt.event.ActionEvent) {
        String data1 = something1.getSomething();
        String data2 = something2.getSomething();
        String data3 = something3.getSomething();
        String data4 = something4.getSomething();
    
        Object[] row = { data1, data2, data3, data4 };
    
        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
    
        model.addRow(row);
    
        // clear the entries.
    }
    

So for every set of data like from a couple text fields, a combo box, and a check box, you can gather that data each time the button is pressed and add it as a row to the model.

Could not resolve placeholder in string value

You can also try default values. spring-value-annotation

Default values can be provided for properties that might not be defined. In this example the value “some default” will be injected:

@Value("${unknown.param:some default}")
private String someDefault;

If the same property is defined as a system property and in the properties file, then the system property would be applied.

Cannot convert lambda expression to type 'string' because it is not a delegate type

If it's not related to missing using directives stated by other users, this will also happen if there is another problem with your query.

Take a look on VS compiler error list : For example, if the "Value" variable in your query doesn't exist, you will have the "lambda to string" error, and a few errors after another one more related to the unknown/erroneous field.

In your case it could be :

objContentLine = (from q in db.qryContents
                  where q.LineID == Value
                  orderby q.RowID descending
                  select q).FirstOrDefault();

Errors:

Error 241 Cannot convert lambda expression to type 'string' because it is not a delegate type

Error 242 Delegate 'System.Func<..>' does not take 1 arguments

Error 243 The name 'Value' does not exist in the current context

Fix the "Value" variable error and the other errors will also disappear.

AngularJS multiple filter with custom filter function

Hope below answer in this link will help, Multiple Value Filter

And take a look into the fiddle with example

arrayOfObjectswithKeys | filterMultiple:{key1:['value1','value2','value3',...etc],key2:'value4',key3:[value5,value6,...etc]}

fiddle

fix java.net.SocketTimeoutException: Read timed out

Here are few pointers/suggestions for investigation

  1. I see that every time you vote, you call vote method which creates a fresh HTTP connection.
  2. This might be a problem. I would suggest to use a single HttpClient instance to post to the server. This way it wont create too many connections from the client side.
  3. At the end of everything, HttpClient needs to be shut and hence call httpclient.getConnectionManager().shutdown(); to release the resources used by the connections.

Adding items to a JComboBox

You can use String arrays to add jComboBox items

String [] items = { "First item", "Second item", "Third item", "Fourth item" };

JComboBox comboOne = new JComboBox (items);

ASP.Net MVC - Read File from HttpPostedFileBase without save

byte[] data; using(Stream inputStream=file.InputStream) { MemoryStream memoryStream = inputStream as MemoryStream; if (memoryStream == null) { memoryStream = new MemoryStream(); inputStream.CopyTo(memoryStream); } data = memoryStream.ToArray(); }

An Authentication object was not found in the SecurityContext - Spring 3.2.2

This could also happens if you put a @PreAuthorize or @PostAuthorize in a Bean in creation. I would recommend to move such annotations to methods of interest.

Execute an action when an item on the combobox is selected

this is how you do it with ActionLIstener

import java.awt.FlowLayout;
import java.awt.event.*;

import javax.swing.*;

public class MyWind extends JFrame{

    public MyWind() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setLayout(new FlowLayout(FlowLayout.LEFT));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JTextField field = new JTextField();
        field.setSize(200, 50);
        field.setText("              ");

        JComboBox comboBox = new JComboBox();
        comboBox.setEditable(true);
        comboBox.addItem("item1");
        comboBox.addItem("item2");

        //
        // Create an ActionListener for the JComboBox component.
        //
        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                //
                // Get the source of the component, which is our combo
                // box.
                //
                JComboBox comboBox = (JComboBox) event.getSource();

                Object selected = comboBox.getSelectedItem();
                if(selected.toString().equals("item1"))
                field.setText("30");
                else if(selected.toString().equals("item2"))
                    field.setText("40");

            }
        });
        getContentPane().add(comboBox);
        getContentPane().add(field);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MyWind().setVisible(true);
            }
        });
    }
}

Increase JVM max heap size for Eclipse

It is possible to increase heap size allocated by the Java Virtual Machine (JVM) by using command line options.

-Xms<size>        set initial Java heap size
-Xmx<size>        set maximum Java heap size
-Xss<size>        set java thread stack size

If you are using the tomcat server, you can change the heap size by going to Eclipse/Run/Run Configuration and select Apache Tomcat/your_server_name/Arguments and under VM arguments section use the following:

-XX:MaxPermSize=256m
-Xms256m -Xmx512M

If you are not using any server, you can type the following on the command line before you run your code:

java -Xms64m -Xmx256m HelloWorld

More information on increasing the heap size can be found here

Displaying Image in Java

import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

public class DisplayImage {

    public static void main(String avg[]) throws IOException
    {
        DisplayImage abc=new DisplayImage();
    }

    public DisplayImage() throws IOException
    {
        BufferedImage img=ImageIO.read(new File("f://images.jpg"));
        ImageIcon icon=new ImageIcon(img);
        JFrame frame=new JFrame();
        frame.setLayout(new FlowLayout());
        frame.setSize(200,300);
        JLabel lbl=new JLabel();
        lbl.setIcon(icon);
        frame.add(lbl);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

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

The fields of your object have in turn their fields, some of which do not implement Serializable. In your case the offending class is TransformGroup. How to solve it?

  • if the class is yours, make it Serializable
  • if the class is 3rd party, but you don't need it in the serialized form, mark the field as transient
  • if you need its data and it's third party, consider other means of serialization, like JSON, XML, BSON, MessagePack, etc. where you can get 3rd party objects serialized without modifying their definitions.

Command-line Tool to find Java Heap Size and Memory Used (Linux)?

Using top command is the simplest way to check memory usage of the program. RES column shows the real physical memory that is occupied by a process.

For my case, I had a 10g file read in java and each time I got outOfMemory exception. This happened when the value in the RES column reached to the value set in -Xmx option. Then by increasing the memory using -Xmx option everything went fine.

Get combobox value in Java swing

If the string is empty, comboBox.getSelectedItem().toString() will give a NullPointerException. So better to typecast by (String).

How to call a VbScript from a Batch File without opening an additional command prompt

If you want to fix vbs associations type

regsvr32 vbscript.dll
regsvr32 jscript.dll
regsvr32 wshext.dll
regsvr32 wshom.ocx
regsvr32 wshcon.dll
regsvr32 scrrun.dll

Also if you can't use vbs due to management then convert your script to a vb.net program which is designed to be easy, is easy, and takes 5 minutes.

Big difference is functions and subs are both called using brackets rather than just functions.

So the compilers are installed on all computers with .NET installed.

See this article here on how to make a .NET exe. Note the sample is for a scripting host. You can't use this, you have to put your vbs code in as .NET code.

How can I convert a VBScript to an executable (EXE) file?

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

DBNull if statement

Ternary operator should do nicely here: condition ? first_expression : second_expression;

strLevel = !Convert.IsDBNull(rsData["usr.ursrdaystime"]) ? Convert.ToString(rsData["usr.ursrdaystime"]) : null

configure: error: C compiler cannot create executables

I just had this issue building react-native app when I try to install Pod. I had to export 2 variables:

export CC=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
CPP='/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -E'

Jetty: HTTP ERROR: 503/ Service Unavailable

2012-04-20 11:14:32.617:WARN:oejx.XmlParser:FATAL@file:/C:/Users/***/workspace/Test/WEB-INF/web.xml line:1 col:7 : org.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.

You Log says, that you web.xml is malformed. Line 1, colum 7. It may be a UTF-8 Byte-Order-Marker

Try to verify, that your xml is wellformed and does not have a BOM. Java doesn't use BOMs.

Programmatically select a row in JTable

You use the available API of JTable and do not try to mess with the colors.

Some selection methods are available directly on the JTable (like the setRowSelectionInterval). If you want to have access to all selection-related logic, the selection model is the place to start looking

How to set selected index JComboBox by value

The right way to set an item selected when the combobox is populated by some class' constructor (as @milosz posted):

combobox.getModel().setSelectedItem(new ClassName(parameter1, parameter2));

In your case the code would be:

test.getModel().setSelectedItem(new ComboItem(3, "banana"));

Conditionally Remove Dataframe Rows with R

Use the which function:

A <- c('a','a','b','b','b')
B <- c(1,0,1,1,0)
d <- data.frame(A, B)

r <- with(d, which(B==0, arr.ind=TRUE))
newd <- d[-r, ]

Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

I had the same problem. The only thing that solved it was merge the content of META-INF/spring.handler and META-INF/spring.schemas of each spring jar file into same file names under my META-INF project.

This two threads explain it better:

Maven2: Missing artifact but jars are in place

I had similar problem. it was showing error "Missing artifact......".After digging in, I found that I have proxy settings enabled which should be configured (proxyname, user/pwd) in setting.xml inside conf folder of Maven. As a resolution go to Eclipse....Windows->preferences->Maven->UserSettings....and update the user setting to point the setting.xml which you have inside conf folder of Maven. After that go to Project->Update All Maven Dependencies. It should work fine after the build.

Get the element triggering an onclick event in jquery?

If you don't want to pass the clicked on element to the function through a parameter, then you need to access the event object that is happening, and get the target from that object. This is most easily done if you bind the click event like this:

$('#sendButton').click(function(e){
    var SendButton = $(e.target);
    var TheForm = SendButton.parents('form');
    TheForm.submit();

    return false;
});

Connection Strings for Entity Framework

Instead of using config files you can use a configuration database with a scoped systemConfig table and add all your settings there.

CREATE TABLE [dbo].[SystemConfig]  
    (  
      [Id] [int] IDENTITY(1, 1)  
                 NOT NULL ,  
      [AppName] [varchar](128) NULL ,  
      [ScopeName] [varchar](128) NOT NULL ,  
      [Key] [varchar](256) NOT NULL ,  
      [Value] [varchar](MAX) NOT NULL ,  
      CONSTRAINT [PK_SystemConfig_ID] PRIMARY KEY NONCLUSTERED ( [Id] ASC )  
        WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,  
               IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,  
               ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]  
    )  
ON  [PRIMARY]  

GO  

SET ANSI_PADDING OFF  
GO  

ALTER TABLE [dbo].[SystemConfig] ADD  CONSTRAINT [DF_SystemConfig_ScopeName]  DEFAULT ('SystemConfig') FOR [ScopeName]  
GO 

With such configuration table you can create rows like such: enter image description here

Then from your your application dal(s) wrapping EF you can easily retrieve the scoped configuration.
If you are not using dal(s) and working in the wire directly with EF, you can make an Entity from the SystemConfig table and use the value depending on the application you are on.

Preferred way of getting the selected item of a JComboBox

String x = JComboBox.getSelectedItem().toString();

will convert any value weather it is Integer, Double, Long, Short into text on the other hand,

String x = String.valueOf(JComboBox.getSelectedItem());

will avoid null values, and convert the selected item from object to string

Could not resolve Spring property placeholder

Ensure 'idm.url' is set in property file and the property file is loaded

How to set the component size with GridLayout? Is there a better way?

In my project I managed to use GridLayout and results are very stable, with no flickering and with a perfectly working vertical scrollbar.

First I created a JPanel for the settings; in my case it is a grid with a row for each parameter and two columns: left column is for labels and right column is for components. I believe your case is similar.

JPanel yourSettingsPanel = new JPanel();
yourSettingsPanel.setLayout(new GridLayout(numberOfParams, 2));

I then populate this panel by iterating on my parameters and alternating between adding a JLabel and adding a component.

for (int i = 0; i < numberOfParams; ++i) {
    yourSettingsPanel.add(labels[i]);
    yourSettingsPanel.add(components[i]);
}

To prevent yourSettingsPanel from extending to the entire container I first wrap it in the north region of a dummy panel, that I called northOnlyPanel.

JPanel northOnlyPanel = new JPanel();
northOnlyPanel.setLayout(new BorderLayout());
northOnlyPanel.add(yourSettingsPanel, BorderLayout.NORTH);

Finally I wrap the northOnlyPanel in a JScrollPane, which should behave nicely pretty much anywhere.

JScrollPane scroll = new JScrollPane(northOnlyPanel,
                                     JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                     JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

Most likely you want to display this JScrollPane extended inside a JFrame; you can add it to a BorderLayout JFrame, in the CENTER region:

window.add(scroll, BorderLayout.CENTER);

In my case I put it on the left column of a GridLayout(1, 2) panel, and I use the right column to display contextual help for each parameter.

JTextArea help = new JTextArea();
help.setLineWrap(true);
help.setWrapStyleWord(true);
help.setEditable(false);

JPanel split = new JPanel();
split.setLayout(new GridLayout(1, 2));
split.add(scroll);
split.add(help);

Yes or No confirm box using jQuery

Have a look at this jQuery plugin: jquery.confirm.

<a href="home" class="confirm">Go to home</a>

and then:

$(".confirm").confirm();

This will show a confirmation popup before proceeding to following the link.

There's a demo here: http://myclabs.github.com/jquery.confirm/

Difference between JPanel, JFrame, JComponent, and JApplet

JFrame and JApplet are top level containers. If you wish to create a desktop application, you will use JFrame and if you plan to host your application in browser you will use JApplet.

JComponent is an abstract class for all Swing components and you can use it as the base class for your new component. JPanel is a simple usable component you can use for almost anything.

Since this is for a fun project, the simplest way for you is to work with JPanel and then host it inside JFrame or JApplet. Netbeans has a visual designer for Swing with simple examples.

Calling JMX MBean method from a shell script

Take a look at JManage. It's able to execute MBean methods and get / set attributes from command line.

How do I populate a JComboBox with an ArrayList?

By combining existing answers (this one and this one) the proper type safe way to add an ArrayList to a JComboBox is the following:

private DefaultComboBoxModel<YourClass> getComboBoxModel(List<YourClass> yourClassList)
{
    YourClass[] comboBoxModel = yourClassList.toArray(new YourClass[0]);
    return new DefaultComboBoxModel<>(comboBoxModel);
}

In your GUI code you set the entire list into your JComboBox as follows:

DefaultComboBoxModel<YourClass> comboBoxModel = getComboBoxModel(yourClassList);
comboBox.setModel(comboBoxModel);

log4j:WARN No appenders could be found for logger in web.xml

In my case the solution was easy. You don't need to declare anything in your web.xml.

Because your project is a web application, the config file should be on WEB-INF/classes after deployment. I advise you to create a Java resource folder (src/main/resources) to do that (best pratice). Another approach is to put the config file in your src/main/java.

Beware with the configuration file name. If you are using XML, the file name is log4j.xml, otherwise log4j.properties.

How is the java memory pool divided?

With Java8, non heap region no more contains PermGen but Metaspace, which is a major change in Java8, supposed to get rid of out of memory errors with java as metaspace size can be increased depending on the space required by jvm for class data.

Try/catch does not seem to have an effect

In my case, it was because I was only catching specific types of exceptions:

try
  {
    get-item -Force -LiteralPath $Path -ErrorAction Stop

    #if file exists
    if ($Path -like '\\*') {$fileType = 'n'}  #Network
    elseif ($Path -like '?:\*') {$fileType = 'l'} #Local
    else {$fileType = 'u'} #Unknown File Type

  }
catch [System.UnauthorizedAccessException] {$fileType = 'i'} #Inaccessible
catch [System.Management.Automation.ItemNotFoundException]{$fileType = 'x'} #Doesn't Exist

Added these to handle additional the exception causing the terminating error, as well as unexpected exceptions

catch [System.Management.Automation.DriveNotFoundException]{$fileType = 'x'} #Doesn't Exist
catch {$fileType='u'} #Unknown

How to activate JMX on my JVM for access with jconsole?

I had this exact issue, and created a GitHub project for testing and figuring out the correct settings.

It contains a working Dockerfile with supporting scripts, and a simple docker-compose.yml for quick testing.

Remote JMX connection

Had it been on Linux the problem would be that localhost is the loopback interface, you need to application to bind to your network interface.

You can use the netstat to confirm that it is not bound to the expected network interface.

You can make this work by invoking the program with the system parameter java.rmi.server.hostname="YOUR_IP", either as an environment variable or using

java -Djava.rmi.server.hostname=YOUR_IP YOUR_APP

Has anyone ever got a remote JMX JConsole to work?

You are probably experiencing an issue with a firewall. The 'problem' is that the port you specify is not the only port used, it uses 1 or maybe even 2 more ports for RMI, and those are probably blocked by a firewall.

One of the extra ports will not be know up front if you use the default RMI configuration, so you have to open up a big range of ports - which might not amuse the server administrator.

There is a solution that does not require opening up a lot of ports however, I've gotten it to work using the combined source snippets and tips from

http://forums.sun.com/thread.jspa?threadID=5267091 - link doesn't work anymore

http://blogs.oracle.com/jmxetc/entry/connecting_through_firewall_using_jmx

http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html

It's even possible to setup an ssh tunnel and still get it to work :-)

JComboBox Selection Change Listener?

It should respond to ActionListeners, like this:

combo.addActionListener (new ActionListener () {
    public void actionPerformed(ActionEvent e) {
        doSomething();
    }
});

@John Calsbeek rightly points out that addItemListener() will work, too. You may get 2 ItemEvents, though, one for the deselection of the previously selected item, and another for the selection of the new item. Just don't use both event types!

How to use a switch case 'or' in PHP

Try with these following examples in this article : http://phpswitch.com/

Possible Switch Cases :

(i). A simple switch statement

The switch statement is wondrous and magic. It's a piece of the language that allows you to select between different options for a value, and run different pieces of code depending on which value is set.

Each possible option is given by a case in the switch statement.

Example :

switch($bar)
{
    case 4:
        echo "This is not the number you're looking for.\n";
        $foo = 92;
}

(ii). Delimiting code blocks

The major caveat of switch is that each case will run on into the next one, unless you stop it with break. If the simple case above is extended to cover case 5:

Example :

case 4:
    echo "This is not the number you're looking for.\n";
    $foo = 92;
    break;

case 5:
    echo "A copy of Ringworld is on its way to you!\n";
    $foo = 34;
    break;

(iii). Using fallthrough for multiple cases

Because switch will keep running code until it finds a break, it's easy enough to take the concept of fallthrough and run the same code for more than one case:

Example :

case 2:

case 3:
case 4:
    echo "This is not the number you're looking for.\n";
    $foo = 92;
    break;

case 5:
    echo "A copy of Ringworld is on its way to you!\n";
    $foo = 34;
    break;

(iv). Advanced switching: Condition cases

PHP's switch doesn't just allow you to switch on the value of a particular variable: you can use any expression as one of the cases, as long as it gives a value for the case to use. As an example, here's a simple validator written using switch:

Example :

switch(true)
{
    case (strlen($foo) > 30):
        $error = "The value provided is too long.";
    $valid = false;
    break;

    case (!preg_match('/^[A-Z0-9]+$/i', $foo)):
        $error = "The value must be alphanumeric.";
    $valid = false;
    break;

    default:
    $valid = true;
    break;
}

i think this may help you to resolve your problem.

Switch statement fallthrough in C#?

They left out this behaviour by design to avoid when it was not used by will but caused problems.

It can be used only if there is no statement in the case part, like:

switch (whatever)
{
    case 1:
    case 2:
    case 3: boo; break;
}

Creating instance list of different objects

List<Object> objects = new ArrayList<Object>();

objects list will accept any of the Object

You could design like as follows

public class BaseEmployee{/* stuffs */}

public class RegularEmployee extends BaseEmployee{/* stuffs */}

public class Contractors extends BaseEmployee{/* stuffs */}

and in list

List<? extends BaseEmployee> employeeList = new ArrayList<? extends BaseEmployee>();

selecting from multi-index pandas

You can use DataFrame.xs():

In [36]: df = DataFrame(np.random.randn(10, 4))

In [37]: df.columns = [np.random.choice(['a', 'b'], size=4).tolist(), np.random.choice(['c', 'd'], size=4)]

In [38]: df.columns.names = ['A', 'B']

In [39]: df
Out[39]:
A      b             a
B      d      d      d      d
0 -1.406  0.548 -0.635  0.576
1 -0.212 -0.583  1.012 -1.377
2  0.951 -0.349 -0.477 -1.230
3  0.451 -0.168  0.949  0.545
4 -0.362 -0.855  1.676 -2.881
5  1.283  1.027  0.085 -1.282
6  0.583 -1.406  0.327 -0.146
7 -0.518 -0.480  0.139  0.851
8 -0.030 -0.630 -1.534  0.534
9  0.246 -1.558 -1.885 -1.543

In [40]: df.xs('a', level='A', axis=1)
Out[40]:
B      d      d
0 -0.635  0.576
1  1.012 -1.377
2 -0.477 -1.230
3  0.949  0.545
4  1.676 -2.881
5  0.085 -1.282
6  0.327 -0.146
7  0.139  0.851
8 -1.534  0.534
9 -1.885 -1.543

If you want to keep the A level (the drop_level keyword argument is only available starting from v0.13.0):

In [42]: df.xs('a', level='A', axis=1, drop_level=False)
Out[42]:
A      a
B      d      d
0 -0.635  0.576
1  1.012 -1.377
2 -0.477 -1.230
3  0.949  0.545
4  1.676 -2.881
5  0.085 -1.282
6  0.327 -0.146
7  0.139  0.851
8 -1.534  0.534
9 -1.885 -1.543

How to pause javascript code execution for 2 seconds

There's no way to stop execution of your code as you would do with a procedural language. You can instead make use of setTimeout and some trickery to get a parametrized timeout:

for (var i = 1; i <= 5; i++) {
    var tick = function(i) {
        return function() {
            console.log(i);
        }
    };
    setTimeout(tick(i), 500 * i);
}

Demo here: http://jsfiddle.net/hW7Ch/

CakePHP find method with JOIN

There are two main ways that you can do this. One of them is the standard CakePHP way, and the other is using a custom join.

It's worth pointing out that this advice is for CakePHP 2.x, not 3.x.

The CakePHP Way

You would create a relationship with your User model and Messages Model, and use the containable behavior:

class User extends AppModel {
    public $actsAs = array('Containable');
    public $hasMany = array('Message');
}

class Message extends AppModel {
    public $actsAs = array('Containable');
    public $belongsTo = array('User');
}

You need to change the messages.from column to be messages.user_id so that cake can automagically associate the records for you.

Then you can do this from the messages controller:

$this->Message->find('all', array(
    'contain' => array('User')
    'conditions' => array(
        'Message.to' => 4
    ),
    'order' => 'Message.datetime DESC'
));

The (other) CakePHP way

I recommend using the first method, because it will save you a lot of time and work. The first method also does the groundwork of setting up a relationship which can be used for any number of other find calls and conditions besides the one you need now. However, cakePHP does support a syntax for defining your own joins. It would be done like this, from the MessagesController:

$this->Message->find('all', array(
    'joins' => array(
        array(
            'table' => 'users',
            'alias' => 'UserJoin',
            'type' => 'INNER',
            'conditions' => array(
                'UserJoin.id = Message.from'
            )
        )
    ),
    'conditions' => array(
        'Message.to' => 4
    ),
    'fields' => array('UserJoin.*', 'Message.*'),
    'order' => 'Message.datetime DESC'
));

Note, I've left the field name messages.from the same as your current table in this example.

Using two relationships to the same model

Here is how you can do the first example using two relationships to the same model:

class User extends AppModel {
    public $actsAs = array('Containable');
    public $hasMany = array(
        'MessagesSent' => array(
            'className'  => 'Message',
            'foreignKey' => 'from'
         )
    );
    public $belongsTo = array(
        'MessagesReceived' => array(
            'className'  => 'Message',
            'foreignKey' => 'to'
         )
    );
}

class Message extends AppModel {
    public $actsAs = array('Containable');
    public $belongsTo = array(
        'UserFrom' => array(
            'className'  => 'User',
            'foreignKey' => 'from'
        )
    );
    public $hasMany = array(
        'UserTo' => array(
            'className'  => 'User',
            'foreignKey' => 'to'
        )
    );
}

Now you can do your find call like this:

$this->Message->find('all', array(
    'contain' => array('UserFrom')
    'conditions' => array(
        'Message.to' => 4
    ),
    'order' => 'Message.datetime DESC'
));

convert an enum to another type of enum

To be thorough I normally create a pair of functions, one that takes Enum 1 and returns Enum 2 and another that takes Enum 2 and returns Enum 1. Each consists of a case statement mapping inputs to outputs and the default case throws an exception with a message complaining about an unexpected value.

In this particular case you could take advantage of the fact that the integer values of Male and Female are the same, but I'd avoid that as it's hackish and subject to breakage if either enum changes in the future.

Unable to find valid certification path to requested target - error even after cert imported

Unfortunately - it could be many things - and lots of app servers and other java 'wrappers' are prone to play with properties and their 'own' take on keychains and what not. So it may be looking at something totally different.

Short of truss-ing - I'd try:

java -Djavax.net.debug=all -Djavax.net.ssl.trustStore=trustStore ...

to see if that helps. Instead of 'all' one can also set it to 'ssl', key manager and trust manager - which may help in your case. Setting it to 'help' will list something like below on most platforms.

Regardless - do make sure you fully understand the difference between the keystore (in which you have the private key and cert you prove your own identity with) and the trust store (which determines who you trust) - and the fact that your own identity also has a 'chain' of trust to the root - which is separate from any chain to a root you need to figure out 'who' you trust.

all            turn on all debugging
ssl            turn on ssl debugging

The   following can be used with ssl:
    record       enable per-record tracing
    handshake    print each handshake message
    keygen       print key generation data
    session      print session activity
    defaultctx   print default SSL initialization
    sslctx       print SSLContext tracing
    sessioncache print session cache tracing
    keymanager   print key manager tracing
    trustmanager print trust manager tracing
    pluggability print pluggability tracing

    handshake debugging can be widened with:
    data         hex dump of each handshake message
    verbose      verbose handshake message printing

    record debugging can be widened with:
    plaintext    hex dump of record plaintext
    packet       print raw SSL/TLS packets

Source: # See http://download.oracle.com/javase/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#Debug

Android toolbar center title and custom font

    public class TestActivity extends AppCompatActivity {
    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_test);

        toolbar = (Toolbar) findViewById(R.id.tool_bar); // Attaching the layout to the toolbar object
        setSupportActionBar(toolbar);

        customizeToolbar(toolbar);
    }

    public void customizeToolbar(Toolbar toolbar){
        // Save current title and subtitle
        final CharSequence originalTitle = toolbar.getTitle();
        final CharSequence originalSubtitle = toolbar.getSubtitle();

        // Temporarily modify title and subtitle to help detecting each
        toolbar.setTitle("title");
        toolbar.setSubtitle("subtitle");

        for(int i = 0; i < toolbar.getChildCount(); i++){
            View view = toolbar.getChildAt(i);

            if(view instanceof TextView){
                TextView textView = (TextView) view;


                if(textView.getText().equals("title")){
                    // Customize title's TextView
                    Toolbar.LayoutParams params = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.MATCH_PARENT);
                    params.gravity = Gravity.CENTER_HORIZONTAL;
                    textView.setLayoutParams(params);

                    // Apply custom font using the Calligraphy library
                    Typeface typeface = TypefaceUtils.load(getAssets(), "fonts/myfont-1.otf");
                    textView.setTypeface(typeface);

                } else if(textView.getText().equals("subtitle")){
                    // Customize subtitle's TextView
                    Toolbar.LayoutParams params = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.MATCH_PARENT);
                    params.gravity = Gravity.CENTER_HORIZONTAL;
                    textView.setLayoutParams(params);

                    // Apply custom font using the Calligraphy library
                    Typeface typeface = TypefaceUtils.load(getAssets(), "fonts/myfont-2.otf");
                    textView.setTypeface(typeface);
                }
            }
        }

        // Restore title and subtitle
        toolbar.setTitle(originalTitle);
        toolbar.setSubtitle(originalSubtitle);
    }
}

Transfer data from one HTML file to another

The old fashioned way of setting a global variable that persist between pages is to set the data in a Cookie. The modern way is to use Local Storage, which has a good browser support (IE8+, Firefox 3.5+, Chrome 4+, Android 2+, iPhone 2+). Using localStorage is as easy as using an array:

localStorage["key"] = value;

... in another page ...
value = localStorage["key"];

You can also attach event handlers to listen for changes, though the event API is slightly different between browsers. More on the topic.

Dynamically set value of a file input

I am working on an angular js app, andhavecome across a similar issue. What i did was display the image from the db, then created a button to remove or keep the current image. If the user decided to keep the current image, i changed the ng-submit attribute to another function whihc doesnt require image validation, and updated the record in the db without touching the original image path name. The remove image function also changed the ng-submit attribute value back to a function that submits the form and includes image validation and upload. Also a bit of javascript to slide the into view to upload a new image.

Adding and reading from a Config file

  1. Right click on the project file -> Add -> New Item -> Application Configuration File. This will add an app.config (or web.config) file to your project.

  2. The ConfigurationManager class would be a good start. You can use it to read different configuration values from the configuration file.

I suggest you start reading the MSDN document about Configuration Files.

How can you search Google Programmatically Java API

Some facts:

  1. Google offers a public search webservice API which returns JSON: http://ajax.googleapis.com/ajax/services/search/web. Documentation here

  2. Java offers java.net.URL and java.net.URLConnection to fire and handle HTTP requests.

  3. JSON can in Java be converted to a fullworthy Javabean object using an arbitrary Java JSON API. One of the best is Google Gson.

Now do the math:

public static void main(String[] args) throws Exception {
    String google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
    String search = "stackoverflow";
    String charset = "UTF-8";
    
    URL url = new URL(google + URLEncoder.encode(search, charset));
    Reader reader = new InputStreamReader(url.openStream(), charset);
    GoogleResults results = new Gson().fromJson(reader, GoogleResults.class);
    
    // Show title and URL of 1st result.
    System.out.println(results.getResponseData().getResults().get(0).getTitle());
    System.out.println(results.getResponseData().getResults().get(0).getUrl());
}

With this Javabean class representing the most important JSON data as returned by Google (it actually returns more data, but it's left up to you as an exercise to expand this Javabean code accordingly):

public class GoogleResults {

    private ResponseData responseData;
    public ResponseData getResponseData() { return responseData; }
    public void setResponseData(ResponseData responseData) { this.responseData = responseData; }
    public String toString() { return "ResponseData[" + responseData + "]"; }

    static class ResponseData {
        private List<Result> results;
        public List<Result> getResults() { return results; }
        public void setResults(List<Result> results) { this.results = results; }
        public String toString() { return "Results[" + results + "]"; }
    }

    static class Result {
        private String url;
        private String title;
        public String getUrl() { return url; }
        public String getTitle() { return title; }
        public void setUrl(String url) { this.url = url; }
        public void setTitle(String title) { this.title = title; }
        public String toString() { return "Result[url:" + url +",title:" + title + "]"; }
    }

}

###See also:


Update since November 2010 (2 months after the above answer), the public search webservice has become deprecated (and the last day on which the service was offered was September 29, 2014). Your best bet is now querying http://www.google.com/search directly along with a honest user agent and then parse the result using a HTML parser. If you omit the user agent, then you get a 403 back. If you're lying in the user agent and simulate a web browser (e.g. Chrome or Firefox), then you get a way much larger HTML response back which is a waste of bandwidth and performance.

Here's a kickoff example using Jsoup as HTML parser:

String google = "http://www.google.com/search?q=";
String search = "stackoverflow";
String charset = "UTF-8";
String userAgent = "ExampleBot 1.0 (+http://example.com/bot)"; // Change this to your company's name and bot homepage!

Elements links = Jsoup.connect(google + URLEncoder.encode(search, charset)).userAgent(userAgent).get().select(".g>.r>a");

for (Element link : links) {
    String title = link.text();
    String url = link.absUrl("href"); // Google returns URLs in format "http://www.google.com/url?q=<url>&sa=U&ei=<someKey>".
    url = URLDecoder.decode(url.substring(url.indexOf('=') + 1, url.indexOf('&')), "UTF-8");
    
    if (!url.startsWith("http")) {
        continue; // Ads/news/etc.
    }
    
    System.out.println("Title: " + title);
    System.out.println("URL: " + url);
}

Variables declared outside function

When Python parses a function, it notes when a variable assignment is made. When there is an assignment, it assumes by default that that variable is a local variable. To declare that the assignment refers to a global variable, you must use the global declaration.

When you access a variable in a function, its value is looked up using the LEGB scoping rules.


So, the first example

  x = 1
  def inc():
      x += 5
  inc()

produces an UnboundLocalError because Python determined x inside inc to be a local variable,

while accessing x works in your second example

 def inc():
    print x

because here, in accordance with the LEGB rule, Python looks for x in the local scope, does not find it, then looks for it in the extended scope, still does not find it, and finally looks for it in the global scope successfully.

Fast and simple String encrypt/decrypt in JAVA

Simplest way is to add this JAVA library using Gradle:

compile 'se.simbio.encryption:library:2.0.0'

You can use it as simple as this:

Encryption encryption = Encryption.getDefault("Key", "Salt", new byte[16]);
String encrypted = encryption.encryptOrNull("top secret string");
String decrypted = encryption.decryptOrNull(encrypted);

count (non-blank) lines-of-code in bash

Here's a Bash script that counts the lines of code in a project. It traverses a source tree recursively, and it excludes blank lines and single line comments that use "//".

# $excluded is a regex for paths to exclude from line counting
excluded="spec\|node_modules\|README\|lib\|docs\|csv\|XLS\|json\|png"

countLines(){
  # $total is the total lines of code counted
  total=0
  # -mindepth exclues the current directory (".")
  for file in `find . -mindepth 1 -name "*.*" |grep -v "$excluded"`; do
    # First sed: only count lines of code that are not commented with //
    # Second sed: don't count blank lines
    # $numLines is the lines of code
    numLines=`cat $file | sed '/\/\//d' | sed '/^\s*$/d' | wc -l`

    # To exclude only blank lines and count comment lines, uncomment this:
    #numLines=`cat $file | sed '/^\s*$/d' | wc -l`

    total=$(($total + $numLines))
    echo "  " $numLines $file
  done
  echo "  " $total in total
}

echo Source code files:
countLines
echo Unit tests:
cd spec
countLines

Here's what the output looks like for my project:

Source code files:
   2 ./buildDocs.sh
   24 ./countLines.sh
   15 ./css/dashboard.css
   53 ./data/un_population/provenance/preprocess.js
   19 ./index.html
   5 ./server/server.js
   2 ./server/startServer.sh
   24 ./SpecRunner.html
   34 ./src/computeLayout.js
   60 ./src/configDiff.js
   18 ./src/dashboardMirror.js
   37 ./src/dashboardScaffold.js
   14 ./src/data.js
   68 ./src/dummyVis.js
   27 ./src/layout.js
   28 ./src/links.js
   5 ./src/main.js
   52 ./src/processActions.js
   86 ./src/timeline.js
   73 ./src/udc.js
   18 ./src/wire.js
   664 in total
Unit tests:
   230 ./ComputeLayoutSpec.js
   134 ./ConfigDiffSpec.js
   134 ./ProcessActionsSpec.js
   84 ./UDCSpec.js
   149 ./WireSpec.js
   731 in total

Enjoy! --Curran

How to connect to a MS Access file (mdb) using C#?

What Access File extension or you using? The Jet OLEDB or the Ace OLEDB. If your Access DB is .mdb (aka Jet Oledb)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Oledb

namespace MembershipInformationSystem.Helpers
{
    public class dbs
    {
        private String connectionString;
        private String OleDBProvider = "Microsoft.JET.OLEDB.4.0"; \\if ACE Microsoft.ACE.OLEDB.12.0
        private String OleDBDataSource = "C:\\yourdb.mdb";
        private String OleDBPassword = "infosys";
        private String PersistSecurityInfo = "False";

        public dbs()
        {

        }

        public dbs(String connectionString)
        {
            this.connectionString = connectionString;
        }

        public String konek()
        {
            connectionString = "Provider=" + OleDBProvider + ";Data Source=" + OleDBDataSource + ";JET OLEDB:Database Password=" + OleDBPassword + ";Persist Security Info=" + PersistSecurityInfo + "";
            return connectionString;
        }
    }
}

Second line in li starts under the bullet after CSS-reset

The li tag has a property called list-style-position. This makes your bullets inside or outside the list. On default, it’s set to inside. That makes your text wrap around it. If you set it to outside, the text of your li tags will be aligned.

The downside of that is that your bullets won't be aligned with the text outside the ul. If you want to align it with the other text you can use a margin.

ul li {
    /*
     * We want the bullets outside of the list,
     * so the text is aligned. Now the actual bullet
     * is outside of the list’s container
     */
    list-style-position: outside;

    /*
     * Because the bullet is outside of the list’s
     * container, indent the list entirely
     */
    margin-left: 1em;
}

Edit 15th of March, 2014 Seeing people are still coming in from Google, I felt like the original answer could use some improvement

  • Changed the code block to provide just the solution
  • Changed the indentation unit to em’s
  • Each property is applied to the ul element
  • Good comments :)

HTTP could not register URL http://+:8000/HelloWCF/. Your process does not have access rights to this namespace

Right Click on Visual Studio > Run as Administrator > Open your project and run the service. This is a privilege related issue.

5.7.57 SMTP - Client was not authenticated to send anonymous mail during MAIL FROM error

In my case I was using the MailMessage constructor that takes two strings (to, from) and getting the same error. When I used the default constructor and then added a MailAddress object to the To property of the MailMessage it worked fine.

How can I convert a string to an int in Python?

Since you're writing a calculator that would presumably also accept floats (1.5, 0.03), a more robust way would be to use this simple helper function:

def convertStr(s):
    """Convert string to either int or float."""
    try:
        ret = int(s)
    except ValueError:
        #Try float.
        ret = float(s)
    return ret

That way if the int conversion doesn't work, you'll get a float returned.

Edit: Your division function might also result in some sad faces if you aren't fully aware of how python 2.x handles integer division.

In short, if you want 10/2 to equal 2.5 and not 2, you'll need to do from __future__ import division or cast one or both of the arguments to float, like so:

def division(a, b):
    return float(a) / float(b)

How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?

If you have an Order class, adding a property that references another class in your model, for instance Customer should be enough to let EF know there's a relationship in there:

public class Order
{
    public int ID { get; set; }

    // Some other properties

    // Foreign key to customer
    public virtual Customer Customer { get; set; }
}

You can always set the FK relation explicitly:

public class Order
{
    public int ID { get; set; }

    // Some other properties

    // Foreign key to customer
    [ForeignKey("Customer")]
    public string CustomerID { get; set; }
    public virtual Customer Customer { get; set; }
}

The ForeignKeyAttribute constructor takes a string as a parameter: if you place it on a foreign key property it represents the name of the associated navigation property. If you place it on the navigation property it represents the name of the associated foreign key.

What this means is, if you where to place the ForeignKeyAttribute on the Customer property, the attribute would take CustomerID in the constructor:

public string CustomerID { get; set; }
[ForeignKey("CustomerID")]
public virtual Customer Customer { get; set; }

EDIT based on Latest Code You get that error because of this line:

[ForeignKey("Parent")]
public Patient Patient { get; set; }

EF will look for a property called Parent to use it as the Foreign Key enforcer. You can do 2 things:

1) Remove the ForeignKeyAttribute and replace it with the RequiredAttribute to mark the relation as required:

[Required]
public virtual Patient Patient { get; set; }

Decorating a property with the RequiredAttribute also has a nice side effect: The relation in the database is created with ON DELETE CASCADE.

I would also recommend making the property virtual to enable Lazy Loading.

2) Create a property called Parent that will serve as a Foreign Key. In that case it probably makes more sense to call it for instance ParentID (you'll need to change the name in the ForeignKeyAttribute as well):

public int ParentID { get; set; }

In my experience in this case though it works better to have it the other way around:

[ForeignKey("Patient")]
public int ParentID { get; set; }

public virtual Patient Patient { get; set; }

How do I access refs of a child component in the parent component

Using Ref forwarding you can pass the ref from parent to further down to a child.

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
  1. Create a React ref by calling React.createRef and assign it to a ref variable.
  2. Pass your ref down to by specifying it as a JSX attribute.
  3. React passes the ref to the (props, ref) => ... function inside forwardRef as a second argument.
  4. Forward this ref argument down to by specifying it as a JSX attribute.
  5. When the ref is attached, ref.current will point to the DOM node.

Note The second ref argument only exists when you define a component with React.forwardRef call. Regular functional or class components don’t receive the ref argument, and ref is not available in props either.

Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too.

Reference: React Documentation.

Disabling of EditText in Android

Try this one, works fine for me:

public class CustomEdittext extends EditText {

Boolean mIsTextEditor=true;
public CustomEdittext(Context context, AttributeSet attrs) {
    super(context, attrs);
    // TODO Auto-generated constructor stub
}

@Override
public boolean onCheckIsTextEditor() {
    // TODO Auto-generated method stub
    return mIsTextEditor;
}


@Override
public boolean onTouchEvent(MotionEvent event) {
    // TODO Auto-generated method stub
    mIsTextEditor=false;
    Boolean mOnTouchEvent=super.onTouchEvent(event);
    mIsTextEditor=true;     
    return mOnTouchEvent;
} }

Note: You need to add this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); on your activity or else keyboard will popup at first time.

How to create a simple checkbox in iOS?

On iOS there is the switch UI component instead of a checkbox, look into the UISwitch class. The property on (boolean) can be used to determine the state of the slider and about the saving of its state: That depends on how you save your other stuff already, its just saving a boolean value.

Vue template or render function not defined yet I am using neither?

As a Summary of all the posts

This error:

[Vue warn]: Failed to mount component: template or render function not defined.

You're getting because of a certain problem that's preventing your component from being mounted.

This can be caused by a lot of different issues, as you can see from the different posts here. Debug your component thoroughly, and be aware of everything that is maybe not done correctly and might prevent the mount.

I was getting the error when my component file was not encoded correctly...

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));

Difference between java.lang.RuntimeException and java.lang.Exception

The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time checking, since the compiler cannot establish that run-time exceptions cannot occur. (from JLS).

In the classes that you design you should subclass Exception and throw instances of it to signal any exceptional scenarios. Doing so you will be explicitly signaling the clients of your class that usage of your class might throw exception and they have to take steps to handle those exceptional scenarios.

Below code snippets explain this point:

//Create your own exception class subclassing from Exception
class MyException extends Exception {
    public MyException(final String message) {
        super(message);
    }
}

public class Process {
    public void execute() {
        throw new RuntimeException("Runtime");
    }  
    public void process() throws MyException {
        throw new MyException("Checked");
    }
}

In the above class definition of class Process, the method execute can throw a RuntimeException but the method declaration need not specify that it throws RuntimeException.

The method process throws a checked exception and it should declare that it will throw a checked exception of kind MyException and not doing so will be a compile error.

The above class definition will affect the code that uses Process class as well.

The call new Process().execute() is a valid invocation where as the call of form new Process().process() gives a compile error. This is because the client code should take steps to handle MyException (say call to process() can be enclosed in a try/catch block).

How do you push a Git tag to a branch using a refspec?

I create the tag like this and then I push it to GitHub:

git tag -a v1.1 -m "Version 1.1 is waiting for review"
git push --tags

Counting objects: 1, done.
Writing objects: 100% (1/1), 180 bytes, done.
Total 1 (delta 0), reused 0 (delta 0)
To [email protected]:neoneye/triangle_draw.git
 * [new tag]         v1.1 -> v1.1

android.app.Application cannot be cast to android.app.Activity

You are getting this error because the parameter required is Activity and you are passing it the Application. So, either you cast application to the Activity like: (Activity)getApplicationContext(); Or you can just type the Activity like: MyActivity.this

Excel compare two columns and highlight duplicates

The easiest way to do it, at least for me, is:

Conditional format-> Add new rule->Set your own formula:

=ISNA(MATCH(A2;$B:$B;0))

Where A2 is the first element in column A to be compared and B is the column where A's element will be searched.

Once you have set the formula and picked the format, apply this rule to all elements in the column.

Hope this helps

jQuery - how to write 'if not equal to' (opposite of ==)

== => !=

=== => !==

Equal and its opposite

How to delete mysql database through shell command

In general, you can pass any query to mysql from shell with -e option.

mysql -u username -p -D dbname -e "DROP DATABASE dbname"

How do I update/upsert a document in Mongoose?

You were close with

Contact.update({phone:request.phone}, contact, {upsert: true}, function(err){...})

but your second parameter should be an object with a modification operator for example

Contact.update({phone:request.phone}, {$set: { phone: request.phone }}, {upsert: true}, function(err){...})

Array as session variable

session_start();          //php part
$_SESSION['student']=array();
$student_name=$_POST['student_name']; //student_name form field name
$student_city=$_POST['city_id'];   //city_id form field name
array_push($_SESSION['student'],$student_name,$student_city);   
//print_r($_SESSION['student']);


<table class="table">     //html part
    <tr>
      <th>Name</th>
      <th>City</th>
    </tr>

    <tr>
     <?php for($i = 0 ; $i < count($_SESSION['student']) ; $i++) {
     echo '<td>'.$_SESSION['student'][$i].'</td>';
     }  ?>
    </tr>
</table>

How to copy java.util.list Collection

Use the ArrayList copy constructor, then sort that.

List oldList;
List newList = new ArrayList(oldList);
Collections.sort(newList);

After making the copy, any changes to newList do not affect oldList.

Note however that only the references are copied, so the two lists share the same objects, so changes made to elements of one list affect the elements of the other.

Error: Argument is not a function, got undefined

There appear to be many working solutions suggesting the error has many actual causes.

In my case I hadn't declared the controller in app/index.html:

<scipt src="src/controllers/controller-name.controller.js"></script>

Error gone.

How to run Linux commands in Java?

You can call run-time commands from java for both Windows and Linux.

import java.io.*;

public class Test{
   public static void main(String[] args) 
   {
            try
            { 
            Process process = Runtime.getRuntime().exec("pwd"); // for Linux
            //Process process = Runtime.getRuntime().exec("cmd /c dir"); //for Windows

            process.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
               while ((line=reader.readLine())!=null)
               {
                System.out.println(line);   
                }
             }       
                catch(Exception e)
             { 
                 System.out.println(e); 
             }
             finally
             {
               process.destroy();
             }  
    }
}

Hope it Helps.. :)

What's the @ in front of a string in C#?

It's a verbatim string literal. It means that escaping isn't applied. For instance:

string verbatim = @"foo\bar";
string regular = "foo\\bar";

Here verbatim and regular have the same contents.

It also allows multi-line contents - which can be very handy for SQL:

string select = @"
SELECT Foo
FROM Bar
WHERE Name='Baz'";

The one bit of escaping which is necessary for verbatim string literals is to get a double quote (") which you do by doubling it:

string verbatim = @"He said, ""Would you like some coffee?"" and left.";
string regular = "He said, \"Would you like some coffee?\" and left.";

Bound method error

The syntax problem is shadowing method and variable names. In the current version sort_word_list() is a method, and sorted_word_list is a variable, whereas num_words is both. Also, list.sort() modifies the list and replaces it with a sorted version; the sorted(list) function actually returns a new list.

But I suspect this indicates a design problem. What's the point of calls like

test.parser()
test.sort_word_list()
test.num_words()

which don't do anything? You should probably just have the methods figure out whether the appropriate counting and/or sorting has been done, and, if appropriate, do the count or sort and otherwise just return something.

E.G.,

def sort_word_list(self):
   if self.sorted_word_list is not None:
      self.sorted_word_list = sorted(self.word_list)
   return self.sorted_word_list

(Alternately, you could use properties.)

find if an integer exists in a list of integers

As long as your list is initialized with values and that value actually exists in the list, then Contains should return true.

I tried the following:

var list = new List<int> {1,2,3,4,5};
var intVar = 4;
var exists = list.Contains(intVar);

And exists is indeed set to true.

No 'Access-Control-Allow-Origin' header in Angular 2 app

You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/.

Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS request. So the error comes from the fact that the preflight request doesn't produce the necessary headers. check that you will need to add following in your .htaccess file:

Header set Access-Control-Allow-Origin "*"

React component initialize state from props

you could use key value to reset state when need, pass props to state it's not a good practice , because you have uncontrolled and controlled component in one place. Data should be in one place handled read this https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key

Is there an easy way to return a string repeated X number of times?

Surprised nobody went old-school. I am not making any claims about this code, but just for fun:

public static string Repeat(this string @this, int count)
{
    var dest = new char[@this.Length * count];
    for (int i = 0; i < dest.Length; i += 1)
    {
        dest[i] = @this[i % @this.Length];
    }
    return new string(dest);
}

setting y-axis limit in matplotlib

You can instantiate an object from matplotlib.pyplot.axes and call the set_ylim() on it. It would be something like this:

import matplotlib.pyplot as plt
axes = plt.axes()
axes.set_ylim([0, 1])

How to redirect user's browser URL to a different page in Nodejs?

response.writeHead(301,
  {Location: 'http://whateverhostthiswillbe:8675/'+newRoom}
);
response.end();

How to convert an entire MySQL database characterset and collation to UTF-8?

  1. Make a backup!

  2. Then you need to set the default char sets on the database. This does not convert existing tables, it only sets the default for newly created tables.

    ALTER DATABASE dbname CHARACTER SET utf8 COLLATE utf8_general_ci;
    
  3. Then, you will need to convert the char set on all existing tables and their columns. This assumes that your current data is actually in the current char set. If your columns are set to one char set but your data is really stored in another then you will need to check the MySQL manual on how to handle this.

    ALTER TABLE tbl_name CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
    

JQuery - $ is not defined

I had this problem once for no apparent reason. It was happenning locally whilst I was running through the aspnet development server. It had been working and I reverted everything to a state where it had previously been working and still it didn't work. I looked in the chrome debugger and the jquery-1.7.1.min.js had loaded without any problems. It was all very confusing. I still don't know what the problem was but closing the browser, closing the development server and then trying again sorted it out.

What is the right way to POST multipart/form-data using curl?

to upload a file using curl in Windows I found that the path requires escaped double quotes

e.g.

curl -v -F 'upload=@\"C:/myfile.txt\"' URL

How to access global js variable in AngularJS directive

I created a working CodePen example demonstrating how to do this the correct way in AngularJS. The Angular $window service should be used to access any global objects since directly accessing window makes testing more difficult.

HTML:

<section ng-app="myapp" ng-controller="MainCtrl">
  Value of global variable read by AngularJS: {{variable1}}
</section>

JavaScript:

// global variable outside angular
var variable1 = true;

var app = angular.module('myapp', []);

app.controller('MainCtrl', ['$scope', '$window', function($scope, $window) {
  $scope.variable1 = $window.variable1;
}]);

Partition Function COUNT() OVER possible using DISTINCT

I think the only way of doing this in SQL-Server 2008R2 is to use a correlated subquery, or an outer apply:

SELECT  datekey,
        COALESCE(RunningTotal, 0) AS RunningTotal,
        COALESCE(RunningCount, 0) AS RunningCount,
        COALESCE(RunningDistinctCount, 0) AS RunningDistinctCount
FROM    document
        OUTER APPLY
        (   SELECT  SUM(Amount) AS RunningTotal,
                    COUNT(1) AS RunningCount,
                    COUNT(DISTINCT d2.dateKey) AS RunningDistinctCount
            FROM    Document d2
            WHERE   d2.DateKey <= document.DateKey
        ) rt;

This can be done in SQL-Server 2012 using the syntax you have suggested:

SELECT  datekey,
        SUM(Amount) OVER(ORDER BY DateKey) AS RunningTotal
FROM    document

However, use of DISTINCT is still not allowed, so if DISTINCT is required and/or if upgrading isn't an option then I think OUTER APPLY is your best option

jQuery check/uncheck radio button onclick

This function will add a check/unchecked to all radiobuttons

jQuery(document).ready(function(){
jQuery(':radio').click(function()
{
if ((jQuery(this).attr('checked') == 'checked') && (jQuery(this).attr('class') == 'checked'))
{   
    jQuery(this).attr('class','unchecked');
    jQuery(this).removeAttr('checked');
} else {
jQuery(this).attr('class','checked');
}//or any element you want

});
});

Best practice for localization and globalization of strings and labels

When you’re faced with a problem to solve (and frankly, who isn’t these days?), the basic strategy usually taken by we computer people is called “divide and conquer.” It goes like this:

  • Conceptualize the specific problem as a set of smaller sub-problems.
  • Solve each smaller problem.
  • Combine the results into a solution of the specific problem.

But “divide and conquer” is not the only possible strategy. We can also take a more generalist approach:

  • Conceptualize the specific problem as a special case of a more general problem.
  • Somehow solve the general problem.
  • Adapt the solution of the general problem to the specific problem.

- Eric Lippert

I believe many solutions already exist for this problem in server-side languages such as ASP.Net/C#.

I've outlined some of the major aspects of the problem

  • Issue: We need to load data only for the desired language

    Solution: For this purpose we save data to a separate files for each language

ex. res.de.js, res.fr.js, res.en.js, res.js(for default language)

  • Issue: Resource files for each page should be separated so we only get the data we need

    Solution: We can use some tools that already exist like https://github.com/rgrove/lazyload

  • Issue: We need a key/value pair structure to save our data

    Solution: I suggest a javascript object instead of string/string air. We can benefit from the intellisense from an IDE

  • Issue: General members should be stored in a public file and all pages should access them

    Solution: For this purpose I make a folder in the root of web application called Global_Resources and a folder to store global file for each sub folders we named it 'Local_Resources'

  • Issue: Each subsystems/subfolders/modules member should override the Global_Resources members on their scope

    Solution: I considered a file for each

Application Structure

root/
    Global_Resources/
        default.js
        default.fr.js
    UserManagementSystem/
        Local_Resources/
            default.js
            default.fr.js
            createUser.js
        Login.htm
        CreateUser.htm

The corresponding code for the files:

Global_Resources/default.js

var res = {
    Create : "Create",
    Update : "Save Changes",
    Delete : "Delete"
};

Global_Resources/default.fr.js

var res = {
    Create : "créer",
    Update : "Enregistrer les modifications",
    Delete : "effacer"
};

The resource file for the desired language should be loaded on the page selected from Global_Resource - This should be the first file that is loaded on all the pages.

UserManagementSystem/Local_Resources/default.js

res.Name = "Name";
res.UserName = "UserName";
res.Password = "Password";

UserManagementSystem/Local_Resources/default.fr.js

res.Name = "nom";
res.UserName = "Nom d'utilisateur";
res.Password = "Mot de passe";

UserManagementSystem/Local_Resources/createUser.js

// Override res.Create on Global_Resources/default.js
res.Create = "Create User"; 

UserManagementSystem/Local_Resources/createUser.fr.js

// Override Global_Resources/default.fr.js
res.Create = "Créer un utilisateur";

manager.js file (this file should be load last)

res.lang = "fr";

var globalResourcePath = "Global_Resources";
var resourceFiles = [];

var currentFile = globalResourcePath + "\\default" + res.lang + ".js" ;

if(!IsFileExist(currentFile))
    currentFile = globalResourcePath + "\\default.js" ;
if(!IsFileExist(currentFile)) throw new Exception("File Not Found");

resourceFiles.push(currentFile);

// Push parent folder on folder into folder
foreach(var folder in parent folder of current page)
{
    currentFile = folder + "\\Local_Resource\\default." + res.lang + ".js";

    if(!IsExist(currentFile))
        currentFile = folder + "\\Local_Resource\\default.js";
    if(!IsExist(currentFile)) throw new Exception("File Not Found");

    resourceFiles.push(currentFile);
}

for(int i = 0; i < resourceFiles.length; i++) { Load.js(resourceFiles[i]); }

// Get current page name
var pageNameWithoutExtension = "SomePage";

currentFile = currentPageFolderPath + pageNameWithoutExtension + res.lang + ".js" ;

if(!IsExist(currentFile))
    currentFile = currentPageFolderPath + pageNameWithoutExtension + ".js" ;
if(!IsExist(currentFile)) throw new Exception("File Not Found");

Hope it helps :)

How to manually reload Google Map with JavaScript

map.setZoom(map.getZoom());

For some reasons, resize trigger did not work for me, and this one worked.

Why is <deny users="?" /> included in the following example?

"At run time, the authorization module iterates through the allow and deny elements, starting at the most local configuration file, until the authorization module finds the first access rule that fits a particular user account. Then, the authorization module grants or denies access to a URL resource depending on whether the first access rule found is an allow or a deny rule. The default authorization rule is . Thus, by default, access is allowed unless configured otherwise."

Article at MSDN

deny = * means deny everyone
deny = ? means deny unauthenticated users

In your 1st example deny * will not affect dan, matthew since they were already allowed by the preceding rule.

According to the docs, here is no difference in your 2 rule sets.

Enable 'xp_cmdshell' SQL Server

For me, the only way on SQL 2008 R2 was this :

EXEC sp_configure 'Show Advanced Options', 1    
RECONFIGURE **WITH OVERRIDE**    
EXEC sp_configure 'xp_cmdshell', 1    
RECONFIGURE **WITH OVERRIDE**

SQL UPDATE all values in a field with appended string CONCAT not working

Solved it. Turns out the column had a limited set of characters it would accept, changed it, and now the query works fine.

HTML5 Canvas 100% Width Height of Viewport?

I'll answer the more general question of how to have a canvas dynamically adapt in size upon window resize. The accepted answer appropriately handles the case where width and height are both supposed to be 100%, which is what was asked for, but which also will change the aspect ratio of the canvas. Many users will want the canvas to resize on window resize, but while keeping the aspect ratio untouched. It's not the exact question, but it "fits in", just putting the question into a slightly more general context.

The window will have some aspect ratio (width / height), and so will the canvas object. How you want these two aspect ratios to relate to each other is one thing you'll have to be clear about, there is no "one size fits all" answer to that question - I'll go through some common cases of what you might want.

Most important thing you have to be clear about: the html canvas object has a width attribute and a height attribute; and then, the css of the same object also has a width and a height attribute. Those two widths and heights are different, both are useful for different things.

Changing the width and height attributes is one method with which you can always change the size of your canvas, but then you'll have to repaint everything, which will take time and is not always necessary, because some amount of size change you can accomplish via the css attributes, in which case you do not redraw the canvas.

I see 4 cases of what you might want to happen on window resize (all starting with a full screen canvas)

1: you want the width to remain 100%, and you want the aspect ratio to stay as it was. In that case, you do not need to redraw the canvas; you don't even need a window resize handler. All you need is

$(ctx.canvas).css("width", "100%");

where ctx is your canvas context. fiddle: resizeByWidth

2: you want width and height to both stay 100%, and you want the resulting change in aspect ratio to have the effect of a stretched-out image. Now, you still don't need to redraw the canvas, but you need a window resize handler. In the handler, you do

$(ctx.canvas).css("height", window.innerHeight);

fiddle: messWithAspectratio

3: you want width and height to both stay 100%, but the answer to the change in aspect ratio is something different from stretching the image. Then you need to redraw, and do it the way that is outlined in the accepted answer.

fiddle: redraw

4: you want the width and height to be 100% on page load, but stay constant thereafter (no reaction to window resize.

fiddle: fixed

All fiddles have identical code, except for line 63 where the mode is set. You can also copy the fiddle code to run on your local machine, in which case you can select the mode via a querystring argument, as ?mode=redraw

How to include SCSS file in HTML

You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...

For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.

Subprocess check_output returned non-zero exit status 1

The word check_ in the name means that if the command (the shell in this case that returns the exit status of the last command (yum in this case)) returns non-zero status then it raises CalledProcessError exception. It is by design. If the command that you want to run may return non-zero status on success then either catch this exception or don't use check_ methods. You could use subprocess.call in your case because you are ignoring the captured output, e.g.:

import subprocess

rc = subprocess.call(['grep', 'pattern', 'file'],
                     stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
if rc == 0: # found
   ...
elif rc == 1: # not found
   ...
elif rc > 1: # error
   ...

You don't need shell=True to run the commands from your question.

How do I mock a service that returns promise in AngularJS Jasmine unit test?

I found that useful, stabbing service function as sinon.stub().returns($q.when({})):

this.myService = {
   myFunction: sinon.stub().returns( $q.when( {} ) )
};

this.scope = $rootScope.$new();
this.angularStubs = {
    myService: this.myService,
    $scope: this.scope
};
this.ctrl = $controller( require( 'app/bla/bla.controller' ), this.angularStubs );

controller:

this.someMethod = function(someObj) {
   myService.myFunction( someObj ).then( function() {
        someObj.loaded = 'bla-bla';
   }, function() {
        // failure
   } );   
};

and test

const obj = {
    field: 'value'
};
this.ctrl.someMethod( obj );

this.scope.$digest();

expect( this.myService.myFunction ).toHaveBeenCalled();
expect( obj.loaded ).toEqual( 'bla-bla' );

What's the whole point of "localhost", hosts and ports at all?

Port: In simple language, "Port" is a number used by a particular software to identify its data coming from internet.

Each software, like Skype, Chrome, Youtube has its own port number and that's how they know which internet data is for itself.

Socket: "IP address and Port " together is called "Socket". It is used by another computer to send data to one particular computer's particular software.

IP address is used to identify the computer and Port is to identify the software such as IE, Chrome, Skype etc.

In every home, there is one mailbox and multiple people. The mailbox is a host. Your own home mailbox is a localhost. Each person in a home has a room. All letters for that person are sent to his room, hence the room number is a port.

Build not visible in itunes connect

I want to share my expereince, I uploaded my build by application uploader and xcode and after 10 hours i couldn't see any build on the itunes connect. Finally I contacted apple and they explained that a build validation can take 24 hours maximum. After 24 hours, if the build is not visible on the related page, they advise to upload a newer version. And if after the second 24 hours if there is still not any build, you can call apple developper program assistance. Here is the page where you can find phone numbers :

https://developer.apple.com/contact/phone/

Publishing the first version of your application can takes a few days but a newer version takes much less time.

How to send authorization header with axios

On non-simple http requests your browser will send a "preflight" request (an OPTIONS method request) first in order to determine what the site in question considers safe information to send (see here for the cross-origin policy spec about this). One of the relevant headers that the host can set in a preflight response is Access-Control-Allow-Headers. If any of the headers you want to send were not listed in either the spec's list of whitelisted headers or the server's preflight response, then the browser will refuse to send your request.

In your case, you're trying to send an Authorization header, which is not considered one of the universally safe to send headers. The browser then sends a preflight request to ask the server whether it should send that header. The server is either sending an empty Access-Control-Allow-Headers header (which is considered to mean "don't allow any extra headers") or it's sending a header which doesn't include Authorization in its list of allowed headers. Because of this, the browser is not going to send your request and instead chooses to notify you by throwing an error.

Any Javascript workaround you find that lets you send this request anyways should be considered a bug as it is against the cross origin request policy your browser is trying to enforce for your own safety.

tl;dr - If you'd like to send Authorization headers, your server had better be configured to allow it. Set your server up so it responds to an OPTIONS request at that url with an Access-Control-Allow-Headers: Authorization header.

git pull fails "unable to resolve reference" "unable to update local ref"

If git gc --prune=now dosen't help you. (bad luck like me)

What I did is remove the project in local, and re clone the whole project again.

how to cancel/abort ajax request in axios

Using cp-axios wrapper you able to abort your requests with three diffent types of the cancellation API:

1. Promise cancallation API (CPromise):

Live browser example

 const cpAxios= require('cp-axios');
 const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
 
 const chain = cpAxios(url)
      .timeout(5000)
      .then(response=> {
          console.log(`Done: ${JSON.stringify(response.data)}`)
      }, err => {
          console.warn(`Request failed: ${err}`)
      });
 
 setTimeout(() => {
    chain.cancel();
 }, 500);

2. Using AbortController signal API:

 const cpAxios= require('cp-axios');
 const CPromise= require('c-promise2');
 const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
 
 const abortController = new CPromise.AbortController();
 const {signal} = abortController;
 
 const chain = cpAxios(url, {signal})
      .timeout(5000)
      .then(response=> {
          console.log(`Done: ${JSON.stringify(response.data)}`)
      }, err => {
          console.warn(`Request failed: ${err}`)
      });
 
 setTimeout(() => {
    abortController.abort();
 }, 500);

3. Using a plain axios cancelToken:

 const cpAxios= require('cp-axios');
 const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';

 const source = cpAxios.CancelToken.source();
 
 cpAxios(url, {cancelToken: source.token})
      .timeout(5000)
      .then(response=> {
          console.log(`Done: ${JSON.stringify(response.data)}`)
      }, err => {
          console.warn(`Request failed: ${err}`)
      });
 
 setTimeout(() => {
    source.cancel();
 }, 500);

I keep getting "Uncaught SyntaxError: Unexpected token o"

Basically if the response header is text/html you need to parse, and if the response header is application/json it is already parsed for you.

Parsed data from jquery success handler for text/html response:

var parsed = JSON.parse(data);

Parsed data from jquery success handler for application/json response:

var parsed = data;

Return index of highest value in an array

Something like this should do the trick

function array_max_key($array) {
  $max_key = -1;
  $max_val = -1;

  foreach ($array as $key => $value) {
    if ($value > $max_val) {
      $max_key = $key;
      $max_val = $value;
    }
  }

  return $max_key;
}

Writing Unicode text to a text file?

Preface: will your viewer work?

Make sure your viewer/editor/terminal (however you are interacting with your utf-8 encoded file) can read the file. This is frequently an issue on Windows, for example, Notepad.

Writing Unicode text to a text file?

In Python 2, use open from the io module (this is the same as the builtin open in Python 3):

import io

Best practice, in general, use UTF-8 for writing to files (we don't even have to worry about byte-order with utf-8).

encoding = 'utf-8'

utf-8 is the most modern and universally usable encoding - it works in all web browsers, most text-editors (see your settings if you have issues) and most terminals/shells.

On Windows, you might try utf-16le if you're limited to viewing output in Notepad (or another limited viewer).

encoding = 'utf-16le' # sorry, Windows users... :(

And just open it with the context manager and write your unicode characters out:

with io.open(filename, 'w', encoding=encoding) as f:
    f.write(unicode_object)

Example using many Unicode characters

Here's an example that attempts to map every possible character up to three bits wide (4 is the max, but that would be going a bit far) from the digital representation (in integers) to an encoded printable output, along with its name, if possible (put this into a file called uni.py):

from __future__ import print_function
import io
from unicodedata import name, category
from curses.ascii import controlnames
from collections import Counter

try: # use these if Python 2
    unicode_chr, range = unichr, xrange
except NameError: # Python 3
    unicode_chr = chr

exclude_categories = set(('Co', 'Cn'))
counts = Counter()
control_names = dict(enumerate(controlnames))
with io.open('unidata', 'w', encoding='utf-8') as f:
    for x in range((2**8)**3): 
        try:
            char = unicode_chr(x)
        except ValueError:
            continue # can't map to unicode, try next x
        cat = category(char)
        counts.update((cat,))
        if cat in exclude_categories:
            continue # get rid of noise & greatly shorten result file
        try:
            uname = name(char)
        except ValueError: # probably control character, don't use actual
            uname = control_names.get(x, '')
            f.write(u'{0:>6x} {1}    {2}\n'.format(x, cat, uname))
        else:
            f.write(u'{0:>6x} {1}  {2}  {3}\n'.format(x, cat, char, uname))
# may as well describe the types we logged.
for cat, count in counts.items():
    print('{0} chars of category, {1}'.format(count, cat))

This should run in the order of about a minute, and you can view the data file, and if your file viewer can display unicode, you'll see it. Information about the categories can be found here. Based on the counts, we can probably improve our results by excluding the Cn and Co categories, which have no symbols associated with them.

$ python uni.py

It will display the hexadecimal mapping, category, symbol (unless can't get the name, so probably a control character), and the name of the symbol. e.g.

I recommend less on Unix or Cygwin (don't print/cat the entire file to your output):

$ less unidata

e.g. will display similar to the following lines which I sampled from it using Python 2 (unicode 5.2):

     0 Cc NUL
    20 Zs     SPACE
    21 Po  !  EXCLAMATION MARK
    b6 So  ¶  PILCROW SIGN
    d0 Lu  Ð  LATIN CAPITAL LETTER ETH
   e59 Nd  ?  THAI DIGIT NINE
  2887 So  ?  BRAILLE PATTERN DOTS-1238
  bc13 Lo  ?  HANGUL SYLLABLE MIH
  ffeb Sm  ?  HALFWIDTH RIGHTWARDS ARROW

My Python 3.5 from Anaconda has unicode 8.0, I would presume most 3's would.

pointer to array c++

The parenthesis are superfluous in your example. The pointer doesn't care whether there's an array involved - it only knows that its pointing to an int

  int g[] = {9,8};
  int (*j) = g;

could also be rewritten as

  int g[] = {9,8};
  int *j = g;

which could also be rewritten as

  int g[] = {9,8};
  int *j = &g[0];

a pointer-to-an-array would look like

  int g[] = {9,8};
  int (*j)[2] = &g;

  //Dereference 'j' and access array element zero
  int n = (*j)[0];

There's a good read on pointer declarations (and how to grok them) at this link here: http://www.codeproject.com/Articles/7042/How-to-interpret-complex-C-C-declarations

What does it mean to write to stdout in C?

That means that you are printing output on the main output device for the session... whatever that may be. The user's console, a tty session, a file or who knows what. What that device may be varies depending on how the program is being run and from where.

The following command will write to the standard output device (stdout)...

printf( "hello world\n" );

Which is just another way, in essence, of doing this...

fprintf( stdout, "hello world\n" );

In which case stdout is a pointer to a FILE stream that represents the default output device for the application. You could also use

fprintf( stderr, "that didn't go well\n" );

in which case you would be sending the output to the standard error output device for the application which may, or may not, be the same as stdout -- as with stdout, stderr is a pointer to a FILE stream representing the default output device for error messages.

Determining if an Object is of primitive type

This is the simplest way I could think of. The wrapper classes are present only in java.lang package. And apart from the wrapper classes, no other class in java.lang has field named TYPE. You could use that to check whether a class is Wrapper class or not.

public static boolean isBoxingClass(Class<?> clazz)
{
    String pack = clazz.getPackage().getName();
    if(!"java.lang".equals(pack)) 
        return false;
    try 
    {
        clazz.getField("TYPE");
    } 
    catch (NoSuchFieldException e) 
    {
        return false;
    }           
    return true;        
}

xampp MySQL does not start

You already have a version of mySQL installed on this machine that is using port 3306. Go into the most recent my.ini file and change the port to 3307. Restart the mySQL service and see if it comes up.

You also need to change port 3306 to 3307 in xampp\php\php.ini

How to view/delete local storage in Firefox?

There is now a great plugin for Firebug that clones this nice feature in chrome. Check out:

https://addons.mozilla.org/en-US/firefox/addon/firestorage-plus/

It's developed by Nick Belhomme and updated regularly

How to set javascript variables using MVC4 with Razor

I've seen several approaches to working around the bug, and I ran some timing tests to see what works for speed (http://jsfiddle.net/5dwwy/)

Approaches:

  1. Direct assignment

    In this approach, the razor syntax is directly assigned to the variable. This is what throws the error. As a baseline, the JavaScript speed test simply does a straight assignment of a number to a variable.

  2. Pass through `Number` constructor

    In this approach, we wrap the razor syntax in a call to the `Number` constructor, as in `Number(@ViewBag.Value)`.

  3. ParseInt

    In this approach, the razor syntax is put inside quotes and passed to the `parseInt` function.

  4. Value-returning function

    In this approach, a function is created that simply takes the razor syntax as a parameter and returns it.

  5. Type-checking function

    In this approach, the function performs some basic type checking (looking for null, basically) and returns the value if it isn't null.

Procedure:

Using each approach mentioned above, a for-loop repeats each function call 10M times, getting the total time for the entire loop. Then, that for-loop is repeated 30 times to obtain an average time per 10M actions. These times were then compared to each other to determine which actions were faster than others.

Note that since it is JavaScript running, the actual numbers other people receive will differ, but the importance is not in the actual number, but how the numbers compare to the other numbers.

Results:

Using the Direct assignment approach, the average time to process 10M assignments was 98.033ms. Using the Number constructor yielded 1554.93ms per 10M. Similarly, the parseInt method took 1404.27ms. The two function calls took 97.5ms for the simple function and 101.4ms for the more complex function.

Conclusions:

The cleanest code to understand is the Direct assignment. However, because of the bug in Visual Studio, this reports an error and could cause issues with Intellisense and give a vague sense of being wrong.

The fastest code was the simple function call, but only by a slim margin. Since I didn't do further analysis, I do not know if this difference has a statistical significance. The type-checking function was also very fast, only slightly slower than a direct assignment, and includes the possibility that the variable may be null. It's not really practical, though, because even the basic function will return undefined if the parameter is undefined (null in razor syntax).

Parsing the razor value as an int and running it through the constructor were extremely slow, on the order of 15x slower than a direct assignment. Most likely the Number constructor is actually internally calling parseInt, which would explain why it takes longer than a simple parseInt. However, they do have the advantage of being more meaningful, without requiring an externally-defined (ie somewhere else in the file or application) function to execute, with the Number constructor actually minimizing the visible casting of an integer to a string.

Bottom line, these numbers were generated running through 10M iterations. On a single item, the speed is incalculably small. For most, simply running it through the Number constructor might be the most readable code, despite being the slowest.

How to send Basic Auth with axios

The reason the code in your question does not authenticate is because you are sending the auth in the data object, not in the config, which will put it in the headers. Per the axios docs, the request method alias for post is:

axios.post(url[, data[, config]])

Therefore, for your code to work, you need to send an empty object for data:

var session_url = 'http://api_address/api/session_endpoint';
var username = 'user';
var password = 'password';
var basicAuth = 'Basic ' + btoa(username + ':' + password);
axios.post(session_url, {}, {
  headers: { 'Authorization': + basicAuth }
}).then(function(response) {
  console.log('Authenticated');
}).catch(function(error) {
  console.log('Error on Authentication');
});

The same is true for using the auth parameter mentioned by @luschn. The following code is equivalent, but uses the auth parameter instead (and also passes an empty data object):

var session_url = 'http://api_address/api/session_endpoint';
var uname = 'user';
var pass = 'password';
axios.post(session_url, {}, {
  auth: {
    username: uname,
    password: pass
  }
}).then(function(response) {
  console.log('Authenticated');
}).catch(function(error) {
  console.log('Error on Authentication');
});

Why Choose Struct Over Class?

Since struct instances are allocated on stack, and class instances are allocated on heap, structs can sometimes be drastically faster.

However, you should always measure it yourself and decide based on your unique use case.

Consider the following example, which demonstrates 2 strategies of wrapping Int data type using struct and class. I am using 10 repeated values are to better reflect real world, where you have multiple fields.

class Int10Class {
    let value1, value2, value3, value4, value5, value6, value7, value8, value9, value10: Int
    init(_ val: Int) {
        self.value1 = val
        self.value2 = val
        self.value3 = val
        self.value4 = val
        self.value5 = val
        self.value6 = val
        self.value7 = val
        self.value8 = val
        self.value9 = val
        self.value10 = val
    }
}

struct Int10Struct {
    let value1, value2, value3, value4, value5, value6, value7, value8, value9, value10: Int
    init(_ val: Int) {
        self.value1 = val
        self.value2 = val
        self.value3 = val
        self.value4 = val
        self.value5 = val
        self.value6 = val
        self.value7 = val
        self.value8 = val
        self.value9 = val
        self.value10 = val
    }
}

func + (x: Int10Class, y: Int10Class) -> Int10Class {
    return IntClass(x.value + y.value)
}

func + (x: Int10Struct, y: Int10Struct) -> Int10Struct {
    return IntStruct(x.value + y.value)
}

Performance is measured using

// Measure Int10Class
measure("class (10 fields)") {
    var x = Int10Class(0)
    for _ in 1...10000000 {
        x = x + Int10Class(1)
    }
}

// Measure Int10Struct
measure("struct (10 fields)") {
    var y = Int10Struct(0)
    for _ in 1...10000000 {
        y = y + Int10Struct(1)
    }
}

func measure(name: String, @noescape block: () -> ()) {
    let t0 = CACurrentMediaTime()

    block()

    let dt = CACurrentMediaTime() - t0
    print("\(name) -> \(dt)")
}

Code can be found at https://github.com/knguyen2708/StructVsClassPerformance

UPDATE (27 Mar 2018):

As of Swift 4.0, Xcode 9.2, running Release build on iPhone 6S, iOS 11.2.6, Swift Compiler setting is -O -whole-module-optimization:

  • class version took 2.06 seconds
  • struct version took 4.17e-08 seconds (50,000,000 times faster)

(I no longer average multiple runs, as variances are very small, under 5%)

Note: the difference is a lot less dramatic without whole module optimization. I'd be glad if someone can point out what the flag actually does.


UPDATE (7 May 2016):

As of Swift 2.2.1, Xcode 7.3, running Release build on iPhone 6S, iOS 9.3.1, averaged over 5 runs, Swift Compiler setting is -O -whole-module-optimization:

  • class version took 2.159942142s
  • struct version took 5.83E-08s (37,000,000 times faster)

Note: as someone mentioned that in real-world scenarios, there will be likely more than 1 field in a struct, I have added tests for structs/classes with 10 fields instead of 1. Surprisingly, results don't vary much.


ORIGINAL RESULTS (1 June 2014):

(Ran on struct/class with 1 field, not 10)

As of Swift 1.2, Xcode 6.3.2, running Release build on iPhone 5S, iOS 8.3, averaged over 5 runs

  • class version took 9.788332333s
  • struct version took 0.010532942s (900 times faster)

OLD RESULTS (from unknown time)

(Ran on struct/class with 1 field, not 10)

With release build on my MacBook Pro:

  • The class version took 1.10082 sec
  • The struct version took 0.02324 sec (50 times faster)

Set maxlength in Html Textarea

<p>
   <textarea id="msgc" onkeyup="cnt(event)" rows="1" cols="1"></textarea> 
</p> 
<p id="valmess2" style="color:red" ></p>

function cnt(event)
{ 
 document.getElementById("valmess2").innerHTML=""; // init and clear if b < max     
allowed character 

 a = document.getElementById("msgc").value; 
 b = a.length; 
 if (b > 400)
  { 
   document.getElementById("valmess2").innerHTML="the max length of 400 characters is 
reached, you typed in  " + b + "characters"; 
  } 
}

maxlength is only valid for HTML5. For HTML/XHTML you have to use JavaScript and/or PHP. With PHP you can use strlen for example.This example indicates only the max length, it's NOT blocking the input.

"commence before first target. Stop." error

This means that there is a line which starts with a space, tab, or some other whitespace without having a target in front of it.

Spring Boot: Is it possible to use external application.properties files in arbitrary directories with a fat jar?

This may be coming in Late but I think I figured out a better way to load external configurations especially when you run your spring-boot app using java jar myapp.war instead of @PropertySource("classpath:some.properties")

The configuration would be loaded form the root of the project or from the location the war/jar file is being run from

public class Application implements EnvironmentAware {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void setEnvironment(Environment environment) {
        //Set up Relative path of Configuration directory/folder, should be at the root of the project or the same folder where the jar/war is placed or being run from
        String configFolder = "config";
        //All static property file names here
        List<String> propertyFiles = Arrays.asList("application.properties","server.properties");
        //This is also useful for appending the profile names
        Arrays.asList(environment.getActiveProfiles()).stream().forEach(environmentName -> propertyFiles.add(String.format("application-%s.properties", environmentName))); 
        for (String configFileName : propertyFiles) {
            File configFile = new File(configFolder, configFileName);
            LOGGER.info("\n\n\n\n");
            LOGGER.info(String.format("looking for configuration %s from %s", configFileName, configFolder));
            FileSystemResource springResource = new FileSystemResource(configFile);
            LOGGER.log(Level.INFO, "Config file : {0}", (configFile.exists() ? "FOund" : "Not Found"));
            if (configFile.exists()) {
                try {
                    LOGGER.info(String.format("Loading configuration file %s", configFileName));
                    PropertiesFactoryBean pfb = new PropertiesFactoryBean();
                    pfb.setFileEncoding("UTF-8");
                    pfb.setLocation(springResource);
                    pfb.afterPropertiesSet();
                    Properties properties = pfb.getObject();
                    PropertiesPropertySource externalConfig = new PropertiesPropertySource("externalConfig", properties);
                    ((ConfigurableEnvironment) environment).getPropertySources().addFirst(externalConfig);
                } catch (IOException ex) {
                    LOGGER.log(Level.SEVERE, null, ex);
                }
            } else {
                LOGGER.info(String.format("Cannot find Configuration file %s... \n\n\n\n", configFileName));

            }

        }
    }

}

Hope it helps.

Run a Docker image as a container

For those who had the same problem as well, but encountered an error like

rpc error: code = 2 desc = oci runtime error: exec failed: container_linux.go:247: starting container process caused "exec: \"bash\": executable file not found in $PATH"

I added an entry point that was worked for me:

docker run -it --entrypoint /bin/sh for the images without Bash.

Example (from the approved example):

run -it --entrypoint /bin/sh ubuntu:12.04

Reference: https://gist.github.com/mitchwongho/11266726

How do I set a program to launch at startup

Thanks to everyone for responding so fast. Joel, I used your option 2 and added a registry key to the "Run" folder of the current user. Here's the code I used for anyone else who's interested.

    using Microsoft.Win32;
    private void SetStartup()
    {
        RegistryKey rk = Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

        if (chkStartUp.Checked)
            rk.SetValue(AppName, Application.ExecutablePath);
        else
            rk.DeleteValue(AppName,false);            

    }

Change the jquery show()/hide() animation?

You can also use a fadeIn/FadeOut Combo, too....

$('.test').bind('click', function(){
    $('.div1').fadeIn(500); 
    $('.div2').fadeOut(500);
    $('.div3').fadeOut(500);
    return false;
});

Wavy shape with css

I think this is the right way to make a shape like you want. By using the SVG possibilities, and an container to keep the shape responsive.

_x000D_
_x000D_
svg {_x000D_
  display: inline-block;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
}_x000D_
.container {_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
  width: 100%;_x000D_
  padding-bottom: 100%;_x000D_
  vertical-align: middle;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <svg viewBox="0 0 500 500" preserveAspectRatio="xMinYMin meet">_x000D_
    <path d="M0,100 C150,200 350,0 500,100 L500,00 L0,0 Z" style="stroke: none; fill:red;"></path>_x000D_
  </svg>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Check whether a path is valid in Python without creating a file at the path's target

With Python 3, how about:

try:
    with open(filename, 'x') as tempfile: # OSError if file exists or is invalid
        pass
except OSError:
    # handle error here

With the 'x' option we also don't have to worry about race conditions. See documentation here.

Now, this WILL create a very shortlived temporary file if it does not exist already - unless the name is invalid. If you can live with that, it simplifies things a lot.

Remove directory from remote repository after adding them to .gitignore

The answer from Blundell should work, but for some bizarre reason it didn't do with me. I had to pipe first the filenames outputted by the first command into a file and then loop through that file and delete that file one by one.

git ls-files -i --exclude-from=.gitignore > to_remove.txt
while read line; do `git rm -r --cached "$line"`; done < to_remove.txt
rm to_remove.txt
git commit -m 'Removed all files that are in the .gitignore' 
git push origin master

What is the difference between SAX and DOM?

Both SAX and DOM are used to parse the XML document. Both has advantages and disadvantages and can be used in our programming depending on the situation

SAX:

  1. Parses node by node

  2. Does not store the XML in memory

  3. We cant insert or delete a node

  4. Top to bottom traversing

DOM

  1. Stores the entire XML document into memory before processing

  2. Occupies more memory

  3. We can insert or delete nodes

  4. Traverse in any direction.

If we need to find a node and does not need to insert or delete we can go with SAX itself otherwise DOM provided we have more memory.

Selecting a Record With MAX Value

Say, for an user, there is revision for each date. The following will pick up record for the max revision of each date for each employee.

select job, adate, rev, usr, typ 
from tbl
where exists (  select 1 from ( select usr, adate, max(rev) as max_rev 
                                from tbl
                                group by usr, adate 
                              ) as cond
                where tbl.usr=cond.usr 
                and tbl.adate =cond.adate 
                and tbl.rev =cond.max_rev
             )
order by adate, job, usr

Looking for a 'cmake clean' command to clear up CMake output

In the case where you pass -D parameters into CMake when generating the build files and don't want to delete the entire build/ directory:

Simply delete the CMakeFiles/ directory inside your build directory.

rm -rf CMakeFiles/
cmake --build .

This causes CMake to rerun, and build system files are regenerated. Your build will also start from scratch.

How to build and fill pandas dataframe from for loop?

Make a list of tuples with your data and then create a DataFrame with it:

d = []
for p in game.players.passing():
    d.append((p, p.team, p.passer_rating()))

pd.DataFrame(d, columns=('Player', 'Team', 'Passer Rating'))

A list of tuples should have less overhead than a list dictionaries. I tested this below, but please remember to prioritize ease of code understanding over performance in most cases.

Testing functions:

def with_tuples(loop_size=1e5):
    res = []

    for x in range(int(loop_size)):
        res.append((x-1, x, x+1))

    return pd.DataFrame(res, columns=("a", "b", "c"))

def with_dict(loop_size=1e5):
    res = []

    for x in range(int(loop_size)):
        res.append({"a":x-1, "b":x, "c":x+1})

    return pd.DataFrame(res)

Results:

%timeit -n 10 with_tuples()
# 10 loops, best of 3: 55.2 ms per loop

%timeit -n 10 with_dict()
# 10 loops, best of 3: 130 ms per loop

Which Java library provides base64 encoding/decoding?

If you're an Android developer you can use android.util.Base64 class for this purpose.

How to get week number of the month from the date in sql server 2008

There is no inbuilt function to get you the week number. I dont think dividing will help you anyway as the number of weeks in a month is not constant.

http://msdn.microsoft.com/en-us/library/bb675168.aspx

I guess you can divide the number(48) by 4 and take the modules of the same and project that as the week number of that month, by adding one to the result.

Difference between left join and right join in SQL Server

select * from Table1 left join Table2 on Table1.id = Table2.id

In the first query Left join compares left-sided table table1 to right-sided table table2.

In Which all the properties of table1 will be shown, whereas in table2 only those properties will be shown in which condition get true.

select * from Table2 right join Table1 on Table1.id = Table2.id

In the first query Right join compares right-sided table table1 to left-sided table table2.

In Which all the properties of table1 will be shown, whereas in table2 only those properties will be shown in which condition get true.

Both queries will give the same result because the order of table declaration in query are different like you are declaring table1 and table2 in left and right respectively in first left join query, and also declaring table1 and table2 in right and left respectively in second right join query.

This is the reason why you are getting the same result in both queries. So if you want different result then execute this two queries respectively,

select * from Table1 left join Table2 on Table1.id = Table2.id

select * from Table1 right join Table2 on Table1.id = Table2.id

How to override the properties of a CSS class using another CSS class

You should override by increasing Specificity of your styling. There are different ways of increasing the Specificity. Usage of !important which effects specificity, is a bad practice because it breaks natural cascading in your style sheet.

Following diagram taken from css-tricks.com will help you produce right specificity for your element based on a points structure. Whichever specificity has higher points, will win. Sounds like a game - doesn't it?

enter image description here

Checkout sample calculations here on css-tricks.com. This will help you understand the concept very well and it will only take 2 minutes.

If you then like to produce and/or compare different specificities by yourself, try this Specificity Calculator: https://specificity.keegan.st/ or you can just use traditional paper/pencil.

For further reading try MDN Web Docs.

All the best for not using !important.

Grant Select on all Tables Owned By Specific User

Well, it's not a single statement, but it's about as close as you can get with oracle:

BEGIN
   FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP
      EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser';
   END LOOP;
END; 

Empty set literal?

No, there's no literal syntax for the empty set. You have to write set().

What does -XX:MaxPermSize do?

In Java 8 that parameter is commonly used to print a warning message like this one:

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=512m; support was removed in 8.0

The reason why you get this message in Java 8 is because Permgen has been replaced by Metaspace to address some of PermGen's drawbacks (as you were able to see for yourself, one of those drawbacks is that it had a fixed size).

FYI: an article on Metaspace: http://java-latte.blogspot.in/2014/03/metaspace-in-java-8.html

How to set an environment variable in a running docker container

If you are running the container as a service using docker swarm, you can do:

docker service update --env-add <you environment variable> <service_name>

Also remove using --env-rm

To make sure it's addedd as you wanted, just run: docker exec -it <container id> env

How do I embed a mp4 movie into my html?

You should look into Video For Everyone:

Video for Everybody is very simply a chunk of HTML code that embeds a video into a website using the HTML5 element which offers native playback in Firefox 3.5 and Safari 3 & 4 and an increasing number of other browsers.

The video is played by the browser itself. It loads quickly and doesn’t threaten to crash your browser.

In other browsers that do not support , it falls back to QuickTime.

If QuickTime is not installed, Adobe Flash is used. You can host locally or embed any Flash file, such as a YouTube video.

The only downside, is that you have to have 2/3 versions of the same video stored, but you can serve to every existing device/browser that supports video (i.e.: the iPhone).

<video width="640" height="360" poster="__POSTER__.jpg" controls="controls">
    <source src="__VIDEO__.mp4" type="video/mp4" />
    <source src="__VIDEO__.webm" type="video/webm" />
    <source src="__VIDEO__.ogv" type="video/ogg" /><!--[if gt IE 6]>
    <object width="640" height="375" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"><!
    [endif]--><!--[if !IE]><!-->
    <object width="640" height="375" type="video/quicktime" data="__VIDEO__.mp4"><!--<![endif]-->
    <param name="src" value="__VIDEO__.mp4" />
    <param name="autoplay" value="false" />
    <param name="showlogo" value="false" />
    <object width="640" height="380" type="application/x-shockwave-flash"
        data="__FLASH__.swf?image=__POSTER__.jpg&amp;file=__VIDEO__.mp4">
        <param name="movie" value="__FLASH__.swf?image=__POSTER__.jpg&amp;file=__VIDEO__.mp4" />
        <img src="__POSTER__.jpg" width="640" height="360" />
        <p>
            <strong>No video playback capabilities detected.</strong>
            Why not try to download the file instead?<br />
            <a href="__VIDEO__.mp4">MPEG4 / H.264 “.mp4” (Windows / Mac)</a> |
            <a href="__VIDEO__.ogv">Ogg Theora &amp; Vorbis “.ogv” (Linux)</a>
        </p>
    </object><!--[if gt IE 6]><!-->
    </object><!--<![endif]-->
</video>

There is an updated version that is a bit more readable:

<!-- "Video For Everybody" v0.4.1 by Kroc Camen of Camen Design <camendesign.com/code/video_for_everybody>
     =================================================================================================================== -->
<!-- first try HTML5 playback: if serving as XML, expand `controls` to `controls="controls"` and autoplay likewise       -->
<!-- warning: playback does not work on iPad/iPhone if you include the poster attribute! fixed in iOS4.0                 -->
<video width="640" height="360" controls preload="none">
    <!-- MP4 must be first for iPad! -->
    <source src="__VIDEO__.MP4" type="video/mp4" /><!-- WebKit video    -->
    <source src="__VIDEO__.webm" type="video/webm" /><!-- Chrome / Newest versions of Firefox and Opera -->
    <source src="__VIDEO__.OGV" type="video/ogg" /><!-- Firefox / Opera -->
    <!-- fallback to Flash: -->
    <object width="640" height="384" type="application/x-shockwave-flash" data="__FLASH__.SWF">
        <!-- Firefox uses the `data` attribute above, IE/Safari uses the param below -->
        <param name="movie" value="__FLASH__.SWF" />
        <param name="flashvars" value="image=__POSTER__.JPG&amp;file=__VIDEO__.MP4" />
        <!-- fallback image. note the title field below, put the title of the video there -->
        <img src="__VIDEO__.JPG" width="640" height="360" alt="__TITLE__"
             title="No video playback capabilities, please download the video below" />
    </object>
</video>
<!-- you *must* offer a download link as they may be able to play the file locally. customise this bit all you want -->
<p> <strong>Download Video:</strong>
    Closed Format:  <a href="__VIDEO__.MP4">"MP4"</a>
    Open Format:    <a href="__VIDEO__.OGV">"OGG"</a>
</p>

Call a url from javascript

If you need to be checking external pages, you won't be able to get away with a pure javascript solution, since any requests to external URLs are blocked. You can get away with it by using JSONP, but that won't work unless the page you're requesting only serves up JSON.

You need to have a proxy on your own server to get the external links for you. This is actually rather simple with any server-side language.

<?php
$contents = file_get_contents($_GET['url']); // please do some sanitation here...
                                             // i'm just showing an example.
echo $contents;
?>

If you needed to check server response codes (eg: 404, 301, etc), then using a library such as cURL in your server-side script could retrieve that information and then pass it onto your javascript app.

Thinking about it now, there probably could be JSONP-enabled proxies out there for you to use, should the "setting up my own proxy" option not be viable.

Accurate way to measure execution times of php scripts

You can use the microtime function for this. From the documentation:

microtime — Return current Unix timestamp with microseconds


If get_as_float is set to TRUE, then microtime() returns a float, which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.

Example usage:

$start = microtime(true);
while (...) {

}
$time_elapsed_secs = microtime(true) - $start;

Password encryption/decryption code in .NET

First create a class like:

public class Encryption
    { 
        public static string Encrypt(string clearText)
        {
            string EncryptionKey = "MAKV2SPBNI99212";
            byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    clearText = Convert.ToBase64String(ms.ToArray());
                }
            }
            return clearText;
        }

        public static string Decrypt(string cipherText)
        {
            string EncryptionKey = "MAKV2SPBNI99212";
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(cipherBytes, 0, cipherBytes.Length);
                        cs.Close();
                    }
                    cipherText = Encoding.Unicode.GetString(ms.ToArray());
                }
            }
            return cipherText;
        }
    }

**In Controller **

add reference for this encryption class:

using testdemo.Models

public ActionResult Index() {
            return View();
        }
        [HttpPost]
        public ActionResult Index(string text)
        {
            if (Request["txtEncrypt"] != null)
            {
                string getEncryptionCode = Request["txtEncrypt"];
                string DecryptCode = Encryption.Decrypt(HttpUtility.UrlDecode(getEncryptionCode));
                ViewBag.GetDecryptCode = DecryptCode;
                return View();
            }
            else {
                string getDecryptCode = Request["txtDecrypt"];
                string EncryptionCode = HttpUtility.UrlEncode(Encryption.Encrypt(getDecryptCode));
                ViewBag.GetEncryptionCode = EncryptionCode;
                return View();
            }

        }

In View

<h2>Decryption Code</h2>
@using (Html.BeginForm())
{
    <table class="table-bordered table">
        <tr>
            <th>Encryption Code</th>
            <td><input type="text" id="txtEncrypt" name="txtEncrypt" placeholder="Enter Encryption Code" /></td>
        </tr>
        <tr>
            <td colspan="2">
                <span style="color:red">@ViewBag.GetDecryptCode</span>
            </td>
        </tr>
        <tr>
                <td colspan="2">
                    <input type="submit" id="btnEncrypt" name="btnEncrypt"value="Decrypt to Encrypt code" />
                </td>
            </tr>
    </table>
}
    <br />
    <br />
    <br />
    <h2>Encryption Code</h2>
@using (Html.BeginForm())
{
    <table class="table-bordered table">
        <tr>
            <th>Decryption Code</th>
            <td><input type="text" id="txtDecrypt" name="txtDecrypt" placeholder="Enter Decryption Code" /></td>
        </tr>

        <tr>
            <td colspan="2">
                <span style="color:red">@ViewBag.GetEncryptionCode</span>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" id="btnDecryt" name="btnDecryt" value="Encrypt to Decrypt code" />
            </td>
        </tr>
    </table>
}

Counting the number of elements in array

Just use the length filter on the whole array. It works on more than just strings:

{{ notcount|length }}

Renaming files in a folder to sequential numbers

I had a similar issue and wrote a shell script for that reason. I've decided to post it regardless that many good answers were already posted because I think it can be helpful for someone. Feel free to improve it!

numerate

@Gnutt The behavior you want can be achieved by typing the following:

./numerate.sh -d <path to directory> -o modtime -L 4 -b <startnumber> -r

If the option -r is left out the reaming will be only simulated (Should be helpful for testing).

The otion L describes the length of the target number (which will be filled with leading zeros) it is also possible to add a prefix/suffix with the options -p <prefix> -s <suffix>.

In case somebody wants the files to be sorted numerically before they get numbered, just remove the -o modtime option.

SelectSingleNode returning null for known good xml node path using XPath

I strongly suspect the problem is to do with namespaces. Try getting rid of the namespace and you'll be fine - but obviously that won't help in your real case, where I'd assume the document is fixed.

I can't remember offhand how to specify a namespace in an XPath expression, but I'm sure that's the problem.

EDIT: Okay, I've remembered how to do it now. It's not terribly pleasant though - you need to create an XmlNamespaceManager for it. Here's some sample code that works with your sample document:

using System;
using System.Xml;

public class Test
{
    static void Main()
    {
        XmlDocument doc = new XmlDocument();
        XmlNamespaceManager namespaces = new XmlNamespaceManager(doc.NameTable);
        namespaces.AddNamespace("ns", "urn:hl7-org:v3");
        doc.Load("test.xml");
        XmlNode idNode = doc.SelectSingleNode("/My_RootNode/ns:id", namespaces);
        string msgID = idNode.Attributes["extension"].Value;
        Console.WriteLine(msgID);
    }
}

How to extract a floating number from a string

You may like to try something like this which covers all the bases, including not relying on whitespace after the number:

>>> import re
>>> numeric_const_pattern = r"""
...     [-+]? # optional sign
...     (?:
...         (?: \d* \. \d+ ) # .1 .12 .123 etc 9.1 etc 98.1 etc
...         |
...         (?: \d+ \.? ) # 1. 12. 123. etc 1 12 123 etc
...     )
...     # followed by optional exponent part if desired
...     (?: [Ee] [+-]? \d+ ) ?
...     """
>>> rx = re.compile(numeric_const_pattern, re.VERBOSE)
>>> rx.findall(".1 .12 9.1 98.1 1. 12. 1 12")
['.1', '.12', '9.1', '98.1', '1.', '12.', '1', '12']
>>> rx.findall("-1 +1 2e9 +2E+09 -2e-9")
['-1', '+1', '2e9', '+2E+09', '-2e-9']
>>> rx.findall("current level: -2.03e+99db")
['-2.03e+99']
>>>

For easy copy-pasting:

numeric_const_pattern = '[-+]? (?: (?: \d* \. \d+ ) | (?: \d+ \.? ) )(?: [Ee] [+-]? \d+ ) ?'
rx = re.compile(numeric_const_pattern, re.VERBOSE)
rx.findall("Some example: Jr. it. was .23 between 2.3 and 42.31 seconds")

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

This is due to using obsolete mysql-connection-java version, your MySQl is updated but not your MySQL jdbc Driver, you can update your connection jar from the official site Official MySQL Connector site. Good Luck.

How do I declare a 2d array in C++ using new?

This question was bugging me - it's a common enough problem that a good solution should already exist, something better than the vector of vectors or rolling your own array indexing.

When something ought to exist in C++ but doesn't, the first place to look is boost.org. There I found the Boost Multidimensional Array Library, multi_array. It even includes a multi_array_ref class that can be used to wrap your own one-dimensional array buffer.

What is the difference between NULL, '\0' and 0?

All three define the meaning of zero in different context.

  • pointer context - NULL is used and means the value of the pointer is 0, independent of whether it is 32bit or 64bit (one case 4 bytes the other 8 bytes of zeroes).
  • string context - the character representing the digit zero has a hex value of 0x30, whereas the NUL character has hex value of 0x00 (used for terminating strings).

These three are always different when you look at the memory:

NULL - 0x00000000 or 0x00000000'00000000 (32 vs 64 bit)
NUL - 0x00 or 0x0000 (ascii vs 2byte unicode)
'0' - 0x20

I hope this clarifies it.

Python 101: Can't open file: No such file or directory

I resolved this problem by navigating to C:\Python27\Scripts folder and then run file.py file instead of C:\Python27 folder

How to sort in-place using the merge sort algorithm?

Knuth left this as an exercise (Vol 3, 5.2.5). There do exist in-place merge sorts. They must be implemented carefully.

First, naive in-place merge such as described here isn't the right solution. It downgrades the performance to O(N2).

The idea is to sort part of the array while using the rest as working area for merging.

For example like the following merge function.

void wmerge(Key* xs, int i, int m, int j, int n, int w) {
    while (i < m && j < n)
        swap(xs, w++, xs[i] < xs[j] ? i++ : j++);
    while (i < m)
        swap(xs, w++, i++);
    while (j < n)
        swap(xs, w++, j++);
}  

It takes the array xs, the two sorted sub-arrays are represented as ranges [i, m) and [j, n) respectively. The working area starts from w. Compare with the standard merge algorithm given in most textbooks, this one exchanges the contents between the sorted sub-array and the working area. As the result, the previous working area contains the merged sorted elements, while the previous elements stored in the working area are moved to the two sub-arrays.

However, there are two constraints that must be satisfied:

  1. The work area should be within the bounds of the array. In other words, it should be big enough to hold elements exchanged in without causing any out-of-bound error.
  2. The work area can be overlapped with either of the two sorted arrays; however, it must ensure that none of the unmerged elements are overwritten.

With this merging algorithm defined, it's easy to imagine a solution, which can sort half of the array; The next question is, how to deal with the rest of the unsorted part stored in work area as shown below:

... unsorted 1/2 array ... | ... sorted 1/2 array ...

One intuitive idea is to recursive sort another half of the working area, thus there are only 1/4 elements haven't been sorted yet.

... unsorted 1/4 array ... | sorted 1/4 array B | sorted 1/2 array A ...

The key point at this stage is that we must merge the sorted 1/4 elements B with the sorted 1/2 elements A sooner or later.

Is the working area left, which only holds 1/4 elements, big enough to merge A and B? Unfortunately, it isn't.

However, the second constraint mentioned above gives us a hint, that we can exploit it by arranging the working area to overlap with either sub-array if we can ensure the merging sequence that the unmerged elements won't be overwritten.

Actually, instead of sorting the second half of the working area, we can sort the first half, and put the working area between the two sorted arrays like this:

... sorted 1/4 array B | unsorted work area | ... sorted 1/2 array A ...

This setup effectively arranges the work area overlap with the sub-array A. This idea is proposed in [Jyrki Katajainen, Tomi Pasanen, Jukka Teuhola. ``Practical in-place mergesort''. Nordic Journal of Computing, 1996].

So the only thing left is to repeat the above step, which reduces the working area from 1/2, 1/4, 1/8, … When the working area becomes small enough (for example, only two elements left), we can switch to a trivial insertion sort to end this algorithm.

Here is the implementation in ANSI C based on this paper.

void imsort(Key* xs, int l, int u);

void swap(Key* xs, int i, int j) {
    Key tmp = xs[i]; xs[i] = xs[j]; xs[j] = tmp;
}

/* 
 * sort xs[l, u), and put result to working area w. 
 * constraint, len(w) == u - l
 */
void wsort(Key* xs, int l, int u, int w) {
    int m;
    if (u - l > 1) {
        m = l + (u - l) / 2;
        imsort(xs, l, m);
        imsort(xs, m, u);
        wmerge(xs, l, m, m, u, w);
    }
    else
        while (l < u)
            swap(xs, l++, w++);
}

void imsort(Key* xs, int l, int u) {
    int m, n, w;
    if (u - l > 1) {
        m = l + (u - l) / 2;
        w = l + u - m;
        wsort(xs, l, m, w); /* the last half contains sorted elements */
        while (w - l > 2) {
            n = w;
            w = l + (n - l + 1) / 2;
            wsort(xs, w, n, l);  /* the first half of the previous working area contains sorted elements */
            wmerge(xs, l, l + n - w, n, u, w);
        }
        for (n = w; n > l; --n) /*switch to insertion sort*/
            for (m = n; m < u && xs[m] < xs[m-1]; ++m)
                swap(xs, m, m - 1);
    }
}

Where wmerge is defined previously.

The full source code can be found here and the detailed explanation can be found here

By the way, this version isn't the fastest merge sort because it needs more swap operations. According to my test, it's faster than the standard version, which allocates extra spaces in every recursion. But it's slower than the optimized version, which doubles the original array in advance and uses it for further merging.

How to remove "onclick" with JQuery?

Old Way (pre-1.7):

$("...").attr("onclick", "").unbind("click");

New Way (1.7+):

$("...").prop("onclick", null).off("click");

(Replace ... with the selector you need.)

_x000D_
_x000D_
// use the "[attr=value]" syntax to avoid syntax errors with special characters (like "$")_x000D_
$('[id="a$id"]').prop('onclick',null).off('click');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<a id="a$id" onclick="alert('get rid of this')" href="javascript:void(0)"  class="black">Qualify</a>
_x000D_
_x000D_
_x000D_

find all subsets that sum to a particular value

public class SumOfSubSet {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int a[] = {1,2};
        int sum=0;
        if(a.length<=0) {
            System.out.println(sum);
        }else {
        for(int i=0;i<a.length;i++) {
            sum=sum+a[i];
            for(int j=i+1;j<a.length;j++) {
                sum=sum+a[i]+a[j];
            }
        }
        System.out.println(sum);

        }


    }

}

How to run a Command Prompt command with Visual Basic code?

Yes. You can use Process.Start to launch an executable, including a console application.

If you need to read the output from the application, you may need to read from it's StandardOutput stream in order to get anything printed from the application you launch.

How to identify numpy types in python?

To get the type, use the builtin type function. With the in operator, you can test if the type is a numpy type by checking if it contains the string numpy;

In [1]: import numpy as np

In [2]: a = np.array([1, 2, 3])

In [3]: type(a)
Out[3]: <type 'numpy.ndarray'>

In [4]: 'numpy' in str(type(a))
Out[4]: True

(This example was run in IPython, by the way. Very handy for interactive use and quick tests.)

HashMap allows duplicates?

Each key in a HashMap must be unique.

When "adding a duplicate key" the old value (for the same key, as keys must be unique) is simply replaced; see HashMap.put:

Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

Returns the previous value associated with key, or null if there was no mapping for key.

As far as nulls: a single null key is allowed (as keys must be unique) but the HashMap can have any number of null values, and a null key need not have a null value. Per the documentation:

[.. HashMap] permits null values and [a] null key.

However, the documentation says nothing about null/null needing to be a specific key/value pair or null/"a" being invalid.

Insert current date/time using now() in a field using MySQL/PHP

You forgot to close the mysql_query command:

mysql_query("INSERT INTO users (first, last, whenadded) VALUES ('$first', '$last', now())");

Note that last parentheses.

How I can check whether a page is loaded completely or not in web driver?

I know this post is old. But after gathering all code from above I made a nice method (solution) to handle ajax running and regular pages. The code is made for C# only (since Selenium is definitely a best fit for C# Visual Studio after a year of messing around).

The method is used as an extension method, which means to put it simple; that you can add more functionality (methods) in this case, to the object IWebDriver. Important is that you have to define: 'this' in the parameters to make use of it.

The timeout variable is the amount of seconds for the webdriver to wait, if the page is not responding. Using 'Selenium' and 'Selenium.Support.UI' namespaces it is possible to execute a piece of javascript that returns a boolean, whether the document is ready (complete) and if jQuery is loaded. If the page does not have jQuery then the method will throw an exception. This exception is 'catched' by error handling. In the catch state the document will only be checked for it's ready state, without checking for jQuery.

public static void WaitUntilDocumentIsReady(this IWebDriver driver, int timeoutInSeconds) {
    var javaScriptExecutor = driver as IJavaScriptExecutor;
    var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));

    try {
        Func<IWebDriver, bool> readyCondition = webDriver => (bool)javaScriptExecutor.ExecuteScript("return (document.readyState == 'complete' && jQuery.active == 0)");
        wait.Until(readyCondition);
    } catch(InvalidOperationException) {
        wait.Until(wd => javaScriptExecutor.ExecuteScript("return document.readyState").ToString() == "complete");
    }
}

List Git commits not pushed to the origin yet

how to determine if a commit with particular hash have been pushed to the origin already?

# list remote branches that contain $commit
git branch -r --contains $commit

Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org

For me the problem was that I was setting REQUESTS_CA_BUNDLE in my .bash_profile

/Users/westonagreene/.bash_profile:
...
export REQUESTS_CA_BUNDLE=/usr/local/etc/openssl/cert.pem
...

Once I set REQUESTS_CA_BUNDLE to blank (i.e. removed from .bash_profile), requests worked again.

export REQUESTS_CA_BUNDLE=""

The problem only exhibited when executing python requests via a CLI (Command Line Interface). If I ran requests.get(URL, CERT) it resolved just fine.

Mac OS Catalina (10.15.6). Pyenv of 3.6.11. Error message I was getting: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)

My answer elsewhere: https://stackoverflow.com/a/64151964/4420657

Iterating through list of list in Python

So wait, this is just a list-within-a-list?

The easiest way is probably just to use nested for loops:

>>> a = [[1, 3, 4], [2, 4, 4], [3, 4, 5]]
>>> a
[[1, 3, 4], [2, 4, 4], [3, 4, 5]]
>>> for list in a:
...     for number in list:
...         print number
...
1
3
4
2
4
4
3
4
5

Or is it something more complicated than that? Arbitrary nesting or something? Let us know if there's something else as well.

Also, for performance reasons, you might want to look at using list comprehensions to do this:

http://docs.python.org/tutorial/datastructures.html#nested-list-comprehensions

Traverse all the Nodes of a JSON Object Tree with JavaScript

You can get all keys / values and preserve the hierarchy with this

// get keys of an object or array
function getkeys(z){
  var out=[]; 
  for(var i in z){out.push(i)};
  return out;
}

// print all inside an object
function allInternalObjs(data, name) {
  name = name || 'data';
  return getkeys(data).reduce(function(olist, k){
    var v = data[k];
    if(typeof v === 'object') { olist.push.apply(olist, allInternalObjs(v, name + '.' + k)); }
    else { olist.push(name + '.' + k + ' = ' + v); }
    return olist;
  }, []);
}

// run with this
allInternalObjs({'a':[{'b':'c'},{'d':{'e':5}}],'f':{'g':'h'}}, 'ob')

This is a modification on (https://stackoverflow.com/a/25063574/1484447)

Waiting for background processes to finish before exiting script

GNU parallel and xargs

These two tools that can make scripts simpler, and also control the maximum number of threads (thread pool). E.g.:

seq 10 | xargs -P4 -I'{}' echo '{}'

or:

seq 10 | parallel -j4  echo '{}'

See also: how to write a process-pool bash shell

Html5 Full screen video

Add object-fit: cover to the style of video

<video controls style="object-fit: cover;" >

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

<img title="<a href="javascript:alert('hello world')">The Link</a>" /> 

Android Studio - Device is connected but 'offline'

Reboot the your mobile this will fix it.

"Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

Personally, I ran these exact steps:

* Install Interop Assemblies: you can install from Microsoft's website https://www.microsoft.com/en-us/download/details.aspx?id=3508&tduid=(09cd06700e5e2553aa540650ec905f71)(256380)(2459594)(TnL5HPStwNw-yuTjfb1FeDiXvvZxhh.R.Q)()

* Check assemblies version: check the version of the assemblies on development and production machines. The assemblies will be in the GAC, in widows 7 this folder is %windir%\assembly.

* Create a Desktop folder: the service uses the desktop folder under systemprofile so you will need to create this folder if not there, here is the location of the folder: For 64 bit applications : C:\Windows\SysWOW64\config\systemprofile\Desktop For 32 bit applications : C:\Windows\System32\config\systemprofile\Desktop

* Add DCOM user permissions:
---start the run window and type 'dcomcnfg'.
---Expand Component Services –> Computers –> My Computer –> DCOM Config.
---Look for Microsoft Excel Application. Right click on it and select properties, then select the Security tab.
---Select the Customize radio button under 'Launch and Activation Permissions' and 'Access Permission' and click the Edit button for both to add users as follows.
---------Click the Add button and users 'IIS_IUSRS' and 'NETWORK SERVICE' and give them full privileges.
---Go to the Identity tab and select "The interactive user" option.
---Click Apply and OK.

Google API authentication: Not valid origin for the client

I received the same console error message when working with this example: https://developers.google.com/analytics/devguides/reporting/embed/v1/getting-started

The documentation says not to overlook two critical steps ("As you go through the instructions, it's important that you not overlook these two critical steps: Enable the Analytics API [&] Set the correct origins"), but does not clearly state WHERE to set the correct origins.

Since the client ID I had was not working, I created a new project and a new client ID. The new project may not have been necessary, but I'm retaining (and using) it.

Here's what worked:

During creation of the credentials, you will see a section called "Restrictions Enter JavaScript origins, redirect URIs, or both". This is where you can enter your origins.

Save and copy your client ID (and secret).

My script worked after I created the new OAUTH credential, assigned the origin, and used the newly generated client ID following this process.

Entity Framework throws exception - Invalid object name 'dbo.BaseCs'

Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.BaseCs'

This error means that EF is translating your LINQ into a sql statement that uses an object (most likely a table) named dbo.BaseCs, which does not exist in the database.

Check your database and verify whether that table exists, or that you should be using a different table name. Also, if you could post a link to the tutorial you are following, it would help to follow along with what you are doing.

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

Just Follow Simple 1-2-3 Steps :

1) Go to Taskbar

2) Click on WAMP icon (Left Click)

enter image description here

3) Now Go to Apache > Services > Apache Module and check Rewrite_module is enable or not ! if its not then click on it ! WAMP will be automatically restarted and you're done !

enter image description here

Find integer index of rows with NaN in pandas dataframe

Let the dataframe be named df and the column of interest(i.e. the column in which we are trying to find nulls) is 'b'. Then the following snippet gives the desired index of null in the dataframe:

   for i in range(df.shape[0]):
       if df['b'].isnull().iloc[i]:
           print(i)

CSS:Defining Styles for input elements inside a div

When you say "called" I'm going to assume you mean an ID tag.

To make it cross-brower, I wouldn't suggest using the CSS3 [], although it is an option. This being said, give each of your textboxes a class like "tb" and the radio button "rb".

Then:

#divContainer .tb { width: 150px }
#divContainer .rb { width: 20px }

This assumes you are using the same classes elsewhere, if not, this will suffice:

.tb { width: 150px }
.rb { width: 20px }

As @David mentioned, to access anything within the division itself:

#divContainer [element] { ... }

Where [element] is whatever HTML element you need.

Curl : connection refused

127.0.0.1 restricts access on every interface on port 8000 except development computer. change it to 0.0.0.0:8000 this will allow connection from curl.

Validate SSL certificates with Python

You can use Twisted to verify certificates. The main API is CertificateOptions, which can be provided as the contextFactory argument to various functions such as listenSSL and startTLS.

Unfortunately, neither Python nor Twisted comes with a the pile of CA certificates required to actually do HTTPS validation, nor the HTTPS validation logic. Due to a limitation in PyOpenSSL, you can't do it completely correctly just yet, but thanks to the fact that almost all certificates include a subject commonName, you can get close enough.

Here is a naive sample implementation of a verifying Twisted HTTPS client which ignores wildcards and subjectAltName extensions, and uses the certificate-authority certificates present in the 'ca-certificates' package in most Ubuntu distributions. Try it with your favorite valid and invalid certificate sites :).

import os
import glob
from OpenSSL.SSL import Context, TLSv1_METHOD, VERIFY_PEER, VERIFY_FAIL_IF_NO_PEER_CERT, OP_NO_SSLv2
from OpenSSL.crypto import load_certificate, FILETYPE_PEM
from twisted.python.urlpath import URLPath
from twisted.internet.ssl import ContextFactory
from twisted.internet import reactor
from twisted.web.client import getPage
certificateAuthorityMap = {}
for certFileName in glob.glob("/etc/ssl/certs/*.pem"):
    # There might be some dead symlinks in there, so let's make sure it's real.
    if os.path.exists(certFileName):
        data = open(certFileName).read()
        x509 = load_certificate(FILETYPE_PEM, data)
        digest = x509.digest('sha1')
        # Now, de-duplicate in case the same cert has multiple names.
        certificateAuthorityMap[digest] = x509
class HTTPSVerifyingContextFactory(ContextFactory):
    def __init__(self, hostname):
        self.hostname = hostname
    isClient = True
    def getContext(self):
        ctx = Context(TLSv1_METHOD)
        store = ctx.get_cert_store()
        for value in certificateAuthorityMap.values():
            store.add_cert(value)
        ctx.set_verify(VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, self.verifyHostname)
        ctx.set_options(OP_NO_SSLv2)
        return ctx
    def verifyHostname(self, connection, x509, errno, depth, preverifyOK):
        if preverifyOK:
            if self.hostname != x509.get_subject().commonName:
                return False
        return preverifyOK
def secureGet(url):
    return getPage(url, HTTPSVerifyingContextFactory(URLPath.fromString(url).netloc))
def done(result):
    print 'Done!', len(result)
secureGet("https://google.com/").addCallback(done)
reactor.run()

Clear the cache in JavaScript

Try changing the JavaScript file's src? From this:

<script language="JavaScript" src="js/myscript.js"></script>

To this:

<script language="JavaScript" src="js/myscript.js?n=1"></script>

This method should force your browser to load a new copy of the JS file.

Paging UICollectionView by cells, not screen

Kind of like evya's answer, but a little smoother because it doesn't set the targetContentOffset to zero.

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    if ([scrollView isKindOfClass:[UICollectionView class]]) {
        UICollectionView* collectionView = (UICollectionView*)scrollView;
        if ([collectionView.collectionViewLayout isKindOfClass:[UICollectionViewFlowLayout class]]) {
            UICollectionViewFlowLayout* layout = (UICollectionViewFlowLayout*)collectionView.collectionViewLayout;

            CGFloat pageWidth = layout.itemSize.width + layout.minimumInteritemSpacing;
            CGFloat usualSideOverhang = (scrollView.bounds.size.width - pageWidth)/2.0;
            // k*pageWidth - usualSideOverhang = contentOffset for page at index k if k >= 1, 0 if k = 0
            // -> (contentOffset + usualSideOverhang)/pageWidth = k at page stops

            NSInteger targetPage = 0;
            CGFloat currentOffsetInPages = (scrollView.contentOffset.x + usualSideOverhang)/pageWidth;
            targetPage = velocity.x < 0 ? floor(currentOffsetInPages) : ceil(currentOffsetInPages);
            targetPage = MAX(0,MIN(self.projects.count - 1,targetPage));

            *targetContentOffset = CGPointMake(MAX(targetPage*pageWidth - usualSideOverhang,0), 0);
        }
    }
}

The process cannot access the file because it is being used by another process (File is created but contains nothing)

using (var fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
using (var sw = new StreamWriter(fs))
{
    sw.WriteLine(message);
}

How to create a new file in unix?

Try > workdirectory/filename.txt

This would:

  • truncate the file if it exists
  • create if it doesn't exist

You can consider it equivalent to:

rm -f workdirectory/filename.txt; touch workdirectory/filename.txt

Set Memory Limit in htaccess

In your .htaccess you can add:

PHP 5.x

<IfModule mod_php5.c>
    php_value memory_limit 64M
</IfModule>

PHP 7.x

<IfModule mod_php7.c>
    php_value memory_limit 64M
</IfModule>

If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.

If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.

Read more on http://support.tigertech.net/php-value

Asserting successive calls to a mock method

You can use the Mock.call_args_list attribute to compare parameters to previous method calls. That in conjunction with Mock.call_count attribute should give you full control.

How to have the formatter wrap code with IntelliJ?

Or you can use the shortcut:

Ctrl + Alt + L

What is a magic number, and why is it bad?

A Magic Number is a hard-coded value that may change at a later stage, but that can be therefore hard to update.

For example, let's say you have a Page that displays the last 50 Orders in a "Your Orders" Overview Page. 50 is the Magic Number here, because it's not set through standard or convention, it's a number that you made up for reasons outlined in the spec.

Now, what you do is you have the 50 in different places - your SQL script (SELECT TOP 50 * FROM orders), your Website (Your Last 50 Orders), your order login (for (i = 0; i < 50; i++)) and possibly many other places.

Now, what happens when someone decides to change 50 to 25? or 75? or 153? You now have to replace the 50 in all the places, and you are very likely to miss it. Find/Replace may not work, because 50 may be used for other things, and blindly replacing 50 with 25 can have some other bad side effects (i.e. your Session.Timeout = 50 call, which is also set to 25 and users start reporting too frequent timeouts).

Also, the code can be hard to understand, i.e. "if a < 50 then bla" - if you encounter that in the middle of a complicated function, other developers who are not familiar with the code may ask themselves "WTF is 50???"

That's why it's best to have such ambiguous and arbitrary numbers in exactly 1 place - "const int NumOrdersToDisplay = 50", because that makes the code more readable ("if a < NumOrdersToDisplay", it also means you only need to change it in 1 well defined place.

Places where Magic Numbers are appropriate is everything that is defined through a standard, i.e. SmtpClient.DefaultPort = 25 or TCPPacketSize = whatever (not sure if that is standardized). Also, everything only defined within 1 function might be acceptable, but that depends on Context.

How does JavaScript .prototype work?

The Definitive Guide to Object-Oriented JavaScript - a very concise and clear ~30min video explanation of the asked question (Prototypal Inheritance topic begins from 5:45, although I'd rather listen to the whole video). The author of this video also made JavaScript object visualizer website http://www.objectplayground.com/.enter image description here enter image description here

How to use filesaver.js

It works in my react project:

import FileSaver from 'file-saver';
// ...
onTestSaveFile() {
    var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
    FileSaver.saveAs(blob, "hello world.txt");
}

How can I color a UIImage in Swift?

This function uses core graphics to achieve this.

func overlayImage(color: UIColor) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)
    let context = UIGraphicsGetCurrentContext()

    color.setFill()

    context!.translateBy(x: 0, y: self.size.height)
    context!.scaleBy(x: 1.0, y: -1.0)

    context!.setBlendMode(CGBlendMode.colorBurn)
    let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
    context!.draw(self.cgImage!, in: rect)

    context!.setBlendMode(CGBlendMode.sourceIn)
    context!.addRect(rect)
    context!.drawPath(using: CGPathDrawingMode.fill)

    let coloredImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return coloredImage
}

How do I fetch multiple columns for use in a cursor loop?

Here is slightly modified version. Changes are noted as code commentary.

BEGIN TRANSACTION

declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500) 
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
 SELECT COLUMN_NAME, TABLE_NAME
   FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE COLUMN_NAME LIKE 'pct%' 
    AND TABLE_NAME LIKE 'TestData%'

open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
  -- And then fetch
  fetch next from Tests into @test, @tableName
  -- And then, if no row is fetched, exit the loop
  if @@fetch_status <> 0
  begin
     break
  end
  -- Quotename is needed if you ever use special characters
  -- in table/column names. Spaces, reserved words etc.
  -- Other changes add apostrophes at right places.
  set @cmd = N'exec sp_rename ''' 
           + quotename(@tableName) 
           + '.' 
           + quotename(@test) 
           + N''',''' 
           + RIGHT(@test,LEN(@test)-3) 
           + '_Pct''' 
           + N', ''column''' 

  print @cmd

  EXEC sp_executeSQL @cmd
END

close Tests 
deallocate Tests

ROLLBACK TRANSACTION
--COMMIT TRANSACTION

Launching Spring application Address already in use

Spring Boot uses embedded Tomcat by default, but it handles it differently without using tomcat-maven-plugin. To change the port use --server.port parameter for example:

java -jar target/gs-serving-web-content-0.1.0.jar --server.port=8181

Update. Alternatively put server.port=8181 into application.properties (or application.yml).

"python" not recognized as a command

emphasis: Remember to always RESTART the CMD WINDOW after setting the PATH environmental variable for it to take effect!

Uninstall / remove a Homebrew package including all its dependencies

Using this answer requires that you create and maintain a file that contains the package names you want installed on your system. If you don't have one already, use the following command and delete the package names what you don't want to keep installed.

brew leaves > brew_packages

Then you can remove all installed, but unwanted packages and any unnecessary dependencies by running the following command

brew_clean brew_packages

brew_clean is available here: https://gist.github.com/cskeeters/10ff1295bca93808213d

This script gets all of the packages you specified in brew_packages and all of their dependancies and compares them against the output of brew list and finally removes the unwanted packages after verifying this list with the user.

At this point if you want to remove package a, you simply remove it from the brew_packages file then re-run brew_clean brew_packages. It will remove b, but not c.

Check if any type of files exist in a directory using BATCH script

You can use this

@echo off
for /F %%i in ('dir /b "c:\test directory\*.*"') do (
   echo Folder is NON empty
   goto :EOF
)
echo Folder is empty or does not exist

Taken from here.

That should do what you need.

Very simple C# CSV reader

This fixed version of code above remember the last element of CVS row ;-)

(tested with a CSV file with 5400 rows and 26 elements by row)

   public static string[] CSVRowToStringArray(string r, char fieldSep = ',', char stringSep = '\"')  {
            bool bolQuote = false;
            StringBuilder bld = new StringBuilder();
            List<string> retAry = new List<string>();

            foreach (char c in r.ToCharArray())
                if ((c == fieldSep && !bolQuote))
                {
                    retAry.Add(bld.ToString());
                    bld.Clear();
                }
                else
                    if (c == stringSep)
                        bolQuote = !bolQuote;
                    else
                        bld.Append(c);

            /* to solve the last element problem */
            retAry.Add(bld.ToString()); /* added this line */
            return retAry.ToArray();
        }

Floating elements within a div, floats outside of div. Why?

Put your floating div(s) in a div and in CSS give it overflow:hidden;
it will work fine.

How to run Conda?

If you installed Anaconda with Visual Studio 2017 for Windows, conda executable is in this path or similar.

In my case path is this: C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\Scripts

Steps to add it to your PATH:

  • On the Windows desktop, right-click My Computer.
  • In the pop-up menu, click Properties.
  • In the System Properties window, click the Advanced tab, and then click Environment Variables.
  • In the System Variables window, highlight Path, and click Edit.
  • Add your path and restart your cmd.

You will be able to execute conda

Happy coding!

How to use target in location.href

You could try this:

        <script type="text/javascript">
         function newWindow(url){
                window.open(url);
            }
        </script>

And call the function

How to copy a dictionary and only edit the copy

As others have explained, the built-in dict does not do what you want. But in Python2 (and probably 3 too) you can easily create a ValueDict class that copies with = so you can be sure that the original will not change.

class ValueDict(dict):

    def __ilshift__(self, args):
        result = ValueDict(self)
        if isinstance(args, dict):
            dict.update(result, args)
        else:
            dict.__setitem__(result, *args)
        return result # Pythonic LVALUE modification

    def __irshift__(self, args):
        result = ValueDict(self)
        dict.__delitem__(result, args)
        return result # Pythonic LVALUE modification

    def __setitem__(self, k, v):
        raise AttributeError, \
            "Use \"value_dict<<='%s', ...\" instead of \"d[%s] = ...\"" % (k,k)

    def __delitem__(self, k):
        raise AttributeError, \
            "Use \"value_dict>>='%s'\" instead of \"del d[%s]" % (k,k)

    def update(self, d2):
        raise AttributeError, \
            "Use \"value_dict<<=dict2\" instead of \"value_dict.update(dict2)\""


# test
d = ValueDict()

d <<='apples', 5
d <<='pears', 8
print "d =", d

e = d
e <<='bananas', 1
print "e =", e
print "d =", d

d >>='pears'
print "d =", d
d <<={'blueberries': 2, 'watermelons': 315}
print "d =", d
print "e =", e
print "e['bananas'] =", e['bananas']


# result
d = {'apples': 5, 'pears': 8}
e = {'apples': 5, 'pears': 8, 'bananas': 1}
d = {'apples': 5, 'pears': 8}
d = {'apples': 5}
d = {'watermelons': 315, 'blueberries': 2, 'apples': 5}
e = {'apples': 5, 'pears': 8, 'bananas': 1}
e['bananas'] = 1

# e[0]=3
# would give:
# AttributeError: Use "value_dict<<='0', ..." instead of "d[0] = ..."

Please refer to the lvalue modification pattern discussed here: Python 2.7 - clean syntax for lvalue modification. The key observation is that str and int behave as values in Python (even though they're actually immutable objects under the hood). While you're observing that, please also observe that nothing is magically special about str or int. dict can be used in much the same ways, and I can think of many cases where ValueDict makes sense.

Setting Column width in Apache POI

You can use also util methods mentioned in this blog: Getting cell witdth and height from excel with Apache POI. It can solve your problem.

Copy & paste from that blog:

static public class PixelUtil {

    public static final short EXCEL_COLUMN_WIDTH_FACTOR = 256;
    public static final short EXCEL_ROW_HEIGHT_FACTOR = 20;
    public static final int UNIT_OFFSET_LENGTH = 7;
    public static final int[] UNIT_OFFSET_MAP = new int[] { 0, 36, 73, 109, 146, 182, 219 };

    public static short pixel2WidthUnits(int pxs) {
        short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR * (pxs / UNIT_OFFSET_LENGTH));
        widthUnits += UNIT_OFFSET_MAP[(pxs % UNIT_OFFSET_LENGTH)];
        return widthUnits;
    }

    public static int widthUnits2Pixel(short widthUnits) {
        int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR) * UNIT_OFFSET_LENGTH;
        int offsetWidthUnits = widthUnits % EXCEL_COLUMN_WIDTH_FACTOR;
        pixels += Math.floor((float) offsetWidthUnits / ((float) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH));
        return pixels;
    }

    public static int heightUnits2Pixel(short heightUnits) {
        int pixels = (heightUnits / EXCEL_ROW_HEIGHT_FACTOR);
        int offsetWidthUnits = heightUnits % EXCEL_ROW_HEIGHT_FACTOR;
        pixels += Math.floor((float) offsetWidthUnits / ((float) EXCEL_ROW_HEIGHT_FACTOR / UNIT_OFFSET_LENGTH));
        return pixels;
    }
}

So when you want to get cell width and height you can use this to get value in pixel, values are approximately.

PixelUtil.heightUnits2Pixel((short) row.getHeight())
PixelUtil.widthUnits2Pixel((short) sh.getColumnWidth(columnIndex));

Make .gitignore ignore everything except a few files

I also had some issues with the negation of single files. I was able to commit them, but my IDE (IntelliJ) always complained about ignored files, which are tracked.

git ls-files -i --exclude-from .gitignore

Displayed the two files, which I've excluded this way:

public/
!public/typo3conf/LocalConfiguration.php
!public/typo3conf/PackageStates.php

In the end, this worked for me:

public/*
!public/typo3conf/
public/typo3conf/*
!public/typo3conf/LocalConfiguration.php
!public/typo3conf/PackageStates.php

The key was the negation of the folder typo3conf/ first.

Also, it seems that the order of the statements doesn't matter. Instead, you need to explicitly negate all subfolders, before you can negate single files in it.

The folder !public/typo3conf/ and the folder contents public/typo3conf/* are two different things for .gitignore.

Great thread! This issue bothered me for a while ;)

How to embed an autoplaying YouTube video in an iframe?

Nowadays I include a new attribute "allow" on iframe tag, for example:

allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"

The final code is:

<iframe src="https://www.youtube.com/embed/[VIDEO-CODE]?autoplay=1" 
frameborder="0" style="width: 100%; height: 100%;"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"></iframe>

Jupyter notebook not running code. Stuck on In [*]

I fixed this issue

just only type this command: jupyter notebook --no-browser

It will show you the path then copy and paste on Jupyter Notebook browser

The code will be executed in IPython Notebook Python 3

Excel: Searching for multiple terms in a cell

In addition to the answer of @teylyn, I would like to add that you can put the string of multiple search terms inside a SINGLE cell (as opposed to using a different cell for each term and then using that range as argument to SEARCH), using named ranges and the EVALUATE function as I found from this link.

For example, I put the following terms as text in a cell, $G$1:

"PRB", "utilization", "alignment", "spectrum"

Then, I defined a named range named search_terms for that cell as described in the link above and shown in the figure below:

Named range definition

In the Refers to: field I put the following:

=EVALUATE("{" & TDoc_List!$G$1 & "}")

The above EVALUATE expression is simple used to emulate the literal string

{"PRB", "utilization", "alignment", "spectrum"}

to be used as input to the SEARCH function: using a direct reference to the SINGLE cell $G$1 (augmented with the curly braces in that case) inside SEARCH does not work, hence the use of named ranges and EVALUATE.

The trick now consists in replacing the direct reference to $G$1 by the EVALUATE-augmented named range search_terms.

The formula

It really works, and shows once more how powerful Excel really is!

It really works!

Hope this helps.

How To Show And Hide Input Fields Based On Radio Button Selection

<script type="text/javascript">
function Check() {
    if (document.getElementById('yesCheck').checked) {
        document.getElementById('ifYes').style.display = 'block';
    } 
    else {
        document.getElementById('ifYes').style.display = 'none';

   }
}

</script>
</head>
<body>
Select os :
<br>
Two
<input type="radio" onclick="Check();" value="Two" name="categor`enter code here`y" id="yesCheck"/>One
<input type="radio" onclick="Check();" value="One"name="category"/>
<br>
<div id="ifYes" style="display:none" >
Three<input type="radio" name="win" value="Three"/>
Four<input type="radio" name="win" value="Four"/>

Android SDK location

Update v3.3

enter image description here

Update:

Android Studio 3.1 update, some of the icon images have changed. Click this icon in Android Studio.

enter image description here

Original:

Click this icon in Android Studio for the Android SDK manager

enter image description here

And your Android SDK Location will be here enter image description here

Deploying my application at the root in Tomcat

on tomcat v.7 (vanilla installation)

in your conf/server.xml add the following bit towards the end of the file, just before the </Host> closing tag:

<Context path="" docBase="app_name">
    <!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>

Note that docBase attribute. It's the important bit. You either make sure you've deployed app_name before you change your root web app, or just copy your unpacked webapp (app_name) into your tomcat's webapps folder. Startup, visit root, see your app_name there!

linq where list contains any in list

You can use a Contains query for this:

var movies = _db.Movies.Where(p => p.Genres.Any(x => listOfGenres.Contains(x));

Ternary operator in AngularJS templates

For texts in angular template (userType is property of $scope, like $scope.userType):

<span>
  {{userType=='admin' ? 'Edit' : 'Show'}}
</span>

Change Twitter Bootstrap Tooltip content on click

I couldn't get any of the answers working, here's a workaround:

$('#'+$(element).attr('aria-describedby')+' .tooltip-inner').html(newTitle);

How to stop java process gracefully?

Shutdown hooks execute in all cases where the VM is not forcibly killed. So, if you were to issue a "standard" kill (SIGTERM from a kill command) then they will execute. Similarly, they will execute after calling System.exit(int).

However a hard kill (kill -9 or kill -SIGKILL) then they won't execute. Similarly (and obviously) they won't execute if you pull the power from the computer, drop it into a vat of boiling lava, or beat the CPU into pieces with a sledgehammer. You probably already knew that, though.

Finalizers really should run as well, but it's best not to rely on that for shutdown cleanup, but rather rely on your shutdown hooks to stop things cleanly. And, as always, be careful with deadlocks (I've seen far too many shutdown hooks hang the entire process)!

How do you access the element HTML from within an Angular attribute directive?

So actually, my comment that you should do a console.log(el.nativeElement) should have pointed you in the right direction, but I didn't expect the output to be just a string representing the DOM Element.

What you have to do to inspect it in the way it helps you with your problem, is to do a console.log(el) in your example, then you'll have access to the nativeElement object and will see a property called innerHTML.

Which will lead to the answer to your original question:

let myCurrentContent:string = el.nativeElement.innerHTML; // get the content of your element
el.nativeElement.innerHTML = 'my new content'; // set content of your element

Update for better approach:

Since it's the accepted answer and web workers are getting more important day to day (and it's considered best practice anyway) I want to add this suggestion by Mark Rajcok here.

The best way to manipulate DOM Elements programmatically is using the Renderer:

constructor(private _elemRef: ElementRef, private _renderer: Renderer) { 
    this._renderer.setElementProperty(this._elemRef.nativeElement, 'innerHTML', 'my new content');
}

Edit

Since Renderer is deprecated now, use Renderer2 instead with setProperty


Update:

This question with its answer explained the console.log behavior.

Which means that console.dir(el.nativeElement) would be the more direct way of accessing the DOM Element as an "inspectable" Object in your console for this situation.


Hope this helped.

Can't install gems on OS X "El Capitan"

Reinstalling RVM worked for me, but I had to reinstall all of my gems afterward:

rvm implode
\curl -sSL https://get.rvm.io | bash -s stable --ruby
rvm reload

Change the project theme in Android Studio?

In the AndroidManifest.xml, under the application tag, you can set the theme of your choice. To customize the theme, press Ctrl + Click on android:theme = "@style/AppTheme" in the Android manifest file. It will open styles.xml file where you can change the parent attribute of the style tag.

At parent= in styles.xml you can browse all available styles by using auto-complete inside the "". E.g. try parent="Theme." with your cursor right after the . and then pressing Ctrl + Space.

You can also preview themes in the preview window in Android Studio.

enter image description here

EC2 instance has no public DNS

  1. Go to AWS Console.
  2. Go to Services and select VPC
  3. Click on vpc.
  4. select the instance and click on Action.
  5. Select Edit DNS Host name click on yes.

At the end you will get your Public dns.

What is String pool in Java?

I don't think it actually does much, it looks like it's just a cache for string literals. If you have multiple Strings who's values are the same, they'll all point to the same string literal in the string pool.

String s1 = "Arul"; //case 1 
String s2 = "Arul"; //case 2 

In case 1, literal s1 is created newly and kept in the pool. But in case 2, literal s2 refer the s1, it will not create new one instead.

if(s1 == s2) System.out.println("equal"); //Prints equal. 

String n1 = new String("Arul"); 
String n2 = new String("Arul"); 
if(n1 == n2) System.out.println("equal"); //No output.  

http://p2p.wrox.com/java-espanol/29312-string-pooling.html

Margin between items in recycler view Android

Instead of using XML to add margin between items in RecyclerView, it's better way to use RecyclerView.ItemDecoration that provide by android framework.

So, I create a library to solve this issue.

https://github.com/TheKhaeng/recycler-view-margin-decoration

enter image description here

Unescape HTML entities in Javascript?

EDIT: You should use the DOMParser API as Wladimir suggests, I edited my previous answer since the function posted introduced a security vulnerability.

The following snippet is the old answer's code with a small modification: using a textarea instead of a div reduces the XSS vulnerability, but it is still problematic in IE9 and Firefox.

function htmlDecode(input){
  var e = document.createElement('textarea');
  e.innerHTML = input;
  // handle case of empty input
  return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}

htmlDecode("&lt;img src='myimage.jpg'&gt;"); 
// returns "<img src='myimage.jpg'>"

Basically I create a DOM element programmatically, assign the encoded HTML to its innerHTML and retrieve the nodeValue from the text node created on the innerHTML insertion. Since it just creates an element but never adds it, no site HTML is modified.

It will work cross-browser (including older browsers) and accept all the HTML Character Entities.

EDIT: The old version of this code did not work on IE with blank inputs, as evidenced here on jsFiddle (view in IE). The version above works with all inputs.

UPDATE: appears this doesn't work with large string, and it also introduces a security vulnerability, see comments.

JComboBox Selection Change Listener?

Here is creating a ComboBox adding a listener for item selection change:

JComboBox comboBox = new JComboBox();

comboBox.setBounds(84, 45, 150, 20);
contentPane.add(comboBox);

JComboBox comboBox_1 = new JComboBox();
comboBox_1.setBounds(84, 97, 150, 20);
contentPane.add(comboBox_1);
comboBox.addItemListener(new ItemListener() {
    public void itemStateChanged(ItemEvent arg0) {
        //Do Something
    }
});

Read each line of txt file to new array element

$file = __DIR__."/file1.txt";
$f = fopen($file, "r");
$array1 = array();

while ( $line = fgets($f, 1000) )
{
    $nl = mb_strtolower($line,'UTF-8');
    $array1[] = $nl;
}

print_r($array);

Delete last N characters from field in a SQL Server database

UPDATE mytable SET column=LEFT(column, LEN(column)-5)

Removes the last 5 characters from the column (every row in mytable)

Rails: How to run `rails generate scaffold` when the model already exists?

TL;DR: rails g scaffold_controller <name>

Even though you already have a model, you can still generate the necessary controller and migration files by using the rails generate option. If you run rails generate -h you can see all of the options available to you.

Rails:
  controller
  generator
  helper
  integration_test
  mailer
  migration
  model
  observer
  performance_test
  plugin
  resource
  scaffold
  scaffold_controller
  session_migration
  stylesheets

If you'd like to generate a controller scaffold for your model, see scaffold_controller. Just for clarity, here's the description on that:

Stubs out a scaffolded controller and its views. Pass the model name, either CamelCased or under_scored, and a list of views as arguments. The controller name is retrieved as a pluralized version of the model name.

To create a controller within a module, specify the model name as a path like 'parent_module/controller_name'.

This generates a controller class in app/controllers and invokes helper, template engine and test framework generators.

To create your resource, you'd use the resource generator, and to create a migration, you can also see the migration generator (see, there's a pattern to all of this madness). These provide options to create the missing files to build a resource. Alternatively you can just run rails generate scaffold with the --skip option to skip any files which exist :)

I recommend spending some time looking at the options inside of the generators. They're something I don't feel are documented extremely well in books and such, but they're very handy.

How do I move to end of line in Vim?

The main question - end of line

$ goes to the end of line, remains in command mode

A goes to the end of line, switches to insert mode

Conversely - start of line (technically the first non-whitespace character)

^ goes to the start of line, remains in command mode

I (uppercase i) goes to the start of line, switches to insert mode

Further - start of line (technically the first column irrespective of whitespace)

0 (zero) goes to the start of line, remains in command mode

0i (zero followed by lowercase i) goes the start of line, switches to insert mode

For those starting to learn vi, here is a good introduction to vi by listing side by side vi commands to typical Windows GUI Editor cursor movement and shortcut keys.

vi editor for Windows users

Class method differences in Python: bound, unbound and static

When you call a class member, Python automatically uses a reference to the object as the first parameter. The variable self actually means nothing, it's just a coding convention. You could call it gargaloo if you wanted. That said, the call to method_two would raise a TypeError, because Python is automatically trying to pass a parameter (the reference to its parent object) to a method that was defined as having no parameters.

To actually make it work, you could append this to your class definition:

method_two = staticmethod(method_two)

or you could use the @staticmethod function decorator.

Batch File: ( was unexpected at this time

you need double quotes in all your three if statements, eg.:

IF "%a%"=="2" (

@echo OFF &SETLOCAL ENABLEDELAYEDEXPANSION
cls
title ~USB Wizard~
echo What do you want to do?
echo 1.Enable/Disable USB Storage Devices.
echo 2.Enable/Disable Writing Data onto USB Storage.
echo 3.~Yet to come~.


set "a=%globalparam1%"
goto :aCheck
:aPrompt
set /p "a=Enter Choice: "
:aCheck
if "%a%"=="" goto :aPrompt
echo %a%

IF "%a%"=="2" (
    title USB WRITE LOCK
    echo What do you want to do?
    echo 1.Apply USB Write Protection
    echo 2.Remove USB Write Protection
    ::param1
    set "param1=%globalparam2%"
    goto :param1Check
    :param1Prompt
    set /p "param1=Enter Choice: "
    :param1Check
    if "!param1!"=="" goto :param1Prompt

    if "!param1!"=="1" (
         REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001
         USB Write is Locked!
    )
    if "!param1!"=="2" (
         REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
         USB Write is Unlocked!
    )
)
pause

Error: "The sandbox is not in sync with the Podfile.lock..." after installing RestKit with cocoapods

I got this error when I added a new developer account. I changed the Team under project name but I missed to update it under the Pods folder.

I solved it once I updated the new developer ID under the Teams option available under Pods-> Signing -> Team, the error was gone and the build succeeded.

PHP Fatal error: Cannot redeclare class

This will happen if we use any of the in built classes in the php library. I used the class name as Directory and I got the same error. If you get error first make sure that the class name you use is not one of the in built classes.

How to return a list of keys from a Hash Map?

map.keySet()

will return you all the keys. If you want the keys to be sorted, you might consider a TreeMap

Is it possible to assign numeric value to an enum in Java?

If you're looking for a way to group constants in a class, you can use a static inner class:

public class OuterClass {
    public void exit(boolean isTrue){
        if(isTrue){
            System.exit(ExitCode.A);
        }else{
            System.exit(ExitCode.B);
        }
    }
    public static class ExitCode{
        public static final int A = 203;
        public static final int B = 204;
    }   
}

Pair/tuple data type in Go

There is no tuple type in Go, and you are correct, the multiple values returned by functions do not represent a first-class object.

Nick's answer shows how you can do something similar that handles arbitrary types using interface{}. (I might have used an array rather than a struct to make it indexable like a tuple, but the key idea is the interface{} type)

My other answer shows how you can do something similar that avoids creating a type using anonymous structs.

These techniques have some properties of tuples, but no, they are not tuples.

Aligning textviews on the left and right edges in Android layout

enter image description here

This Code will Divide the control into two equal sides.

    <LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/linearLayout">
    <TextView
        android:text = "Left Side"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight = "1"
        android:id = "@+id/txtLeft"/>

    <TextView android:text = "Right Side"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight = "1"
        android:id = "@+id/txtRight"/>
    </LinearLayout>

Decoding UTF-8 strings in Python

It's an encoding error - so if it's a unicode string, this ought to fix it:

text.encode("windows-1252").decode("utf-8")

If it's a plain string, you'll need an extra step:

text.decode("utf-8").encode("windows-1252").decode("utf-8")

Both of these will give you a unicode string.

By the way - to discover how a piece of text like this has been mangled due to encoding issues, you can use chardet:

>>> import chardet
>>> chardet.detect(u"And the Hip’s coming, too")
{'confidence': 0.5, 'encoding': 'windows-1252'}

MySQL LEFT JOIN 3 tables

SELECT p.*, f.Fear
FROM Persons p
LEFT JOIN Person_Fear pf ON pf.PersonID = p.PersonID
LEFT JOIN Fears f ON f.FearID = pf.FearID
ORDER BY p.PersonID

  1. You need to select from the Persons table to ensure you generate a row for every person, whether they have fears or not.
  2. Then you can left join Person_Fear to every person, which will just be NULL if they don't have any entries (as you want).
  3. Finally, you left join Fears on Person_Fear so that you can select the name of the fear.
  4. Optionally, add an order so that each person has all their fears listed together, even if they were added to the Person_Fear table at different times.

Best way to generate xml?

Use lxml.builder class, from: http://lxml.de/tutorial.html#the-e-factory

import lxml.builder as lb
from lxml import etree

nstext = "new story"
story = lb.E.Asset(
  lb.E.Attribute(nstext, name="Name", act="set"),
  lb.E.Relation(lb.E.Asset(idref="Scope:767"),
            name="Scope", act="set")
  )

print 'story:\n', etree.tostring(story, pretty_print=True)

Output:

story:
<Asset>
  <Attribute name="Name" act="set">new story</Attribute>
  <Relation name="Scope" act="set">
    <Asset idref="Scope:767"/>
  </Relation>
</Asset>

Append an array to another array in JavaScript

If you want to modify the original array instead of returning a new array, use .push()...

array1.push.apply(array1, array2);
array1.push.apply(array1, array3);

I used .apply to push the individual members of arrays 2 and 3 at once.

or...

array1.push.apply(array1, array2.concat(array3));

To deal with large arrays, you can do this in batches.

for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
    array1.push.apply(array1, to_add.slice(n, n+300));
}

If you do this a lot, create a method or function to handle it.

var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);

Object.defineProperty(Array.prototype, "pushArrayMembers", {
    value: function() {
        for (var i = 0; i < arguments.length; i++) {
            var to_add = arguments[i];
            for (var n = 0; n < to_add.length; n+=300) {
                push_apply(this, slice_call(to_add, n, n+300));
            }
        }
    }
});

and use it like this:

array1.pushArrayMembers(array2, array3);

_x000D_
_x000D_
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
    value: function() {_x000D_
        for (var i = 0; i < arguments.length; i++) {_x000D_
            var to_add = arguments[i];_x000D_
            for (var n = 0; n < to_add.length; n+=300) {_x000D_
                push_apply(this, slice_call(to_add, n, n+300));_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
_x000D_
_x000D_

jQuery - prevent default, then continue default

Use jQuery.one()

Attach a handler to an event for the elements. The handler is executed at most once per element per event type

$('form').one('submit', function(e) {
    e.preventDefault();
    // do your things ...

    // and when you done:
    $(this).submit();
});

The use of one prevent also infinite loop because this custom submit event is detatched after the first submit.

Save Screen (program) output to a file

The selected answer doesn't work quite well with multiple sessions and doesn't allow to specify a custom log file name.

For multiple screen sessions, this is my formula:

  1. Create a configuration file for each process:

    logfile test.log
    logfile flush 1
    log on
    logtstamp after 1
    logtstamp string "[ %t: %Y-%m-%d %c:%s ]\012"
    logtstamp on
    

    If you want to do it "on the fly", you can change logfile automatically. \012 means "new line", as using \n will print it on the log file: source.

  2. Start your command with the "-c" and "-L" flags:

    screen -c ./test.conf -dmSL 'Test' ./test.pl
    

    That's it. You will see "test.log" after the first flush:

    ...
    6 Something is happening...
    [ test.pl: 2016-06-01 13:02:53 ]
    7 Something else...
    [ test.pl: 2016-06-01 13:02:54 ]
    8 Nothing here
    [ test.pl: 2016-06-01 13:02:55 ]
    9 Something is happening...
    [ test.pl: 2016-06-01 13:02:56 ]
    10 Something else...
    [ test.pl: 2016-06-01 13:02:57 ]
    11 Nothing here
    [ test.pl: 2016-06-01 13:02:58 ]
    ...
    

I found that "-L" is still required even when "log on" is on the configuration file.

I couldn't find a list of the time format variables (like %m) used by screen. If you have a link of those formats, please post it bellow.

Extra

In case you want to do it "on the fly", you can use this script:

#!/bin/bash
if [[ $2 == "" ]]; then
    echo "Usage: $0 name command";
    exit 1;
fi
name=$1
command=$2
path="/var/log";
config="logfile ${path}/${name}.log
logfile flush 1
log on
logtstamp after 1
logtstamp string \"[ %t: %Y-%m-%d %c:%s ]\012\"
logtstamp on";
echo "$config" > /tmp/log.conf
screen -c /tmp/log.conf -dmSL "$name" $command
rm /tmp/log.conf

To use it, save it (screen.sh) and set +x permissions:

./screen.sh TEST ./test.pl

... and will execute ./test.pl and create a log file in /var/log/TEST.log

DOUBLE vs DECIMAL in MySQL

Actually it's quite different. DOUBLE causes rounding issues. And if you do something like 0.1 + 0.2 it gives you something like 0.30000000000000004. I personally would not trust financial data that uses floating point math. The impact may be small, but who knows. I would rather have what I know is reliable data than data that were approximated, especially when you are dealing with money values.

How to compare two tags with git?

If source code is on Github, you can use their comparing tool: https://help.github.com/articles/comparing-commits-across-time/

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

Here's a more concise answer for people that are looking for a quick reference as well as some examples using promises and async/await.

Start with the naive approach (that doesn't work) for a function that calls an asynchronous method (in this case setTimeout) and returns a message:

function getMessage() {
  var outerScopeVar;
  setTimeout(function() {
    outerScopeVar = 'Hello asynchronous world!';
  }, 0);
  return outerScopeVar;
}
console.log(getMessage());

undefined gets logged in this case because getMessage returns before the setTimeout callback is called and updates outerScopeVar.

The two main ways to solve it are using callbacks and promises:

Callbacks

The change here is that getMessage accepts a callback parameter that will be called to deliver the results back to the calling code once available.

function getMessage(callback) {
  setTimeout(function() {
    callback('Hello asynchronous world!');
  }, 0);
}
getMessage(function(message) {
  console.log(message);
});

Promises

Promises provide an alternative which is more flexible than callbacks because they can be naturally combined to coordinate multiple async operations. A Promises/A+ standard implementation is natively provided in node.js (0.12+) and many current browsers, but is also implemented in libraries like Bluebird and Q.

function getMessage() {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve('Hello asynchronous world!');
    }, 0);
  });
}

getMessage().then(function(message) {
  console.log(message);  
});

jQuery Deferreds

jQuery provides functionality that's similar to promises with its Deferreds.

function getMessage() {
  var deferred = $.Deferred();
  setTimeout(function() {
    deferred.resolve('Hello asynchronous world!');
  }, 0);
  return deferred.promise();
}

getMessage().done(function(message) {
  console.log(message);  
});

async/await

If your JavaScript environment includes support for async and await (like Node.js 7.6+), then you can use promises synchronously within async functions:

function getMessage () {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            resolve('Hello asynchronous world!');
        }, 0);
    });
}

async function main() {
    let message = await getMessage();
    console.log(message);
}

main();

What exactly is an instance in Java?

basically object and instance are the two words used interchangeably. A class is template for an object and an object is an instance of a class.

How to convert array values to lowercase in PHP?

`$Color = array('A' => 'Blue', 'B' => 'Green', 'c' => 'Red');

$strtolower = array_map('strtolower', $Color);

$strtoupper = array_map('strtoupper', $Color);

print_r($strtolower); print_r($strtoupper);`

Node.js ES6 classes with require

The ES6 way of require is import. You can export your class and import it somewhere else using import { ClassName } from 'path/to/ClassName'syntax.

import fs from 'fs';
export default class Animal {

  constructor(name){
    this.name = name ;
  }

  print(){
    console.log('Name is :'+ this.name);
  }
}

import Animal from 'path/to/Animal.js';