Programs & Examples On #Taskmanager

What is the 'realtime' process priority setting for?

A realtime priority thread can never be pre-empted by timer interrupts and runs at a higher priority than any other thread in the system. As such a CPU bound realtime priority thread can totally ruin a machine.

Creating realtime priority threads requires a privilege (SeIncreaseBasePriorityPrivilege) so it can only be done by administrative users.

For Vista and beyond, one option for applications that do require that they run at realtime priorities is to use the Multimedia Class Scheduler Service (MMCSS) and let it manage your threads priority. The MMCSS will prevent your application from using too much CPU time so you don't have to worry about tanking the machine.

What, why or when it is better to choose cshtml vs aspx?

As other people have answered, .cshtml (or .vbhtml if that's your flavor) provides a handler-mapping to load the MVC engine. The .aspx extension simply loads the aspnet_isapi.dll that performs the compile and serves up web forms. The difference in the handler mapping is simply a method of allowing the two to co-exist on the same server allowing both MVC applications and WebForms applications to live under a common root.

This allows http://www.mydomain.com/MyMVCApplication to be valid and served with MVC rules along with http://www.mydomain.com/MyWebFormsApplication to be valid as a standard web form.

Edit:
As for the difference in the technologies, the MVC (Razor) templating framework is intended to return .Net pages to a more RESTful "web-based" platform of templated views separating the code logic between the model (business/data objects), the view (what the user sees) and the controllers (the connection between the two). The WebForms model (aspx) was an attempt by Microsoft to use complex javascript embedding to simulate a more stateful application similar to a WinForms application complete with events and a page lifecycle that would be capable of retaining its own state from page to page.

The choice to use one or the other is always going to be a contentious one because there are arguments for and against both systems. I for one like the simplicity in the MVC architecture (though routing is anything but simple) and the ease of the Razor syntax. I feel the WebForms architecture is just too heavy to be an effective web platform. That being said, there are a lot of instances where the WebForms framework provides a very succinct and usable model with a rich event structure that is well defined. It all boils down to the needs of the application and the preferences of those building it.

printf \t option

A tab is a tab. How many spaces it consumes is a display issue, and depends on the settings of your shell.

If you want to control the width of your data, then you could use the width sub-specifiers in the printf format string. Eg. :

printf("%5d", 2);

It's not a complete solution (if the value is longer than 5 characters, it will not be truncated), but might be ok for your needs.

If you want complete control, you'll probably have to implement it yourself.

Append to the end of a file in C

Open with append:

pFile2 = fopen("myfile2.txt", "a");

then just write to pFile2, no need to fseek().

How to get different colored lines for different plots in a single figure?

Setting them later

If you don't know the number of the plots you are going to plot you can change the colours once you have plotted them retrieving the number directly from the plot using .lines, I use this solution:

Some random data

import matplotlib.pyplot as plt
import numpy as np

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)


for i in range(1,15):
    ax1.plot(np.array([1,5])*i,label=i)

The piece of code that you need:

colormap = plt.cm.gist_ncar #nipy_spectral, Set1,Paired   
colors = [colormap(i) for i in np.linspace(0, 1,len(ax1.lines))]
for i,j in enumerate(ax1.lines):
    j.set_color(colors[i])
  

ax1.legend(loc=2)

The result is the following:enter image description here

Spring Boot REST service exception handling

New answer (2016-04-20)

Using Spring Boot 1.3.1.RELEASE

New Step 1 - It is easy and less intrusive to add the following properties to the application.properties:

spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false

Much easier than modifying the existing DispatcherServlet instance (as below)! - JO'

If working with a full RESTful Application, it is very important to disable the automatic mapping of static resources since if you are using Spring Boot's default configuration for handling static resources then the resource handler will be handling the request (it's ordered last and mapped to /** which means that it picks up any requests that haven't been handled by any other handler in the application) so the dispatcher servlet doesn't get a chance to throw an exception.


New Answer (2015-12-04)

Using Spring Boot 1.2.7.RELEASE

New Step 1 - I found a much less intrusive way of setting the "throExceptionIfNoHandlerFound" flag. Replace the DispatcherServlet replacement code below (Step 1) with this in your application initialization class:

@ComponentScan()
@EnableAutoConfiguration
public class MyApplication extends SpringBootServletInitializer {
    private static Logger LOG = LoggerFactory.getLogger(MyApplication.class);
    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(MyApplication.class, args);
        DispatcherServlet dispatcherServlet = (DispatcherServlet)ctx.getBean("dispatcherServlet");
        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
    }

In this case, we're setting the flag on the existing DispatcherServlet, which preserves any auto-configuration by the Spring Boot framework.

One more thing I've found - the @EnableWebMvc annotation is deadly to Spring Boot. Yes, that annotation enables things like being able to catch all the controller exceptions as described below, but it also kills a LOT of the helpful auto-configuration that Spring Boot would normally provide. Use that annotation with extreme caution when you use Spring Boot.


Original Answer:

After a lot more research and following up on the solutions posted here (thanks for the help!) and no small amount of runtime tracing into the Spring code, I finally found a configuration that will handle all Exceptions (not Errors, but read on) including 404s.

Step 1 - tell SpringBoot to stop using MVC for "handler not found" situations. We want Spring to throw an exception instead of returning to the client a view redirect to "/error". To do this, you need to have an entry in one of your configuration classes:

// NEW CODE ABOVE REPLACES THIS! (2015-12-04)
@Configuration
public class MyAppConfig {
    @Bean  // Magic entry 
    public DispatcherServlet dispatcherServlet() {
        DispatcherServlet ds = new DispatcherServlet();
        ds.setThrowExceptionIfNoHandlerFound(true);
        return ds;
    }
}

The downside of this is that it replaces the default dispatcher servlet. This hasn't been a problem for us yet, with no side effects or execution problems showing up. If you're going to do anything else with the dispatcher servlet for other reasons, this is the place to do them.

Step 2 - Now that spring boot will throw an exception when no handler is found, that exception can be handled with any others in a unified exception handler:

@EnableWebMvc
@ControllerAdvice
public class ServiceExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(Throwable.class)
    @ResponseBody
    ResponseEntity<Object> handleControllerException(HttpServletRequest req, Throwable ex) {
        ErrorResponse errorResponse = new ErrorResponse(ex);
        if(ex instanceof ServiceException) {
            errorResponse.setDetails(((ServiceException)ex).getDetails());
        }
        if(ex instanceof ServiceHttpException) {
            return new ResponseEntity<Object>(errorResponse,((ServiceHttpException)ex).getStatus());
        } else {
            return new ResponseEntity<Object>(errorResponse,HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @Override
    protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        Map<String,String> responseBody = new HashMap<>();
        responseBody.put("path",request.getContextPath());
        responseBody.put("message","The URL you have reached is not in service at this time (404).");
        return new ResponseEntity<Object>(responseBody,HttpStatus.NOT_FOUND);
    }
    ...
}

Keep in mind that I think the "@EnableWebMvc" annotation is significant here. It seems that none of this works without it. And that's it - your Spring boot app will now catch all exceptions, including 404s, in the above handler class and you may do with them as you please.

One last point - there doesn't seem to be a way to get this to catch thrown Errors. I have a wacky idea of using aspects to catch errors and turn them into Exceptions that the above code can then deal with, but I have not yet had time to actually try implementing that. Hope this helps someone.

Any comments/corrections/enhancements will be appreciated.

php random x digit number

I usually just use RAND() http://php.net/manual/en/function.rand.php

e.g.

rand ( 10000 , 99999 );

for your 5 digit random number

mysql-python install error: Cannot open include file 'config-win.h'

for 64-bit windows

SELECT data from another schema in oracle

Depending on the schema/account you are using to connect to the database, I would suspect you are missing a grant to the account you are using to connect to the database.

Connect as PCT account in the database, then grant the account you are using select access for the table.

grant select on pi_int to Account_used_to_connect

What is the difference between the operating system and the kernel?

The difference between an operating system and a kernel:

The kernel is a part of an operating system. The operating system is the software package that communicates directly to the hardware and our application. The kernel is the lowest level of the operating system. The kernel is the main part of the operating system and is responsible for translating the command into something that can be understood by the computer. The main functions of the kernel are:

  1. memory management
  2. network management
  3. device driver
  4. file management
  5. process management

How to break nested loops in JavaScript?

There are at least five different ways to break out of two or more loops:

1) Set parent(s) loop to the end

for (i = 0; i < 5; i++)
{
    for (j = 0; j < 5; j++)
    {
        if (j === 2)
        {
            i = 5;
            break;
        }
    }
}

2) Use label

fast:
for (i = 0; i < 5; i++)
{
    for (j = 0; j < 5; j++)
    {
        if (j === 2)
            break fast;
    }
}

3) Use variable

var exit_loops = false;
for (i = 0; i < 5; i++)
{
    for (j = 0; j < 5; j++)
    {
        if (j === 2)
        {
            exit_loops = true;
            break;
        }
    }
    if (exit_loops)
        break;
}

4) Use self executing function

(function()
{
    for (i = 0; i < 5; i++)
    {
        for (j = 0; j < 5; j++)
        {
             if (j === 2)
                 return;
        }
    }
})();

5) Use regular function

function nested_loops()
{
    for (i = 0; i < 5; i++)
    {
        for (j = 0; j < 5; j++)
        {
             if (j === 2)
                 return;
        }
    }
}
nested_loops();

Java Spring Boot: How to map my app root (“/”) to index.html?

An example of Dave Syer's answer:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MyWebMvcConfig {

    @Bean
    public WebMvcConfigurerAdapter forwardToIndex() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                // forward requests to /admin and /user to their index.html
                registry.addViewController("/admin").setViewName(
                        "forward:/admin/index.html");
                registry.addViewController("/user").setViewName(
                        "forward:/user/index.html");
            }
        };
    }

}

Convert HttpPostedFileBase to byte[]

As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:

MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();

It's easy enough to write the equivalent of CopyTo in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream.

For efficient purposes you could check whether the stream returned is already a MemoryStream:

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

How can I get the current contents of an element in webdriver

I know when you said "contents" you didn't mean this, but if you want to find all the values of all the attributes of a webelement this is a pretty nifty way to do that with javascript in python:

everything = b.execute_script(
    'var element = arguments[0];'
    'var attributes = {};'
    'for (index = 0; index < element.attributes.length; ++index) {'
    '    attributes[element.attributes[index].name] = element.attributes[index].value };'
    'var properties = [];'
    'properties[0] = attributes;'
    'var element_text = element.textContent;'
    'properties[1] = element_text;'
    'var styles = getComputedStyle(element);'
    'var computed_styles = {};'
    'for (index = 0; index < styles.length; ++index) {'
    '    var value_ = styles.getPropertyValue(styles[index]);'
    '    computed_styles[styles[index]] = value_ };'
    'properties[2] = computed_styles;'
    'return properties;', element)

you can also get some extra data with element.__dict__.

I think this is about all the data you'd ever want to get from a webelement.

c++ array assignment of multiple values

There is a difference between initialization and assignment. What you want to do is not initialization, but assignment. But such assignment to array is not possible in C++.

Here is what you can do:

#include <algorithm>

int array [] = {1,3,34,5,6};
int newarr [] = {34,2,4,5,6};
std::copy(newarr, newarr + 5, array);

However, in C++0x, you can do this:

std::vector<int> array = {1,3,34,5,6};
array = {34,2,4,5,6};

Of course, if you choose to use std::vector instead of raw array.

jQuery add class .active on menu

<script type="text/javascript">
    jQuery(document).ready(function($) {
    var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); 
    $("#navbar li a").each(function() {//alert('dsfgsdgfd');
    if(urlRegExp.test(this.href.replace(/\/$/,''))){
    $(this).addClass("active");}
});
}); 
</script>

How to center a subview of UIView

I would use:

child.center = CGPointMake(parent.bounds.height / 2, parent.bounds.width / 2)

This is simple, short, and sweet. If you use @Hejazi's answer above and parent.center is set to anything other than (0,0) your subview will not be centered!

Best way to get child nodes

Don't let white space fool you. Just test this in a console browser.

Use native javascript. Here is and example with two 'ul' sets with the same class. You don't need to have your 'ul' list all in one line to avoid white space just use your array count to jump over white space.

How to get around white space with querySelector() then childNodes[] js fiddle link: https://jsfiddle.net/aparadise/56njekdo/

var y = document.querySelector('.list');
var myNode = y.childNodes[11].style.backgroundColor='red';

<ul class="list">
    <li>8</li>
    <li>9</li>
    <li>100</li>
</ul>

<ul class="list">
    <li>ABC</li>
    <li>DEF</li>
    <li>XYZ</li>
</ul>

What is the default initialization of an array in Java?

Everything in a Java program not explicitly set to something by the programmer, is initialized to a zero value.

  • For references (anything that holds an object) that is null.
  • For int/short/byte/long that is a 0.
  • For float/double that is a 0.0
  • For booleans that is a false.
  • For char that is the null character '\u0000' (whose decimal equivalent is 0).

When you create an array of something, all entries are also zeroed. So your array contains five zeros right after it is created by new.

Note (based on comments): The Java Virtual Machine is not required to zero out the underlying memory when allocating local variables (this allows efficient stack operations if needed) so to avoid random values the Java Language Specification requires local variables to be initialized.

Laravel back button

Indeed using {{ URL:previous() }} do work, but if you're using a same named route to display multiple views, it will take you back to the first endpoint of this route.

In my case, I have a named route, which based on a parameter selected by the user, can render 3 different views. Of course, I have a default case for the first enter in this route, when the user doesn't selected any option yet.

When I use URL:previous(), Laravel take me back to the default view, even if the user has selected some other option. Only using javascript inside the button I accomplished to be returned to the correct view:

<a href="javascript:history.back()" class="btn btn-default">Voltar</a>

I'm tested this on Laravel 5.3, just for clarification.

How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

A margin-top of -8px means it will be 8px higher than if it had 0 margin.

A margin-bottom of 8px means that the thing below it will be 8px further down that if it had 0 margin.

Laravel migration table field's type change

update: 31 Oct 2018, Still usable on laravel 5.7 https://laravel.com/docs/5.7/migrations#modifying-columns

To make some change to existing db, you can modify column type by using change() in migration.

This is what you could do

Schema::table('orders', function ($table) {
    $table->string('category_id')->change();
});

please note you need to add doctrine/dbal dependency to composer.json for more information you can find it here http://laravel.com/docs/5.1/migrations#modifying-columns

SyntaxError: Non-ASCII character '\xa3' in file when function returns '£'

The error message tells you exactly what's wrong. The Python interpreter needs to know the encoding of the non-ASCII character.

If you want to return U+00A3 then you can say

return u'\u00a3'

which represents this character in pure ASCII by way of a Unicode escape sequence. If you want to return a byte string containing the literal byte 0xA3, that's

return b'\xa3'

(where in Python 2 the b is implicit; but explicit is better than implicit).

The linked PEP in the error message instructs you exactly how to tell Python "this file is not pure ASCII; here's the encoding I'm using". If the encoding is UTF-8, that would be

# coding=utf-8

or the Emacs-compatible

# -*- encoding: utf-8 -*-

If you don't know which encoding your editor uses to save this file, examine it with something like a hex editor and some googling. The Stack Overflow tag has a tag info page with more information and some troubleshooting tips.

In so many words, outside of the 7-bit ASCII range (0x00-0x7F), Python can't and mustn't guess what string a sequence of bytes represents. https://tripleee.github.io/8bit#a3 shows 21 possible interpretations for the byte 0xA3 and that's only from the legacy 8-bit encodings; but it could also very well be the first byte of a multi-byte encoding. But in fact, I would guess you are actually using Latin-1, so you should have

# coding: latin-1

as the first or second line of your source file. Anyway, without knowledge of which character the byte is supposed to represent, a human would not be able to guess this, either.

A caveat: coding: latin-1 will definitely remove the error message (because there are no byte sequences which are not technically permitted in this encoding), but might produce completely the wrong result when the code is interpreted if the actual encoding is something else. You really have to know the encoding of the file with complete certainty when you declare the encoding.

MVC ajax post to controller action method

$('#loginBtn').click(function(e) {
    e.preventDefault(); /// it should not have this code or else it wont continue
    //....
});

nginx error "conflicting server name" ignored

I assume that you're running a Linux, and you're using gEdit to edit your files. In the /etc/nginx/sites-enabled, it may have left a temp file e.g. default~ (watch the ~).

Depending on your editor, the file could be named .save or something like it. Just run $ ls -lah to see which files are unintended to be there and remove them (Thanks @Tisch for this).

Delete this file, and it will solve your problem.

How to do SQL Like % in Linq?

System.Data.Linq.SqlClient.SqlMethods.Like("mystring", "%string")

Return generated pdf using spring MVC

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

Notes:

  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

How to read all of Inputstream in Server Socket JAVA

The problem you have is related to TCP streaming nature.

The fact that you sent 100 Bytes (for example) from the server doesn't mean you will read 100 Bytes in the client the first time you read. Maybe the bytes sent from the server arrive in several TCP segments to the client.

You need to implement a loop in which you read until the whole message was received. Let me provide an example with DataInputStream instead of BufferedinputStream. Something very simple to give you just an example.

Let's suppose you know beforehand the server is to send 100 Bytes of data.

In client you need to write:

byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";

try 
{
    DataInputStream in = new DataInputStream(clientSocket.getInputStream());

    while(!end)
    {
        int bytesRead = in.read(messageByte);
        dataString += new String(messageByte, 0, bytesRead);
        if (dataString.length == 100)
        {
            end = true;
        }
    }
    System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
    e.printStackTrace();
}

Now, typically the data size sent by one node (the server here) is not known beforehand. Then you need to define your own small protocol for the communication between server and client (or any two nodes) communicating with TCP.

The most common and simple is to define TLV: Type, Length, Value. So you define that every message sent form server to client comes with:

  • 1 Byte indicating type (For example, it could also be 2 or whatever).
  • 1 Byte (or whatever) for length of message
  • N Bytes for the value (N is indicated in length).

So you know you have to receive a minimum of 2 Bytes and with the second Byte you know how many following Bytes you need to read.

This is just a suggestion of a possible protocol. You could also get rid of "Type".

So it would be something like:

byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";

try 
{
    DataInputStream in = new DataInputStream(clientSocket.getInputStream());
    int bytesRead = 0;

    messageByte[0] = in.readByte();
    messageByte[1] = in.readByte();

    int bytesToRead = messageByte[1];

    while(!end)
    {
        bytesRead = in.read(messageByte);
        dataString += new String(messageByte, 0, bytesRead);
        if (dataString.length == bytesToRead )
        {
            end = true;
        }
    }
    System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
    e.printStackTrace();
}

The following code compiles and looks better. It assumes the first two bytes providing the length arrive in binary format, in network endianship (big endian). No focus on different encoding types for the rest of the message.

import java.nio.ByteBuffer;
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;

class Test
{
    public static void main(String[] args)
    {
        byte[] messageByte = new byte[1000];
        boolean end = false;
        String dataString = "";

        try 
        {
            Socket clientSocket;
            ServerSocket server;

            server = new ServerSocket(30501, 100);
            clientSocket = server.accept();

            DataInputStream in = new DataInputStream(clientSocket.getInputStream());
            int bytesRead = 0;

            messageByte[0] = in.readByte();
            messageByte[1] = in.readByte();
            ByteBuffer byteBuffer = ByteBuffer.wrap(messageByte, 0, 2);

            int bytesToRead = byteBuffer.getShort();
            System.out.println("About to read " + bytesToRead + " octets");

            //The following code shows in detail how to read from a TCP socket

            while(!end)
            {
                bytesRead = in.read(messageByte);
                dataString += new String(messageByte, 0, bytesRead);
                if (dataString.length() == bytesToRead )
                {
                    end = true;
                }
            }

            //All the code in the loop can be replaced by these two lines
            //in.readFully(messageByte, 0, bytesToRead);
            //dataString = new String(messageByte, 0, bytesToRead);

            System.out.println("MESSAGE: " + dataString);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

Bootstrap Modal immediately disappearing

For me what worked was to remove

data-toggle="modal"

from the button. The button itself can be any element - a link, div, button etc.

PHP 5.4 Call-time pass-by-reference - Easy fix available?

You should be denoting the call by reference in the function definition, not the actual call. Since PHP started showing the deprecation errors in version 5.3, I would say it would be a good idea to rewrite the code.

From the documentation:

There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);.

For example, instead of using:

// Wrong way!
myFunc(&$arg);               # Deprecated pass-by-reference argument
function myFunc($arg) { }

Use:

// Right way!
myFunc($var);                # pass-by-value argument
function myFunc(&$arg) { }

Calling a method inside another method in same class

The add method that takes a String and a Person is calling a different add method that takes a Position. The one that takes Position is inherited from the ArrayList class.

Since your class Staff extends ArrayList<Position>, it automatically has the add(Position) method. The new add(String, Person) method is one that was written particularly for the Staff class.

ORA-12170: TNS:Connect timeout occurred

I was getting the same error while connecting my "hr" user of ORCLPDB which is a pluggable database.

First, get hostname and port number by typing a command lsnrctl status on windows command prompt. In my case, it was 127.0.0.1 with port number as 1521

Second, enter the below command with your hostname and port number:

sqlplus username/password@HostName:Port Number/PluggableDatabaseName.

For example:

sqlplus hr/[email protected]:1521/ORCLPDB.

How do I find the location of Python module sources?

Not all python modules are written in python. Datetime happens to be one of them that is not, and (on linux) is datetime.so.

You would have to download the source code to the python standard library to get at it.

Focus Next Element In Tab Index

Did you specify your own tabIndex values for each element you want to cycle through? if so, you can try this:

var lasTabIndex = 10; //Set this to the highest tabIndex you have
function OnFocusOut()
{
    var currentElement = $get(currentElementId); // ID set by OnFocusIn 

    var curIndex = $(currentElement).attr('tabindex'); //get the tab index of the current element
    if(curIndex == lastTabIndex) { //if we are on the last tabindex, go back to the beginning
        curIndex = 0;
    }
    $('[tabindex=' + (curIndex + 1) + ']').focus(); //set focus on the element that has a tab index one greater than the current tab index
}

You are using jquery, right?

How to get the dimensions of a tensor (in TensorFlow) at graph construction time?

Just print out the embed after construction graph (ops) without running:

import tensorflow as tf

...

train_dataset = tf.placeholder(tf.int32, shape=[128, 2])
embeddings = tf.Variable(
    tf.random_uniform([50000, 64], -1.0, 1.0))
embed = tf.nn.embedding_lookup(embeddings, train_dataset)
print (embed)

This will show the shape of the embed tensor:

Tensor("embedding_lookup:0", shape=(128, 2, 64), dtype=float32)

Usually, it's good to check shapes of all tensors before training your models.

Could not open input file: composer.phar

I have fixed the same issue with below steps

  1. Open project directory Using Terminal (which you are using i.e. mintty )
  2. Now install composer within this directory as per given directions on https://getcomposer.org/download/

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"

php -r "if (hash_file('SHA384', 'composer-setup.php') === 'the-provided-hash-code') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

php composer-setup.php php -r "unlink('composer-setup.php');"

  1. Now run your command.

Everything is working fine now because the composer.phar file is available within the current project directory.

Copied from https://stackoverflow.com/questions/21670709/running-composer-returns-could-not-open-input-file-composer-phar/51907013#51907013

thanks

Schedule automatic daily upload with FileZilla

FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.

Some references:


Though you can use any other client that allows automation.

You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).

Combine WinSCP scripting capabilities with Windows Scheduler:

A typical WinSCP script for upload (with SFTP) looks like:

open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close

With FTP, just replace the sftp:// with the ftp:// and remove the -hostkey="..." switch.


Similarly for download: How to schedule an automatic FTP download on Windows?


WinSCP can even generate a script from an imported FileZilla session.

For details, see the guide to FileZilla automation.

(I'm the author of WinSCP)


Another option, if you are using SFTP, is the psftp.exe client from PuTTY suite.

CSS background image URL failing to load

I know this is really old, but I'm posting my solution anyways since google finds this thread.

background-image: url('./imagefolder/image.jpg');

That is what I do. Two dots means drill back one directory closer to root ".." while one "." should mean start where you are at as if it were root. I was having similar issues but adding that fixed it for me. You can even leave the "." in it when uploading to your host because it should work fine so long as your directory setup is exactly the same.

Why is synchronized block better than synchronized method?

Difference between synchronized block and synchronized method are following:

  1. synchronized block reduce scope of lock, but synchronized method's scope of lock is whole method.
  2. synchronized block has better performance as only the critical section is locked but synchronized method has poor performance than block.
  3. synchronized block provide granular control over lock but synchronized method lock either on current object represented by this or class level lock.
  4. synchronized block can throw NullPointerException but synchronized method doesn't throw.
  5. synchronized block: synchronized(this){}

    synchronized method: public synchronized void fun(){}

Insert new column into table in sqlite?

You have two options. First, you could simply add a new column with the following:

ALTER TABLE {tableName} ADD COLUMN COLNew {type};

Second, and more complicatedly, but would actually put the column where you want it, would be to rename the table:

ALTER TABLE {tableName} RENAME TO TempOldTable;

Then create the new table with the missing column:

CREATE TABLE {tableName} (name TEXT, COLNew {type} DEFAULT {defaultValue}, qty INTEGER, rate REAL);

And populate it with the old data:

INSERT INTO {tableName} (name, qty, rate) SELECT name, qty, rate FROM TempOldTable;

Then delete the old table:

DROP TABLE TempOldTable;

I'd much prefer the second option, as it will allow you to completely rename everything if need be.

JavaScript: Create and save file

_x000D_
_x000D_
setTimeout("create('Hello world!', 'myfile.txt', 'text/plain')");_x000D_
function create(text, name, type) {_x000D_
  var dlbtn = document.getElementById("dlbtn");_x000D_
  var file = new Blob([text], {type: type});_x000D_
  dlbtn.href = URL.createObjectURL(file);_x000D_
  dlbtn.download = name;_x000D_
}
_x000D_
<a href="javascript:void(0)" id="dlbtn"><button>click here to download your file</button></a>
_x000D_
_x000D_
_x000D_

Which method performs better: .Any() vs .Count() > 0?

Since this is a rather popular topic and answers differ, I had to take a fresh look on the problem.

Testing env: EF 6.1.3, SQL Server, 300k records

Table model:

class TestTable
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    public string Surname { get; set; }
}

Test code:

class Program
{
    static void Main()
    {
        using (var context = new TestContext())
        {
            context.Database.Log = Console.WriteLine;

            context.TestTables.Where(x => x.Surname.Contains("Surname")).Any(x => x.Id > 1000);
            context.TestTables.Where(x => x.Surname.Contains("Surname") && x.Name.Contains("Name")).Any(x => x.Id > 1000);
            context.TestTables.Where(x => x.Surname.Contains("Surname")).Count(x => x.Id > 1000);
            context.TestTables.Where(x => x.Surname.Contains("Surname") && x.Name.Contains("Name")).Count(x => x.Id > 1000);

            Console.ReadLine();
        }
    }
}

Results:

Any() ~ 3ms

Count() ~ 230ms for first query, ~ 400ms for second

Remarks:

For my case, EF didn't generate SQL like @Ben mentioned in his post.

Postgres: INSERT if does not exist already

It's easy with rules:

CREATE RULE file_insert_defer AS ON INSERT TO file
WHERE (EXISTS ( SELECT * FROM file WHERE file.id = new.id)) DO INSTEAD NOTHING

But it fails with concurrent writes ...

Parse query string into an array

Using parse_str().

$str = 'pg_id=2&parent_id=2&document&video';
parse_str($str, $arr);
print_r($arr);

Getting the source HTML of the current page from chrome extension

Inject a script into the page you want to get the source from and message it back to the popup....

manifest.json

{
  "name": "Get pages source",
  "version": "1.0",
  "manifest_version": 2,
  "description": "Get pages source from a popup",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": ["tabs", "<all_urls>"]
}

popup.html

<!DOCTYPE html>
<html style=''>
<head>
<script src='popup.js'></script>
</head>
<body style="width:400px;">
<div id='message'>Injecting Script....</div>
</body>
</html>

popup.js

chrome.runtime.onMessage.addListener(function(request, sender) {
  if (request.action == "getSource") {
    message.innerText = request.source;
  }
});

function onWindowLoad() {

  var message = document.querySelector('#message');

  chrome.tabs.executeScript(null, {
    file: "getPagesSource.js"
  }, function() {
    // If you try and inject into an extensions page or the webstore/NTP you'll get an error
    if (chrome.runtime.lastError) {
      message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
    }
  });

}

window.onload = onWindowLoad;

getPagesSource.js

// @author Rob W <http://stackoverflow.com/users/938089/rob-w>
// Demo: var serialized_html = DOMtoString(document);

function DOMtoString(document_root) {
    var html = '',
        node = document_root.firstChild;
    while (node) {
        switch (node.nodeType) {
        case Node.ELEMENT_NODE:
            html += node.outerHTML;
            break;
        case Node.TEXT_NODE:
            html += node.nodeValue;
            break;
        case Node.CDATA_SECTION_NODE:
            html += '<![CDATA[' + node.nodeValue + ']]>';
            break;
        case Node.COMMENT_NODE:
            html += '<!--' + node.nodeValue + '-->';
            break;
        case Node.DOCUMENT_TYPE_NODE:
            // (X)HTML documents are identified by public identifiers
            html += "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>\n';
            break;
        }
        node = node.nextSibling;
    }
    return html;
}

chrome.runtime.sendMessage({
    action: "getSource",
    source: DOMtoString(document)
});

Forwarding port 80 to 8080 using NGINX

you can do this very easy by using following in sudo vi /etc/nginx/sites-available/default

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    server_name _ your_domain;

    location /health {
            access_log off;
            return 200 "healthy\n";
    }

    location / {
            proxy_pass http://localhost:8080; 
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_cache_bypass $http_upgrade;
    }
  }

How to check if a file is empty in Bash?

[[ -s file ]] --> Checks if file has size greater than 0

if [[ -s diff.txt ]]; then echo "file has something"; else echo "file is empty"; fi

If needed, this checks all the *.txt files in the current directory; and reports all the empty file:

for file in *.txt; do if [[ ! -s $file ]]; then echo $file; fi; done

How do operator.itemgetter() and sort() work?

Looks like you're a little bit confused about all that stuff.

operator is a built-in module providing a set of convenient operators. In two words operator.itemgetter(n) constructs a callable that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it.

So, you can't use key=a[x][1] there, because python has no idea what x is. Instead, you could use a lambda function (elem is just a variable name, no magic there):

a.sort(key=lambda elem: elem[1])

Or just an ordinary function:

def get_second_elem(iterable):
    return iterable[1]

a.sort(key=get_second_elem)

So, here's an important note: in python functions are first-class citizens, so you can pass them to other functions as a parameter.

Other questions:

  1. Yes, you can reverse sort, just add reverse=True: a.sort(key=..., reverse=True)
  2. To sort by more than one column you can use itemgetter with multiple indices: operator.itemgetter(1,2), or with lambda: lambda elem: (elem[1], elem[2]). This way, iterables are constructed on the fly for each item in list, which are than compared against each other in lexicographic(?) order (first elements compared, if equal - second elements compared, etc)
  3. You can fetch value at [3,2] using a[2,1] (indices are zero-based). Using operator... It's possible, but not as clean as just indexing.

Refer to the documentation for details:

  1. operator.itemgetter explained
  2. Sorting list by custom key in Python

Integer value in TextView

If you want it to display on your layout you should

For example:

activity_layout.XML file

    <TextView
        android:id="@+id/example_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

On the activity.java file

    final TextView textView = findViewById(R.id.example_tv);
    textView.setText(Integer.toString(yourNumberHere));

In the first line on the XML file you can see:

android:id="@+id/example_tv"

That's where you get the id to change in the .java file for the findViewById(R.id.example_tv)

Hope I made myself clear, I just went with this explanation because a lot of times people seem to know the ".setText()" method, they just can't change the text in the "UI".


EDIT Since this is a fairly old answer, and Kotlin is the preferred language for Android development, here's its counterpart.

With the same XML layout:

You can either use the findViewbyId() or use Kotlin synthetic properties:

findViewById<TextView>(R.id.example_tv).text = yourNumberHere.toString()

// Or

example_tv?.text = yourNumberHere.toString()

The toString() is from Kotlin's Any object (comparable to the Java Object):

The root of the Kotlin class hierarchy. Every Kotlin class has Any as a superclass.

Double quotes within php script echo

You need to escape ", so it won't be interpreted as end of string. Use \ to escape it:

echo "<script>$('#edit_errors').html('<h3><em><font color=\"red\">Please Correct Errors Before Proceeding</font></em></h3>')</script>";

Read more: strings and escape sequences

How to apply two CSS classes to a single element

This is very clear that to add two classes in single div, first you have to generate the classes and then combine them. This process is used to make changes and reduce the no. of classes. Those who make the website from scratch mostly used this type of methods. they make two classes first class is for color and second class is for setting width, height, font-style, etc. When we combine both the classes then the first class and second class both are in effect.

_x000D_
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
  width:"100%";_x000D_
  height:"100px";_x000D_
  font-size: 16px;_x000D_
  text-align:center;_x000D_
  line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
_x000D_
_x000D_

How can I test a PDF document if it is PDF/A compliant?

The 3-Heights™ PDF Validator Online Tool provides good feedback for different PDF/A conformance levels and versions.

  • PDF/A1-a
  • PDF/A2-a
  • PDF/A2-b
  • PDF/A1-b
  • PDF/A2-u

How to assign name for a screen?

The easiest way use screen with name

screen -S 'name' 'application'
  • Ctrl+a, d = exit and leave application open

Return to screen:

screen -r 'name'

for example using lynx with screen

Create screen:

screen -S lynx lynx

Ctrl+a, d =exit

later you can return with:

screen -r lynx

Why is my xlabel cut off in my matplotlib plot?

Use:

import matplotlib.pyplot as plt

plt.gcf().subplots_adjust(bottom=0.15)

to make room for the label.

Edit:

Since i gave the answer, matplotlib has added the tight_layout() function. So i suggest to use it:

plt.tight_layout()

should make room for the xlabel.

How do I convert date/time from 24-hour format to 12-hour AM/PM?

Use smaller h

// 24 hrs 
H:i 
// output 14:20

// 12 hrs 
h:i 
// output 2:20

Import existing source code to GitHub

Create your repository in git hub

Allow to track your project by GIT

  1. using CMD go to folder where your project file is kept->cd /automation/xyz/codebase check for git intialization with command git status If you get this error message: fatal: Not a git repository (or any of the parent directories): .git, that means the folder you are currently in is not being tracked by git. In that case, initialize git inside your project folder by typing git init, then going through the process of adding and committing your project.

If you get another error message, read carefully what it says. Is it saying git isn't installed on your computer by saying that the word 'git' is not recognized? Is it saying that you're already in a folder or sub-folder where git is initialized? Google your error and/or output to understand it, and to figure out how to fix it.

now run following command

#

echo "your git hub repository name" >> README.md git init git add README.md git commit -m "first commit" git remote add origin https:// #

above block you will get when first time you are opening your repository

If error occurs or nothing happens after last command run"git push -u origin master" dont worry

go to folder where code is available and through git extention push it to git [URL], branch

If you can decode JWT, how are they secure?

Let's discuss from the very beginning:

JWT is a very modern, simple and secure approach which extends for Json Web Tokens. Json Web Tokens are a stateless solution for authentication. So there is no need to store any session state on the server, which of course is perfect for restful APIs. Restful APIs should always be stateless, and the most widely used alternative to authentication with JWTs is to just store the user's log-in state on the server using sessions. But then of course does not follow the principle that says that restful APIs should be stateless and that's why solutions like JWT became popular and effective.

So now let's know how authentication actually works with Json Web Tokens. Assuming we already have a registered user in our database. So the user's client starts by making a post request with the username and the password, the application then checks if the user exists and if the password is correct, then the application will generate a unique Json Web Token for only that user.

The token is created using a secret string that is stored on a server. Next, the server then sends that JWT back to the client which will store it either in a cookie or in local storage. enter image description here

Just like this, the user is authenticated and basically logged into our application without leaving any state on the server.

So the server does in fact not know which user is actually logged in, but of course, the user knows that he's logged in because he has a valid Json Web Token which is a bit like a passport to access protected parts of the application.

So again, just to make sure you got the idea. A user is logged in as soon as he gets back his unique valid Json Web Token which is not saved anywhere on the server. And so this process is therefore completely stateless.

Then, each time a user wants to access a protected route like his user profile data, for example. He sends his Json Web Token along with a request, so it's a bit like showing his passport to get access to that route.

Once the request hits the server, our app will then verify if the Json Web Token is actually valid and if the user is really who he says he is, well then the requested data will be sent to the client and if not, then there will be an error telling the user that he's not allowed to access that resource. enter image description here

All this communication must happen over https, so secure encrypted Http in order to prevent that anyone can get access to passwords or Json Web Tokens. Only then we have a really secure system.

enter image description here

So a Json Web Token looks like left part of this screenshot which was taken from the JWT debugger at jwt.io. So essentially, it's an encoding string made up of three parts. The header, the payload and the signature Now the header is just some metadata about the token itself and the payload is the data that we can encode into the token, any data really that we want. So the more data we want to encode here the bigger the JWT. Anyway, these two parts are just plain text that will get encoded, but not encrypted.

So anyone will be able to decode them and to read them, we cannot store any sensitive data in here. But that's not a problem at all because in the third part, so in the signature, is where things really get interesting. The signature is created using the header, the payload, and the secret that is saved on the server.

And this whole process is then called signing the Json Web Token. The signing algorithm takes the header, the payload, and the secret to create a unique signature. So only this data plus the secret can create this signature, all right? Then together with the header and the payload, these signature forms the JWT, which then gets sent to the client. enter image description here

Once the server receives a JWT to grant access to a protected route, it needs to verify it in order to determine if the user really is who he claims to be. In other words, it will verify if no one changed the header and the payload data of the token. So again, this verification step will check if no third party actually altered either the header or the payload of the Json Web Token.

So, how does this verification actually work? Well, it is actually quite straightforward. Once the JWT is received, the verification will take its header and payload, and together with the secret that is still saved on the server, basically create a test signature.

But the original signature that was generated when the JWT was first created is still in the token, right? And that's the key to this verification. Because now all we have to do is to compare the test signature with the original signature. And if the test signature is the same as the original signature, then it means that the payload and the header have not been modified. enter image description here

Because if they had been modified, then the test signature would have to be different. Therefore in this case where there has been no alteration of the data, we can then authenticate the user. And of course, if the two signatures are actually different, well, then it means that someone tampered with the data. Usually by trying to change the payload. But that third party manipulating the payload does of course not have access to the secret, so they cannot sign the JWT. So the original signature will never correspond to the manipulated data. And therefore, the verification will always fail in this case. And that's the key to making this whole system work. It's the magic that makes JWT so simple, but also extremely powerful.

C# Wait until condition is true

At least you can change your loop from a busy-wait to a slow poll. For example:

    while (!isExcelInteractive())
    {
        Console.WriteLine("Excel is busy");
        await Task.Delay(25);
    }

MySQL ORDER BY rand(), name ASC

Use a subquery:

SELECT * FROM 
(
    SELECT * FROM users ORDER BY rand() LIMIT 20
) T1
ORDER BY name 

The inner query selects 20 users at random and the outer query orders the selected users by name.

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

You haven't put the shared library in a location where the loader can find it. look inside the /usr/local/opencv and /usr/local/opencv2 folders and see if either of them contains any shared libraries (files beginning in lib and usually ending in .so). when you find them, create a file called /etc/ld.so.conf.d/opencv.conf and write to it the paths to the folders where the libraries are stored, one per line.

for example, if the libraries were stored under /usr/local/opencv/libopencv_core.so.2.4 then I would write this to my opencv.conf file:

/usr/local/opencv/

Then run

sudo ldconfig -v

If you can't find the libraries, try running

sudo updatedb && locate libopencv_core.so.2.4

in a shell. You don't need to run updatedb if you've rebooted since compiling OpenCV.

References:

About shared libraries on Linux: http://www.eyrie.org/~eagle/notes/rpath.html

About adding the OpenCV shared libraries: http://opencv.willowgarage.com/wiki/InstallGuide_Linux

How can I pipe stderr, and not stdout?

I just came up with a solution for sending stdout to one command and stderr to another, using named pipes.

Here goes.

mkfifo stdout-target
mkfifo stderr-target
cat < stdout-target | command-for-stdout &
cat < stderr-target | command-for-stderr &
main-command 1>stdout-target 2>stderr-target

It's probably a good idea to remove the named pipes afterward.

How to put a horizontal divisor line between edit text's in a activity

For only one line, you need

...
<View android:id="@+id/primerdivisor"
android:layout_height="2dp"
android:layout_width="fill_parent"
android:background="#ffffff" /> 
...

Monitor the Graphics card usage

From Unix.SE: A simple command-line utility called gpustat now exists: https://github.com/wookayin/gpustat.

It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi.

Why was the name 'let' chosen for block-scoped variable declarations in JavaScript?

I guess it follows mathematical tradition. In mathematics, it is often said "let x be arbitrary real number" or like that.

Correct way of getting Client's IP Addresses from http.Request

This is how I come up with the IP

func ReadUserIP(r *http.Request) string {
    IPAddress := r.Header.Get("X-Real-Ip")
    if IPAddress == "" {
        IPAddress = r.Header.Get("X-Forwarded-For")
    }
    if IPAddress == "" {
        IPAddress = r.RemoteAddr
    }
    return IPAddress
}
  • X-Real-Ip - fetches first true IP (if the requests sits behind multiple NAT sources/load balancer)

  • X-Forwarded-For - if for some reason X-Real-Ip is blank and does not return response, get from X-Forwarded-For

  • Remote Address - last resort (usually won't be reliable as this might be the last ip or if it is a naked http request to server ie no load balancer)

What is Model in ModelAndView from Spring MVC?

new ModelAndView("welcomePage", "WelcomeMessage", message);

is shorthand for

ModelAndView mav = new ModelAndView();
mav.setViewName("welcomePage");
mav.addObject("WelcomeMessage", message);

Looking at the code above, you can see the view name is "welcomePage". Your ViewResolver (usually setup in .../WEB-INF/spring-servlet.xml) will translate this into a View. The last line of the code sets an attribute in your model (addObject("WelcomeMessage", message)). That's where the model comes into play.

How to divide two columns?

Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.

e.g. if you do this:

SELECT 1 / 2

you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.

e.g.

SELECT CAST(1 AS DECIMAL) / 2

gives 0.500000

SUM OVER PARTITION BY

You could have used DISTINCT or just remove the PARTITION BY portions and use GROUP BY:

SELECT BrandId
       ,SUM(ICount)
       ,TotalICount = SUM(ICount) OVER ()    
       ,Percentage = SUM(ICount) OVER ()*1.0 / SUM(ICount) 
FROM Table 
WHERE DateId  = 20130618
GROUP BY BrandID

Not sure why you are dividing the total by the count per BrandID, if that's a mistake and you want percent of total then reverse those bits above to:

SELECT BrandId
           ,SUM(ICount)
           ,TotalICount = SUM(ICount) OVER ()    
           ,Percentage = SUM(ICount)*1.0 / SUM(ICount) OVER () 
    FROM Table 
    WHERE DateId  = 20130618
    GROUP BY BrandID

How to remove old Docker containers

If you want to remove all containers then use

docker container prune

This command will remove all containers

Why not clean whole docker system with

docker system prune

Do checkbox inputs only post data if they're checked?

I have a page (form) that dynamically generates checkbox so these answers have been a great help. My solution is very similar to many here but I can't help thinking it is easier to implement.

First I put a hidden input box in line with my checkbox , i.e.

 <td><input class = "chkhide" type="hidden" name="delete_milestone[]" value="off"/><input type="checkbox" name="delete_milestone[]"   class="chk_milestone" ></td>

Now if all the checkboxes are un-selected then values returned by the hidden field will all be off.

For example, here with five dynamically inserted checkboxes, the form POSTS the following values:

  'delete_milestone' => 
array (size=7)
  0 => string 'off' (length=3)
  1 => string 'off' (length=3)
  2 => string 'off' (length=3)
  3 => string 'on' (length=2)
  4 => string 'off' (length=3)
  5 => string 'on' (length=2)
  6 => string 'off' (length=3)

This shows that only the 3rd and 4th checkboxes are on or checked.

In essence the dummy or hidden input field just indicates that everything is off unless there is an "on" below the off index, which then gives you the index you need without a single line of client side code.

.

Can I create view with parameter in MySQL?

CREATE VIEW MyView AS
   SELECT Column, Value FROM Table;


SELECT Column FROM MyView WHERE Value = 1;

Is the proper solution in MySQL, some other SQLs let you define Views more exactly.

Note: Unless the View is very complicated, MySQL will optimize this just fine.

How can I pair socks from a pile efficiently?

In order to say how efficient it is to pair socks from a pile, we have to define the machine first, because the pairing isn't done whether by a turing nor by a random access machine, which are normally used as the basis for an algorithmic analysis.

The machine

The machine is an abstraction of a the real world element called human being. It is able to read from the environment via a pair of eyes. And our machine model is able to manipulate the environment by using 2 arms. Logical and arithmetic operations are calculated using our brain (hopefully ;-)).

We also have to consider the intrinsic runtime of the atomic operations that can be carried out with these instruments. Due to physical constraints, operations which are carried out by an arm or eye have non constant time complexity. This is because we can't move an endlessly large pile of socks with an arm nor can an eye see the top sock on an endlessly large pile of socks.

However mechanical physics give us some goodies as well. We are not limited to move at most one sock with an arm. We can move a whole couple of them at once.

So depending on the previous analysis following operations should be used in descending order:

  • logical and arithmetic operations
  • environmental reads
  • environmental modifications

We can also make use of the fact that people only have a very limited amount of socks. So an environmental modification can involve all socks in the pile.

The algorithm

So here is my suggestion:

  1. Spread all socks in the pile over the floor.
  2. Find a pair by looking at the socks on the floor.
  3. Repeat from 2 until no pair can be made.
  4. Repeat from 1 until there are no socks on the floor.

Operation 4 is necessary, because when spreading socks over the floor some socks may hide others. Here is the analysis of the algorithm:

The analysis

The algorithm terminates with high probability. This is due to the fact that one is unable to find pairs of socks in step number 2.

For the following runtime analysis of pairing n pairs of socks, we suppose that at least half of the 2n socks aren't hidden after step 1. So in the average case we can find n/2 pairs. This means that the loop is step 4 is executed O(log n) times. Step 2 is executed O(n^2) times. So we can conclude:

  • The algorithm involves O(ln n + n) environmental modifications (step 1 O(ln n) plus picking every pair of sock from the floor)
  • The algorithm involves O(n^2) environmental reads from step 2
  • The algorithm involves O(n^2) logical and arithmetic operations for comparing a sock with another in step 2

So we have a total runtime complexity of O(r*n^2 + w*(ln n + n)) where r and w are the factors for environmental read and environmental write operations respectively for a reasonable amount of socks. The cost of the logical and arithmetical operations are omitted, because we suppose that it takes a constant amount of logical and arithmetical operations to decide whether 2 socks belong to the same pair. This may not be feasible in every scenario.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

your column value is already in database table it means your table column is Unique you should change your value and try again

What are the main differences between JWT and OAuth authentication?

JWT (JSON Web Tokens)- It is just a token format. JWT tokens are JSON encoded data structures contains information about issuer, subject (claims), expiration time etc. It is signed for tamper proof and authenticity and it can be encrypted to protect the token information using symmetric or asymmetric approach. JWT is simpler than SAML 1.1/2.0 and supported by all devices and it is more powerful than SWT(Simple Web Token).

OAuth2 - OAuth2 solve a problem that user wants to access the data using client software like browse based web apps, native mobile apps or desktop apps. OAuth2 is just for authorization, client software can be authorized to access the resources on-behalf of end user using access token.

OpenID Connect - OpenID Connect builds on top of OAuth2 and add authentication. OpenID Connect add some constraint to OAuth2 like UserInfo Endpoint, ID Token, discovery and dynamic registration of OpenID Connect providers and session management. JWT is the mandatory format for the token.

CSRF protection - You don't need implement the CSRF protection if you do not store token in the browser's cookie.

Convert base-2 binary number string to int

If you are using python3.6 or later you can use f-string to do the conversion:

Binary to decimal:

>>> print(f'{0b1011010:#0}')
90

>>> bin_2_decimal = int(f'{0b1011010:#0}')
>>> bin_2_decimal
90

binary to octal hexa and etc.

>>> f'{0b1011010:#o}'
'0o132'  # octal

>>> f'{0b1011010:#x}'
'0x5a'   # hexadecimal

>>> f'{0b1011010:#0}'
'90'     # decimal

Pay attention to 2 piece of information separated by colon.

In this way, you can convert between {binary, octal, hexadecimal, decimal} to {binary, octal, hexadecimal, decimal} by changing right side of colon[:]

:#b -> converts to binary
:#o -> converts to octal
:#x -> converts to hexadecimal 
:#0 -> converts to decimal as above example

Try changing left side of colon to have octal/hexadecimal/decimal.

How can I search for a commit message on GitHub?

From the help page on searching code, it seems that this isn't yet possible.

You can search for text in your repository, including the ability to choose files or paths to search in, but you can't specify that you want to search in commits.

Maybe suggest this to them?

How to access nested elements of json object using getJSONArray method

I'm also faced with this issue. So I solved with recursion. Maybe it will be helpfull. I created method.I used org.json library.

    public static JSONObject function(JSONObject obj, String keyMain, String newValue) throws Exception {
    // We need to know keys of Jsonobject
    Iterator iterator = obj.keys();
    String key = null;
    while (iterator.hasNext()) {
        key = (String) iterator.next();
        // if object is just string we change value in key
        if ((obj.optJSONArray(key)==null) && (obj.optJSONObject(key)==null)) {
            if ((key.equals(keyMain)) && (obj.get(key).toString().equals(valueMain))) {
                // put new value
                obj.put(key, newValue);
                return obj;
            }
        }

        // if it's jsonobject
        if (obj.optJSONObject(key) != null) {
            function(obj.getJSONObject(key), keyMain, valueMain, newValue);
        }

        // if it's jsonarray
        if (obj.optJSONArray(key) != null) {
            JSONArray jArray = obj.getJSONArray(key);
            for (int i=0;i<jArray.length();i++) {
                    function(jArray.getJSONObject(i), keyMain, valueMain, newValue);
            }
        }
    }
    return obj;
}

if you have questions, I can explain...

push object into array

can be done like this too.

       let data_array = [];
    
       let my_object = {}; 

       my_object.name = "stack";
       my_object.age = 20;
       my_object.hair_color = "red";
       my_object.eye_color = "green";
        
       data_array.push(my_object);

Get latest from Git branch

If you have forked a repository fro Delete your forked copy and fork it again from master.

Which language uses .pde extension?

This code is from Processing.org an open source Java based IDE. You can find it Processing.org. The Arduino IDE also uses this extension, although they run on a hardware board.

EDIT - And yes it is C syntax, used mostly for art or live media presentations.

How can I get a Dialog style activity window to fill the screen?

You may add this values to your style android:windowMinWidthMajor and android:windowMinWidthMinor

<style name="Theme_Dialog" parent="android:Theme.Holo.Dialog">
    ...
    <item name="android:windowMinWidthMajor">97%</item>
    <item name="android:windowMinWidthMinor">97%</item>
</style>

Delete sql rows where IDs do not have a match from another table

Using LEFT JOIN/IS NULL:

DELETE b FROM BLOB b 
  LEFT JOIN FILES f ON f.id = b.fileid 
      WHERE f.id IS NULL

Using NOT EXISTS:

DELETE FROM BLOB 
 WHERE NOT EXISTS(SELECT NULL
                    FROM FILES f
                   WHERE f.id = fileid)

Using NOT IN:

DELETE FROM BLOB
 WHERE fileid NOT IN (SELECT f.id 
                        FROM FILES f)

Warning

Whenever possible, perform DELETEs within a transaction (assuming supported - IE: Not on MyISAM) so you can use rollback to revert changes in case of problems.

Modify tick label text

One can also do this with pylab and xticks

import matplotlib
import matplotlib.pyplot as plt
x = [0,1,2]
y = [90,40,65]
labels = ['high', 'low', 37337]
plt.plot(x,y, 'r')
plt.xticks(x, labels, rotation='vertical')
plt.show()

http://matplotlib.org/examples/ticks_and_spines/ticklabels_demo_rotation.html

Return back to MainActivity from another activity

Here's why you saw the menu with the code you listed in your onClick method:

You were creating an Intent with the constructor that takes a string for the action parameter of the Intent's IntentFilter. You passed "android.intent.action.MAIN" as the argument to that constructor, which specifies that the Intent can be satisfied by any Activity with an IntentFilter including <action="android.intent.action.MAIN">.

When you called startActivity with that Intent, you effectively told the Android OS to go find an Activity (in any app installed on the system) that specifies the android.intent.action.MAIN action. When there are multiple Activities that qualify (and there are in this case since every app will have a main Activity with an IntentFilter including the "android.intent.action.MAIN" action), the OS presents a menu to let the user choose which app to use.

As to the question of how to get back to your main activity, as with most things, it depends on the specifics of your app. While the accepted answer probably worked in your case, I don't think it's the best solution, and it's probably encouraging you to use a non-idiomatic UI in your Android app. If your Button's onClick() method contains only a call to finish() then you should most likely remove the Button from the UI and just let the user push the hardware/software back button, which has the same functionality and is idiomatic for Android. (You'll often see back Buttons used to emulate the behavior of an iOS UINavigationController navigationBar which is discouraged in Android apps).

If your main activity launches a stack of Activities and you want to provide an easy way to get back to the main activity without repeatedly pressing the back button, then you want to call startActivity after setting the flag Intent.FLAG_ACTIVITY_CLEAR_TOP which will close all the Activities in the call stack which are above your main activity and bring your main activity to the top of the call stack. See below (assuming your main activity subclass is called MainActivity:

btnReturn1.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Intent i=new Intent(this, MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
    }
)};

How to deal with a slow SecureRandom generator?

If your hardware supports it try using Java RdRand Utility of which I'm the author.

Its based on Intel's RDRAND instruction and is about 10 times faster than SecureRandom and no bandwidth issues for large volume implementation.


Note that this implementation only works on those CPU's that provide the instruction (i.e. when the rdrand processor flag is set). You need to explicitly instantiate it through the RdRandRandom() constructor; no specific Provider has been implemented.

Angular 5 Reactive Forms - Radio Button Group

IF you want to derive usg Boolean true False need to add "[]" around value

<form [formGroup]="form">
  <input type="radio" [value]=true formControlName="gender" >Male
  <input type="radio" [value]=false formControlName="gender">Female
</form>

How to inject Javascript in WebBrowser control?

I believe the most simple method to inject Javascript in a WebBrowser Control HTML Document from c# is to invoke the "execScript" method with the code to be injected as argument.

In this example the javascript code is injected and executed at global scope:

var jsCode="alert('hello world from injected code');";
WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" });

If you want to delay execution, inject functions and call them after:

var jsCode="function greet(msg){alert(msg);};";
WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" });
...............
WebBrowser.Document.InvokeScript("greet",new object[] {"hello world"});

This is valid for Windows Forms and WPF WebBrowser controls.

This solution is not cross browser because "execScript" is defined only in IE and Chrome. But the question is about Microsoft WebBrowser controls and IE is the only one supported.

For a valid cross browser method to inject javascript code, create a Function object with the new Keyword. This example creates an anonymous function with injected code and executes it (javascript implements closures and the function has access to global space without local variable pollution).

var jsCode="alert('hello world');";
(new Function(code))();

Of course, you can delay execution:

var jsCode="alert('hello world');";
var inserted=new Function(code);
.................
inserted();

Hope it helps

Generate an integer sequence in MySQL

There is no sequence number generator (CREATE SEQUENCE) in MySQL. Closest thing is AUTO_INCREMENT, which can help you construct the table.

Uploading files to file server using webclient class

Just use

File.Copy(filepath, "\\\\192.168.1.28\\Files");

A windows fileshare exposed via a UNC path is treated as part of the file system, and has nothing to do with the web.

The credentials used will be that of the ASP.NET worker process, or any impersonation you've enabled. If you can tweak those to get it right, this can be done.

You may run into problems because you are using the IP address instead of the server name (windows trust settings prevent leaving the domain - by using IP you are hiding any domain details). If at all possible, use the server name!

If this is not on the same windows domain, and you are trying to use a different domain account, you will need to specify the username as "[domain_or_machine]\[username]"

If you need to specify explicit credentials, you'll need to look into coding an impersonation solution.

Gradle store on local file system

It took me a while to realize this, hence the additional answer. Hopefully it can save folks time. Note that if you are running sudo gradle the dependencies may not be in your home directory, even if sudo echo $HOME returns /Users/<my-non-root-user>/. On my Mac, Gradle was caching the dependencies in /private/var/root/.gradle/caches/.

Is there an easy way to attach source in Eclipse?

Another option is to right click on your jar file which would be under (Your Project)->Referenced Libraries->(your jar) and click on properties. Then click on Java Source Attachment. And then in location path put in the location for your source jar file.

This is just another approach to attaching your source file.

Converting milliseconds to a date (jQuery/JavaScript)

Try using this code:

var milisegundos = parseInt(data.replace("/Date(", "").replace(")/", ""));
var newDate = new Date(milisegundos).toLocaleDateString("en-UE");

Enjoy it!

cannot open shared object file: No such file or directory

sudo ldconfig

ldconfig creates the necessary links and cache to the most recent shared libraries found in the directories specified on the command line, in the file /etc/ld.so.conf, and in the trusted directories (/lib and /usr/lib).

Generally package manager takes care of this while installing the new library, but not always (specially when you install library with cmake).

And if the output of this is empty

$ echo $LD_LIBRARY_PATH

Please set the default path

$ LD_LIBRARY_PATH=/usr/local/lib

How to get user name using Windows authentication in asp.net?

Username you get like this:

var userName = HttpContext.Current.Request.LogonUserIdentity?.Name;

Reversing a linked list in Java, recursively

I got half way through (till null, and one node as suggested by plinth), but lost track after making recursive call. However, after reading the post by plinth, here is what I came up with:

Node reverse(Node head) {
  // if head is null or only one node, it's reverse of itself.
  if ( (head==null) || (head.next == null) ) return head;

  // reverse the sub-list leaving the head node.
  Node reverse = reverse(head.next);

  // head.next still points to the last element of reversed sub-list.
  // so move the head to end.
  head.next.next = head;

  // point last node to nil, (get rid of cycles)
  head.next = null;
  return reverse;
}

psql: FATAL: role "postgres" does not exist

This is the only one that fixed it for me :

createuser -s -U $USER

How to get screen width and height

Try with the following code to get width and height of screen

int widthOfscreen =0;
int heightOfScreen = 0;
DisplayMetrics dm = new DisplayMetrics();
        try {
            ((Activity) context).getWindowManager().getDefaultDisplay()
                    .getMetrics(dm);
        } catch (Exception ex) {
        }
         widthOfscreen  = dm.widthPixels;
heightOfScreen  = dm.heightPixels;

no operator "<<" matches these operands

You're not including the standard <string> header.

You got [un]lucky that some of its pertinent definitions were accidentally made available by the other standard headers that you did include ... but operator<< was not.

Scripting Language vs Programming Language

Scripting languages are programming languages that don't require an explicit compilation step.

For example, in the normal case, you have to compile a C program before you can run it. But in the normal case, you don't have to compile a JavaScript program before you run it. So JavaScript is sometimes called a "scripting" language.

This line is getting more and more blurry since compilation can be so fast with modern hardware and modern compilation techniques. For instance, V8, the JavaScript engine in Google Chrome and used a lot outside of the browser as well, actually compiles the JavaScript code on the fly into machine code, rather than interpreting it. (In fact, V8's an optimizing two-phase compiler.)

Also note that whether a language is a "scripting" language or not can be more about the environment than the language. There's no reason you can't write a C interpreter and use it as a scripting language (and people have). There's also no reason you can't compile JavaScript to machine code and store that in an executable file (and people have). The language Ruby is a good example of this: The original implementation was entirely interpreted (a "scripting" language), but there are now multiple compilers for it.

Some examples of "scripting" languages (e.g., languages that are traditionally used without an explicit compilation step):

  • Lua
  • JavaScript
  • VBScript and VBA
  • Perl

And a small smattering of ones traditionally used with an explicit compilation step:

  • C
  • C++
  • D
  • Java (but note that Java is compiled to bytecode, which is then interpreted and/or recompiled at runtime)
  • Pascal

...and then you have things like Python that sit in both camps: Python is widely used without a compilation step, but the main implementation (CPython) does that by compiling to bytecode on-the-fly and then running the bytecode in a VM, and it can write that bytecode out to files (.pyc, .pyo) for use without recompiling.

That's just a very few, if you do some research you can find a lot more.

How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4

Here I'm basically wrapping a button in a link. The advantage is that you can post to different action methods in the same form.

<a href="Controller/ActionMethod">
    <input type="button" value="Click Me" />
</a>

Adding parameters:

<a href="Controller/ActionMethod?userName=ted">
    <input type="button" value="Click Me" />
</a>

Adding parameters from a non-enumerated Model:

<a href="Controller/[email protected]">
    <input type="button" value="Click Me" />
</a>

You can do the same for an enumerated Model too. You would just have to reference a single entity first. Happy Coding!

JSHint and jQuery: '$' is not defined

Instead of recommending the usual "turn off the JSHint globals", I recommend using the module pattern to fix this problem. It keeps your code "contained" and gives a performance boost (based on Paul Irish's "10 things I learned about Jquery").

I tend to write my module patterns like this:

(function (window) {
    // Handle dependencies
    var angular = window.angular,
        $ = window.$,
        document = window.document;

    // Your application's code
}(window))

You can get these other performance benefits (explained more here):

  • When minifying code, the passed in window object declaration gets minified as well. e.g. window.alert() become m.alert().
  • Code inside the self-executing anonymous function only uses 1 instance of the window object.
  • You cut to the chase when calling in a window property or method, preventing expensive traversal of the scope chain e.g. window.alert() (faster) versus alert() (slower) performance.
  • Local scope of functions through "namespacing" and containment (globals are evil). If you need to break up this code into separate scripts, you can make a submodule for each of those scripts, and have them imported into one main module.

Remove specific commit

There are four ways of doing so:

  • Clean way, reverting but keep in log the revert:

    git revert --strategy resolve <commit>
    
  • Harsh way, remove altogether only the last commit:

    git reset --soft "HEAD^"
    

Note: Avoid git reset --hard as it will also discard all changes in files since the last commit. If --soft does not work, rather try --mixed or --keep.

  • Rebase (show the log of the last 5 commits and delete the lines you don't want, or reorder, or squash multiple commits in one, or do anything else you want, this is a very versatile tool):

    git rebase -i HEAD~5
    

And if a mistake is made:

git rebase --abort
  • Quick rebase: remove only a specific commit using its id:

    git rebase --onto commit-id^ commit-id
    
  • Alternatives: you could also try:

    git cherry-pick commit-id
    
  • Yet another alternative:

    git revert --no-commit
    
  • As a last resort, if you need full freedom of history editing (eg, because git don't allow you to edit what you want to), you can use this very fast open source application: reposurgeon.

Note: of course, all these changes are done locally, you should git push afterwards to apply the changes to the remote. And in case your repo doesn't want to remove the commit ("no fast-forward allowed", which happens when you want to remove a commit you already pushed), you can use git push -f to force push the changes.

Note2: if working on a branch and you need to force push, you should absolutely avoid git push --force because this may overwrite other branches (if you have made changes in them, even if your current checkout is on another branch). Prefer to always specify the remote branch when you force push: git push --force origin your_branch.

View contents of database file in Android Studio

Try this android studio plugin SQLScout. you can see and edit your app database realtime.

SQLScout

Edit: Remember it's a paid plugin, but have 24h trial and suitable for headache time.

Format datetime to YYYY-MM-DD HH:mm:ss in moment.js

_x000D_
_x000D_
const format1 = "YYYY-MM-DD HH:mm:ss"
const format2 = "YYYY-MM-DD"
var date1 = new Date("2020-06-24 22:57:36");
var date2 = new Date();

dateTime1 = moment(date1).format(format1);
dateTime2 = moment(date2).format(format2);

document.getElementById("demo1").innerHTML = dateTime1;
document.getElementById("demo2").innerHTML = dateTime2;
_x000D_
<!DOCTYPE html>
<html>
<body>

<p id="demo1"></p>
<p id="demo2"></p>

<script src="https://momentjs.com/downloads/moment.js"></script>

</body>
</html>
_x000D_
_x000D_
_x000D_

How to define and use function inside Jenkins Pipeline config?

First off, you shouldn't add $ when you're outside of strings ($class in your first function being an exception), so it should be:

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
...

Now, as for your problem; the second function takes two arguments while you're only supplying one argument at the call. Either you have to supply two arguments at the call:

...
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1', null)
    }
}

... or you need to add a default value to the functions' second argument:

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere($projectName)
}

css width: calc(100% -100px); alternative using jquery

Try jQuery animate() method, ex.

$("#divid").animate({'width':perc+'%'});

Java parsing XML document gives "Content not allowed in prolog." error

You are not providing the correct address for the file. You need to provide an address such as C:/Users/xyz/Desktop/myfile.xml

Can't choose class as main class in IntelliJ

The documentation you linked actually has the answer in the link associated with the "Java class located out of the source root." Configure your source and test roots and it should work.

https://www.jetbrains.com/idea/webhelp/configuring-content-roots.html

Since you stated that these are tests you should probably go with them marked as Test Source Root instead of Source Root.

Excel is not updating cells, options > formula > workbook calculation set to automatic

My problem was that excel column was showing me "=concatenate(A1,B1)" instead of it 's value after concatenation.

I added a space after "," like this =concatenate(A1, B1) and it worked.

This is just an example that solved my problem.

Try and let me know if it works for you as well.

Sometimes it works without space as well, but at other times it doesn't.

How to extend an existing JavaScript array with another array, without creating a new array

Super simple, does not count on spread operators or apply, if that's an issue.

b.map(x => a.push(x));

After running some performance tests on this, it's terribly slow, but answers the question in regards to not creating a new array. Concat is significantly faster, even jQuery's $.merge() whoops it.

https://jsperf.com/merge-arrays19b/1

break/exit script

Edit: Seems the OP is running a long script, in that case one only needs to wrap the part of the script after the quality control with

if (n >= 500) {

.... long running code here

}

If breaking out of a function, you'll probably just want return(), either explicitly or implicitly.

For example, an explicit double return

foo <- function(x) {
  if(x < 10) {
    return(NA)
  } else {
    xx <- seq_len(x)
    xx <- cumsum(xx)
  }
  xx ## return(xx) is implied here
}

> foo(5)
[1] 0
> foo(10)
 [1]  1  3  6 10 15 21 28 36 45 55

By return() being implied, I mean that the last line is as if you'd done return(xx), but it is slightly more efficient to leave off the call to return().

Some consider using multiple returns bad style; in long functions, keeping track of where the function exits can become difficult or error prone. Hence an alternative is to have a single return point, but change the return object using the if () else () clause. Such a modification to foo() would be

foo <- function(x) {
  ## out is NA or cumsum(xx) depending on x
  out <- if(x < 10) {
    NA
  } else {
    xx <- seq_len(x)
    cumsum(xx)
  }
  out ## return(out) is implied here
}

> foo(5)
[1] NA
> foo(10)
 [1]  1  3  6 10 15 21 28 36 45 55

How to determine whether a substring is in a different string

If you're looking for more than a True/False, you'd be best suited to use the re module, like:

import re
search="please help me out"
fullstring="please help me out so that I could solve this"
s = re.search(search,fullstring)
print(s.group())

s.group() will return the string "please help me out".

Change background position with jQuery

Here you go:

$(document).ready(function(){
    $('#submenu li').hover(function(){
        $('#carousel').css('background-position', '10px 10px');
    }, function(){
        $('#carousel').css('background-position', '');
    });
});

Is there a replacement for unistd.h for Windows (Visual C)?

MinGW 4.x has unistd.h in \MinGW\include, \MinGW\include\sys and \MinGW\lib\gcc\mingw32\4.6.2\include\ssp

Here is the code for the MinGW version, by Rob Savoye; modified by Earnie Boyd, Danny Smith, Ramiro Polla, Gregory McGarry and Keith Marshall:

/*
 * unistd.h
 *
 * Standard header file declaring MinGW's POSIX compatibility features.
 *
 * $Id: unistd.h,v c3ebd36f8211 2016/02/16 16:05:39 keithmarshall $
 *
 * Written by Rob Savoye <[email protected]>
 * Modified by Earnie Boyd <[email protected]>
 *   Danny Smith <[email protected]>
 *   Ramiro Polla <[email protected]>
 *   Gregory McGarry  <[email protected]>
 *   Keith Marshall  <[email protected]>
 * Copyright (C) 1997, 1999, 2002-2004, 2007-2009, 2014-2016,
 *   MinGW.org Project.
 *
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice, this permission notice, and the following
 * disclaimer shall be included in all copies or substantial portions of
 * the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OF OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */
#ifndef _UNISTD_H
#define _UNISTD_H  1
#pragma GCC system_header

/* All MinGW headers MUST include _mingw.h before anything else,
 * to ensure proper initialization of feature test macros.
 */
#include <_mingw.h>

/* unistd.h maps (roughly) to Microsoft's <io.h>
 * Other headers included by <unistd.h> may be selectively processed;
 * __UNISTD_H_SOURCED__ enables such selective processing.
 */
#define __UNISTD_H_SOURCED__ 1

#include <io.h>
#include <process.h>
#include <getopt.h>

/* These are defined in stdio.h.  POSIX also requires that they
 * are to be consistently defined here; don't guard against prior
 * definitions, as this might conceal inconsistencies.
 */
#define SEEK_SET   0
#define SEEK_CUR   1
#define SEEK_END   2

#if _POSIX_C_SOURCE
/* POSIX process/thread suspension functions; all are supported by a
 * common MinGW API in libmingwex.a, providing for suspension periods
 * ranging from mean values of ~7.5 milliseconds, (see the comments in
 * <time.h>), extending up to a maximum of ~136 years.
 *
 * Note that, whereas POSIX supports early wake-up of any suspended
 * process/thread, in response to a signal, this implementation makes
 * no attempt to emulate this signalling behaviour, (since signals are
 * not well supported by Windows); thus, unless impeded by an invalid
 * argument, this implementation always returns an indication as if
 * the sleeping period ran to completion.
 */
_BEGIN_C_DECLS

__cdecl __MINGW_NOTHROW
int __mingw_sleep( unsigned long, unsigned long );

/* The nanosleep() function provides the most general purpose API for
 * process/thread suspension; it is declared in <time.h>, (where it is
 * accompanied by an in-line implementation), rather than here, and it
 * provides for specification of suspension periods in the range from
 * ~7.5 ms mean, (on WinNT derivatives; ~27.5 ms on Win9x), extending
 * up to ~136 years, (effectively eternity).
 *
 * The usleep() function, and its associated useconds_t type specifier
 * were made obsolete in POSIX.1-2008; declared here, only for backward
 * compatibility, its continued use is not recommended.  (It is limited
 * to specification of suspension periods ranging from ~7.5 ms mean up
 * to a maximum of 999,999 microseconds only).
 */
typedef unsigned long useconds_t __MINGW_ATTRIB_DEPRECATED;
int __cdecl __MINGW_NOTHROW usleep( useconds_t )__MINGW_ATTRIB_DEPRECATED;

#ifndef __NO_INLINE__
__CRT_INLINE __LIBIMPL__(( FUNCTION = usleep ))
int usleep( useconds_t period ){ return __mingw_sleep( 0, 1000 * period ); }
#endif

/* The sleep() function is, perhaps, the most commonly used of all the
 * process/thread suspension APIs; it provides support for specification
 * of suspension periods ranging from 1 second to ~136 years.  (However,
 * POSIX recommends limiting the maximum period to 65535 seconds, to
 * maintain portability to platforms with only 16-bit ints).
 */
unsigned __cdecl __MINGW_NOTHROW sleep( unsigned );

#ifndef __NO_INLINE__
__CRT_INLINE __LIBIMPL__(( FUNCTION = sleep ))
unsigned sleep( unsigned period ){ return __mingw_sleep( period, 0 ); }
#endif


/* POSIX ftruncate() function.
 *
 * Microsoft's _chsize() function is incorrectly described, on MSDN,
 * as a preferred replacement for the POSIX chsize() function.  There
 * never was any such POSIX function; the actual POSIX equivalent is
 * the ftruncate() function.
 */
int __cdecl ftruncate( int, off_t );

#ifndef __NO_INLINE__
__CRT_INLINE __JMPSTUB__(( FUNCTION = ftruncate, REMAPPED = _chsize ))
int ftruncate( int __fd, off_t __length ){ return _chsize( __fd, __length ); }
#endif

_END_C_DECLS

#endif /* _POSIX_C_SOURCE */

#undef __UNISTD_H_SOURCED__
#endif /* ! _UNISTD_H: $RCSfile: unistd.h,v $: end of file */

This file requires the inclusion of _mingw.h, which is as follows:

#ifndef __MINGW_H
/*
 * _mingw.h
 *
 * MinGW specific macros included by ALL mingwrt include files; (this file
 * is part of the MinGW32 runtime library package).
 *
 * $Id: _mingw.h.in,v 7daa0459f602 2016/05/03 17:40:54 keithmarshall $
 *
 * Written by Mumit Khan  <[email protected]>
 * Copyright (C) 1999, 2001-2011, 2014-2016, MinGW.org Project
 *
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */
#define __MINGW_H

/* In previous versions, __MINGW32_VERSION was expressed as a dotted
 * numeric pair, representing major.minor; unfortunately, this doesn't
 * adapt well to the inclusion of a patch-level component, since the
 * major.minor.patch dotted triplet representation is not valid as a
 * numeric entity.  Thus, for this version, we adopt a representation
 * which encodes the version as a long integer value, expressing:
 *
 *   __MINGW32_VERSION = 1,000,000 * major + 1,000 * minor + patch
 *
 * DO NOT EDIT these package version assignments manually; they are
 * derived from the package version specification within configure.ac,
 * whence they are propagated automatically, at package build time.
 */
#define __MINGW32_VERSION           3022001L
#define __MINGW32_MAJOR_VERSION           3
#define __MINGW32_MINOR_VERSION          22
#define __MINGW32_PATCHLEVEL              1

#if __GNUC__ >= 3 && ! defined __PCC__
#pragma GCC system_header
#endif

#ifndef _MSVCRTVER_H
/* Legacy versions of mingwrt use the macro __MSVCRT_VERSION__ to
 * enable evolving features of different MSVCRT.DLL versions.  This
 * usage is no longer recommended, but the __MSVCRT_VERSION__ macro
 * remains useful when a non-freely distributable MSVCRxx.DLL is to
 * be substituted for MSVCRT.DLL; for such usage, the substitute
 * MSVCRxx.DLL may be identified as specified in...
 */
# include <msvcrtver.h>
#endif

/* A better inference than __MSVCRT_VERSION__, of the capabilities
 * supported by the operating system default MSVCRT.DLL, is provided
 * by the Windows API version identification macros.
 */
#include <w32api.h>

/* The following are defined by the user (or by the compiler), to specify how
 * identifiers are imported from a DLL.  All headers should include this first,
 * and then use __DECLSPEC_SUPPORTED to choose between the old ``__imp__name''
 * style or the __MINGW_IMPORT style for declarations.
 *
 * __DECLSPEC_SUPPORTED            Defined if dllimport attribute is supported.
 * __MINGW_IMPORT                  The attribute definition to specify imported
 *                                 variables/functions.
 * _CRTIMP                         As above.  For MS compatibility.
 *
 * Macros to enable MinGW features which deviate from standard MSVC
 * compatible behaviour; these may be specified directly in user code,
 * activated implicitly, (e.g. by specifying _POSIX_C_SOURCE or such),
 * or by inclusion in __MINGW_FEATURES__:
 *
 * __USE_MINGW_ANSI_STDIO          Select a more ANSI C99 compatible
 *                                 implementation of printf() and friends;
 *                                 (users should not set this directly).
 *
 * Other macros:
 *
 * __int64                         define to be long long.  Using a typedef
 *                                 doesn't work for "unsigned __int64"
 *
 *
 * Manifest definitions for flags to control globbing of the command line
 * during application start up, (before main() is called).  The first pair,
 * when assigned as bit flags within _CRT_glob, select the globbing algorithm
 * to be used; (the MINGW algorithm overrides MSCVRT, if both are specified).
 * Prior to mingwrt-3.21, only the MSVCRT option was supported; this choice
 * may produce different results, depending on which particular version of
 * MSVCRT.DLL is in use; (in recent versions, it seems to have become
 * definitively broken, when globbing within double quotes).
 */
#define __CRT_GLOB_USE_MSVCRT__     0x0001

/* From mingwrt-3.21 onward, this should be the preferred choice; it will
 * produce consistent results, regardless of the MSVCRT.DLL version in use.
 */
#define __CRT_GLOB_USE_MINGW__      0x0002

/* When the __CRT_GLOB_USE_MINGW__ flag is set, within _CRT_glob, the
 * following additional options are also available; they are not enabled
 * by default, but the user may elect to enable any combination of them,
 * by setting _CRT_glob to the boolean sum (i.e. logical OR combination)
 * of __CRT_GLOB_USE_MINGW__ and the desired options.
 *
 *    __CRT_GLOB_USE_SINGLE_QUOTE__ allows use of single (apostrophe)
 *                      quoting characters, analogously to
 *                      POSIX usage, as an alternative to
 *                      double quotes, for collection of
 *                      arguments separated by white space
 *                      into a single logical argument.
 *
 *    __CRT_GLOB_BRACKET_GROUPS__   enable interpretation of bracketed
 *                      character groups as POSIX compatible
 *                      globbing patterns, matching any one
 *                      character which is either included
 *                      in, or excluded from the group.
 *
 *    __CRT_GLOB_CASE_SENSITIVE__   enable case sensitive matching for
 *                      globbing patterns; this is default
 *                      behaviour for POSIX, but because of
 *                      the case insensitive nature of the
 *                      MS-Windows file system, it is more
 *                      appropriate to use case insensitive
 *                      globbing as the MinGW default.
 *
 */
#define __CRT_GLOB_USE_SINGLE_QUOTE__   0x0010
#define __CRT_GLOB_BRACKET_GROUPS__ 0x0020
#define __CRT_GLOB_CASE_SENSITIVE__ 0x0040

/* The MinGW globbing algorithm uses the ASCII DEL control code as a marker
 * for globbing characters which were embedded within quoted arguments; (the
 * quotes are stripped away BEFORE the argument is globbed; the globbing code
 * treats the marked character as immutable, and strips out the DEL markers,
 * before storing the resultant argument).  The DEL code is mapped to this
 * function here; DO NOT change it, without rebuilding the runtime.
 */
#define __CRT_GLOB_ESCAPE_CHAR__    (char)(127)


/* Manifest definitions identifying the flag bits, controlling activation
 * of MinGW features, as specified by the user in __MINGW_FEATURES__.
 */
#define __MINGW_ANSI_STDIO__        0x0000000000000001ULL
/*
 * The following three are not yet formally supported; they are
 * included here, to document anticipated future usage.
 */
#define __MINGW_LC_EXTENSIONS__     0x0000000000000050ULL
#define __MINGW_LC_MESSAGES__       0x0000000000000010ULL
#define __MINGW_LC_ENVVARS__        0x0000000000000040ULL


/* Try to avoid problems with outdated checks for GCC __attribute__ support.
 */
#undef __attribute__

#if defined (__PCC__)
#  undef __DECLSPEC_SUPPORTED
# ifndef __MINGW_IMPORT
#  define __MINGW_IMPORT extern
# endif
# ifndef _CRTIMP
#  define _CRTIMP
# endif
# ifndef __cdecl
#  define __cdecl  _Pragma("cdecl")
# endif
# ifndef __stdcall
#  define __stdcall _Pragma("stdcall")
# endif
# ifndef __int64
#  define __int64 long long
# endif
# ifndef __int32
#  define __int32 long
# endif
# ifndef __int16
#  define __int16 short
# endif
# ifndef __int8
#  define __int8 char
# endif
# ifndef __small
#  define __small char
# endif
# ifndef __hyper
#  define __hyper long long
# endif
# ifndef __volatile__
#  define __volatile__ volatile
# endif
# ifndef __restrict__
#  define __restrict__ restrict
# endif
# define NONAMELESSUNION
#elif defined(__GNUC__)
# ifdef __declspec
#  ifndef __MINGW_IMPORT
   /* Note the extern. This is needed to work around GCC's
      limitations in handling dllimport attribute.  */
#   define __MINGW_IMPORT  extern __attribute__((__dllimport__))
#  endif
#  ifndef _CRTIMP
#   ifdef __USE_CRTIMP
#    define _CRTIMP  __attribute__((dllimport))
#   else
#    define _CRTIMP
#   endif
#  endif
#  define __DECLSPEC_SUPPORTED
# else /* __declspec */
#  undef __DECLSPEC_SUPPORTED
#  undef __MINGW_IMPORT
#  ifndef _CRTIMP
#   define _CRTIMP
#  endif
# endif /* __declspec */
/*
 * The next two defines can cause problems if user code adds the
 * __cdecl attribute like so:
 * void __attribute__ ((__cdecl)) foo(void);
 */
# ifndef __cdecl
#  define __cdecl  __attribute__((__cdecl__))
# endif
# ifndef __stdcall
#  define __stdcall __attribute__((__stdcall__))
# endif
# ifndef __int64
#  define __int64 long long
# endif
# ifndef __int32
#  define __int32 long
# endif
# ifndef __int16
#  define __int16 short
# endif
# ifndef __int8
#  define __int8 char
# endif
# ifndef __small
#  define __small char
# endif
# ifndef __hyper
#  define __hyper long long
# endif
#else /* ! __GNUC__ && ! __PCC__ */
# ifndef __MINGW_IMPORT
#  define __MINGW_IMPORT  __declspec(dllimport)
# endif
# ifndef _CRTIMP
#  define _CRTIMP  __declspec(dllimport)
# endif
# define __DECLSPEC_SUPPORTED
# define __attribute__(x) /* nothing */
#endif

#if defined (__GNUC__) && defined (__GNUC_MINOR__)
#define __MINGW_GNUC_PREREQ(major, minor) \
  (__GNUC__ > (major) \
   || (__GNUC__ == (major) && __GNUC_MINOR__ >= (minor)))
#else
#define __MINGW_GNUC_PREREQ(major, minor)  0
#endif

#ifdef __cplusplus
# define __CRT_INLINE    inline
#else
# if __GNUC_STDC_INLINE__
#  define __CRT_INLINE   extern inline __attribute__((__gnu_inline__))
# else
#  define __CRT_INLINE   extern __inline__
# endif
#endif

# ifdef __GNUC__
  /* A special form of __CRT_INLINE is provided; it will ALWAYS request
   * inlining when possible.  Originally specified as _CRTALIAS, this is
   * now deprecated in favour of __CRT_ALIAS, for syntactic consistency
   * with __CRT_INLINE itself.
   */
#  define  _CRTALIAS   __CRT_INLINE __attribute__((__always_inline__))
#  define __CRT_ALIAS  __CRT_INLINE __attribute__((__always_inline__))
# else
#  define  _CRTALIAS   __CRT_INLINE /* deprecated form */
#  define __CRT_ALIAS  __CRT_INLINE /* preferred form */
# endif
/*
 * Each function which is implemented as a __CRT_ALIAS should also be
 * accompanied by an externally visible interface.  The following pair
 * of macros provide a mechanism for implementing this, either as a stub
 * redirecting to an alternative external function, or by compilation of
 * the normally inlined code into free standing object code; each macro
 * provides a way for us to offer arbitrary hints for use by the build
 * system, while remaining transparent to the compiler.
 */
#define __JMPSTUB__(__BUILD_HINT__)
#define __LIBIMPL__(__BUILD_HINT__)

#ifdef __cplusplus
# define __UNUSED_PARAM(x)
#else
# ifdef __GNUC__
#  define __UNUSED_PARAM(x) x __attribute__((__unused__))
# else
#  define __UNUSED_PARAM(x) x
# endif
#endif

#ifdef __GNUC__
#define __MINGW_ATTRIB_NORETURN __attribute__((__noreturn__))
#define __MINGW_ATTRIB_CONST __attribute__((__const__))
#else
#define __MINGW_ATTRIB_NORETURN
#define __MINGW_ATTRIB_CONST
#endif

#if __MINGW_GNUC_PREREQ (3, 0)
#define __MINGW_ATTRIB_MALLOC __attribute__((__malloc__))
#define __MINGW_ATTRIB_PURE __attribute__((__pure__))
#else
#define __MINGW_ATTRIB_MALLOC
#define __MINGW_ATTRIB_PURE
#endif

/* Attribute `nonnull' was valid as of gcc 3.3.  We don't use GCC's
   variadiac macro facility, because variadic macros cause syntax
   errors with  --traditional-cpp.  */
#if  __MINGW_GNUC_PREREQ (3, 3)
#define __MINGW_ATTRIB_NONNULL(arg) __attribute__((__nonnull__(arg)))
#else
#define __MINGW_ATTRIB_NONNULL(arg)
#endif /* GNUC >= 3.3 */

#if  __MINGW_GNUC_PREREQ (3, 1)
#define __MINGW_ATTRIB_DEPRECATED __attribute__((__deprecated__))
#else
#define __MINGW_ATTRIB_DEPRECATED
#endif /* GNUC >= 3.1 */

#if  __MINGW_GNUC_PREREQ (3, 3)
#define __MINGW_NOTHROW __attribute__((__nothrow__))
#else
#define __MINGW_NOTHROW
#endif /* GNUC >= 3.3 */


/* TODO: Mark (almost) all CRT functions as __MINGW_NOTHROW.  This will
allow GCC to optimize away some EH unwind code, at least in DW2 case.  */

/* Activation of MinGW specific extended features:
 */
#ifndef __USE_MINGW_ANSI_STDIO
/* Users should not set this directly; rather, define one (or more)
 * of the feature test macros (tabulated below), or specify any of the
 * compiler's command line options, (e.g. -posix, -ansi, or -std=c...),
 * which cause _POSIX_SOURCE, or __STRICT_ANSI__ to be defined.
 *
 * We must check this BEFORE we specifiy any implicit _POSIX_C_SOURCE,
 * otherwise we would always implicitly choose __USE_MINGW_ANSI_STDIO,
 * even if none of these selectors are specified explicitly...
 */
# if   defined __STRICT_ANSI__  ||  defined _ISOC99_SOURCE \
   ||  defined _POSIX_SOURCE    ||  defined _POSIX_C_SOURCE \
   ||  defined _XOPEN_SOURCE    ||  defined _XOPEN_SOURCE_EXTENDED \
   ||  defined _GNU_SOURCE      ||  defined _BSD_SOURCE \
   ||  defined _SVID_SOURCE
   /*
    * but where any of these source code qualifiers are specified,
    * then assume ANSI I/O standards are preferred over Microsoft's...
    */
#  define __USE_MINGW_ANSI_STDIO    1
# else
   /* otherwise use whatever __MINGW_FEATURES__ specifies...
    */
#  define __USE_MINGW_ANSI_STDIO    (__MINGW_FEATURES__ & __MINGW_ANSI_STDIO__)
# endif
#endif

#ifndef _POSIX_C_SOURCE
 /* Users may define this, either directly or indirectly, to explicitly
  * enable a particular level of visibility for the subset of those POSIX
  * features which are supported by MinGW; (notice that this offers no
  * guarantee that any particular POSIX feature will be supported).
  */
# if defined _XOPEN_SOURCE
  /* Specifying this is the preferred method for setting _POSIX_C_SOURCE;
   * (POSIX defines an explicit relationship to _XOPEN_SOURCE).  Note that
   * any such explicit setting will augment the set of features which are
   * available to any compilation unit, even if it seeks to be strictly
   * ANSI-C compliant.
   */
#  if _XOPEN_SOURCE < 500
#   define _POSIX_C_SOURCE  1L      /* POSIX.1-1990 / SUSv1 */

#  elif _XOPEN_SOURCE < 600
#   define _POSIX_C_SOURCE  199506L /* POSIX.1-1996 / SUSv2 */

#  elif _XOPEN_SOURCE < 700
#   define _POSIX_C_SOURCE  200112L /* POSIX.1-2001 / SUSv3 */

#  else
#   define _POSIX_C_SOURCE  200809L /* POSIX.1-2008 / SUSv4 */
#  endif

# elif defined _GNU_SOURCE || defined _BSD_SOURCE || ! defined __STRICT_ANSI__
  /*
   * No explicit level of support has been specified; implicitly grant
   * the most comprehensive level to any compilation unit which requests
   * either GNU or BSD feature support, or does not seek to be strictly
   * ANSI-C compliant.
   */
#  define _POSIX_C_SOURCE  200809L

# elif defined _POSIX_SOURCE
  /* Now formally deprecated by POSIX, some old code may specify this;
   * it will enable a minimal level of POSIX support, in addition to the
   * limited feature set enabled for strict ANSI-C conformity.
   */
#  define _POSIX_C_SOURCE  1L
# endif
#endif

#ifndef _ISOC99_SOURCE
 /* libmingwex.a provides free-standing implementations for many of the
  * functions which were introduced in C99; MinGW headers do not expose
  * prototypes for these, unless this feature test macro is defined, by
  * the user, or implied by other standards...
  */
# if __STDC_VERSION__ >= 199901L || _POSIX_C_SOURCE >= 200112L
#  define _ISOC99_SOURCE  1
# endif
#endif

#if ! defined _MINGW32_SOURCE_EXTENDED && ! defined __STRICT_ANSI__
/*
 * Enable mingw32 extensions by default, except when __STRICT_ANSI__
 * conformity mode has been enabled.
 */
# define _MINGW32_SOURCE_EXTENDED  1
#endif

#endif /* __MINGW_H: $RCSfile: _mingw.h.in,v $: end of file */

The rest of the includes should be standard to your environment.

How can you tell when a layout has been drawn?

An alternative to the usual methods is to hook into the drawing of the view.

OnPreDrawListener is called many times when displaying a view, so there is no specific iteration where your view has valid measured width or height. This requires that you continually verify (view.getMeasuredWidth() <= 0) or set a limit to the number of times you check for a measuredWidth greater than zero.

There is also a chance that the view will never be drawn, which may indicate other problems with your code.

final View view = [ACQUIRE REFERENCE]; // Must be declared final for inner class
ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    @Override
    public boolean onPreDraw() {
        if (view.getMeasuredWidth() > 0) {     
            view.getViewTreeObserver().removeOnPreDrawListener(this);
            int width = view.getMeasuredWidth();
            int height = view.getMeasuredHeight();
            //Do something with width and height here!
        }
        return true; // Continue with the draw pass, as not to stop it
    }
});

Open firewall port on CentOS 7

Hello in Centos 7 firewall-cmd. Yes correct if you use firewall-cmd --zone=public --add-port=2888/tcp but if you reload firewal firewall-cmd --reload

your config not will be save

you need to add key

firewall-cmd --permanent --zone=public --add-port=2888/tcp

Tomcat Server Error - Port 8080 already in use

Open CMD or Powershell in Administrator mode, then run...

netstat -ab

The output should be able to point you in the direction of which process is holding port 8080. Entry may likely be 127.0.0.1:8080 You may still have a running instance of Tomcat at port 8080.

You can either use Stop-Process in PowerShell or taskKill in CMD to stop that process and should be able to execute the program at that point.

Converting from IEnumerable to List

I use an extension method for this. My extension method first checks to see if the enumeration is null and if so creates an empty list. This allows you to do a foreach on it without explicitly having to check for null.

Here is a very contrived example:

IEnumerable<string> stringEnumerable = null;
StringBuilder csv = new StringBuilder();
stringEnumerable.ToNonNullList().ForEach(str=> csv.Append(str).Append(","));

Here is the extension method:

public static List<T> ToNonNullList<T>(this IEnumerable<T> obj)
{
    return obj == null ? new List<T>() : obj.ToList();
}

String to LocalDate

java.time

Since Java 1.8, you can achieve this without an extra library by using the java.time classes. See Tutorial.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd");
formatter = formatter.withLocale( putAppropriateLocaleHere );  // Locale specifies human language for translating, and cultural norms for lowercase/uppercase and abbreviations and such. Example: Locale.US or Locale.CANADA_FRENCH
LocalDate date = LocalDate.parse("2005-nov-12", formatter);

The syntax is nearly the same though.

In Python, what happens when you import inside of a function?

It imports once when the function is called for the first time.

I could imagine doing it this way if I had a function in an imported module that is used very seldomly and is the only one requiring the import. Looks rather far-fetched, though...

How can I multiply and divide using only bit shifting and adding?

To multiply in terms of adding and shifting you want to decompose one of the numbers by powers of two, like so:

21 * 5 = 10101_2 * 101_2             (Initial step)
       = 10101_2 * (1 * 2^2  +  0 * 2^1  +  1 * 2^0)
       = 10101_2 * 2^2 + 10101_2 * 2^0 
       = 10101_2 << 2 + 10101_2 << 0 (Decomposed)
       = 10101_2 * 4 + 10101_2 * 1
       = 10101_2 * 5
       = 21 * 5                      (Same as initial expression)

(_2 means base 2)

As you can see, multiplication can be decomposed into adding and shifting and back again. This is also why multiplication takes longer than bit shifts or adding - it's O(n^2) rather than O(n) in the number of bits. Real computer systems (as opposed to theoretical computer systems) have a finite number of bits, so multiplication takes a constant multiple of time compared to addition and shifting. If I recall correctly, modern processors, if pipelined properly, can do multiplication just about as fast as addition, by messing with the utilization of the ALUs (arithmetic units) in the processor.

Finding the number of days between two dates

Well, the selected answer is not the most correct one because it will fail outside UTC. Depending on the timezone (list) there could be time adjustments creating days "without" 24 hours, and this will make the calculation (60*60*24) fail.

Here it is an example of it:

date_default_timezone_set('europe/lisbon');
$time1 = strtotime('2016-03-27');
$time2 = strtotime('2016-03-29');
echo floor( ($time2-$time1) /(60*60*24));
 ^-- the output will be **1**

So the correct solution will be using DateTime

date_default_timezone_set('europe/lisbon');
$date1 = new DateTime("2016-03-27");
$date2 = new DateTime("2016-03-29");

echo $date2->diff($date1)->format("%a");
 ^-- the output will be **2**

Copy Image from Remote Server Over HTTP

This answer helped to me download image from server to client side.

<a download="original_file.jpg" href="file/path.jpg">
  <img src="file/path.jpg" class="img-responsive" width="600" />
</a>

Python + Django page redirect

Beware. I did this on a development server and wanted to change it later.

I had to clear my caches to change it. In order to avoid this head-scratching in the future, I was able to make it temporary like so:

from django.views.generic import RedirectView

url(r'^source$', RedirectView.as_view(permanent=False, 
                                      url='/dest/')),

How to order results with findBy() in Doctrine

$ens = $em->getRepository('AcmeBinBundle:Marks')
              ->findBy(
                 array(), 
                 array('id' => 'ASC')
               );

Python write line by line to a text file

Well, the problem you have is wrong line ending/encoding for notepad. Notepad uses Windows' line endings - \r\n and you use \n.

Create SQL identity as primary key?

Simple change to syntax is all that is needed:

 create table ImagenesUsuario (
   idImagen int not null identity(1,1) primary key
 )

By explicitly using the "constraint" keyword, you can give the primary key constraint a particular name rather than depending on SQL Server to auto-assign a name:

 create table ImagenesUsuario (
   idImagen int not null identity(1,1) constraint pk_ImagenesUsario primary key
 )

Add the "CLUSTERED" keyword if that makes the most sense based on your use of the table (i.e., the balance of searches for a particular idImagen and amount of writing outweighs the benefits of clustering the table by some other index).

Install Windows Service created in Visual Studio

Here is an alternate way to make the installer and get rid of that error message. Also it seems that VS2015 express does not have the "Add Installer" menu item.

You simply need to create a class and add the below code and add the reference System.Configuration.Install.dll.

using System.Configuration.Install;
using System.ServiceProcess;
using System.ComponentModel;


namespace SAS
{
    [RunInstaller(true)]
    public class MyProjectInstaller : Installer
    {
        private ServiceInstaller serviceInstaller1;
        private ServiceProcessInstaller processInstaller;

        public MyProjectInstaller()
        {
            // Instantiate installer for process and service.
            processInstaller = new ServiceProcessInstaller();
            serviceInstaller1 = new ServiceInstaller();

            // The service runs under the system account.
            processInstaller.Account = ServiceAccount.LocalSystem;

            // The service is started manually.
            serviceInstaller1.StartType = ServiceStartMode.Manual;

            // ServiceName must equal those on ServiceBase derived classes.
            serviceInstaller1.ServiceName = "SAS Service";

            // Add installer to collection. Order is not important if more than one service.
            Installers.Add(serviceInstaller1);
            Installers.Add(processInstaller);
        }
    }
}

QR Code encoding and decoding using zxing

this is my working example Java code to encode QR code using ZXing with UTF-8 encoding, please note: you will need to change the path and utf8 data to your path and language characters

package com.mypackage.qr;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Hashtable;

import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.*;

public class CreateQR {

public static void main(String[] args)
{
    Charset charset = Charset.forName("UTF-8");
    CharsetEncoder encoder = charset.newEncoder();
    byte[] b = null;
    try {
        // Convert a string to UTF-8 bytes in a ByteBuffer
        ByteBuffer bbuf = encoder.encode(CharBuffer.wrap("utf 8 characters - i used hebrew, but you should write some of your own language characters"));
        b = bbuf.array();
    } catch (CharacterCodingException e) {
        System.out.println(e.getMessage());
    }

    String data;
    try {
        data = new String(b, "UTF-8");
        // get a byte matrix for the data
        BitMatrix matrix = null;
        int h = 100;
        int w = 100;
        com.google.zxing.Writer writer = new MultiFormatWriter();
        try {
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(2);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            matrix = writer.encode(data,
            com.google.zxing.BarcodeFormat.QR_CODE, w, h, hints);
        } catch (com.google.zxing.WriterException e) {
            System.out.println(e.getMessage());
        }

        // change this path to match yours (this is my mac home folder, you can use: c:\\qr_png.png if you are on windows)
                String filePath = "/Users/shaybc/Desktop/OutlookQR/qr_png.png";
        File file = new File(filePath);
        try {
            MatrixToImageWriter.writeToFile(matrix, "PNG", file);
            System.out.println("printing to " + file.getAbsolutePath());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    } catch (UnsupportedEncodingException e) {
        System.out.println(e.getMessage());
    }
}

}

How do I change the android actionbar title and icon

For set Title :

getActionBar().setTitle("Title");

For set Icon :

getActionBar().setIcon(R.drawable.YOUR_ICON_NAME);

How to download file in swift?

If you need to download only text file into String you can use this simple way, Swift 5:

let list = try? String(contentsOf: URL(string: "https://example.com/file.txt")!)

In case you want non optional result or error handling:

do {
    let list = try String(contentsOf: URL(string: "https://example.com/file.txt")!)
}
catch {
    // Handle error here
}

You should know that network operations may take some time, to prevent it from running in main thread and locking your UI, you may want to execute the code asynchronously, for example:

DispatchQueue.global().async {
    let list = try? String(contentsOf: URL(string: "https://example.com/file.txt")!)
}

How to use a findBy method with comparative criteria

The Symfony documentation now explicitly shows how to do this:

$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
    'SELECT p
    FROM AppBundle:Product p
    WHERE p.price > :price
    ORDER BY p.price ASC'
)->setParameter('price', '19.99');    
$products = $query->getResult();

From http://symfony.com/doc/2.8/book/doctrine.html#querying-for-objects-with-dql

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

The easiest answer is to just use the cors package.

const cors = require('cors');

const app = require('express')();
app.use(cors());

That will enable CORS across the board. If you want to learn how to enable CORS without outside modules, all you really need is some Express middleware that sets the 'Access-Control-Allow-Origin' header. That's the minimum you need to allow cross-request domains from a browser to your server.

app.options('*', (req, res) => {
  res.set('Access-Control-Allow-Origin', '*');
  res.send('ok');
});

app.use((req, res) => {
  res.set('Access-Control-Allow-Origin', '*');
});

moment.js - UTC gives wrong date

Both Date and moment will parse the input string in the local time zone of the browser by default. However Date is sometimes inconsistent with this regard. If the string is specifically YYYY-MM-DD, using hyphens, or if it is YYYY-MM-DD HH:mm:ss, it will interpret it as local time. Unlike Date, moment will always be consistent about how it parses.

The correct way to parse an input moment as UTC in the format you provided would be like this:

moment.utc('07-18-2013', 'MM-DD-YYYY')

Refer to this documentation.

If you want to then format it differently for output, you would do this:

moment.utc('07-18-2013', 'MM-DD-YYYY').format('YYYY-MM-DD')

You do not need to call toString explicitly.

Note that it is very important to provide the input format. Without it, a date like 01-04-2013 might get processed as either Jan 4th or Apr 1st, depending on the culture settings of the browser.

.NET - Get protocol, host, and port

Very similar to Holger's answer. If you need to grab the URL can do something like:

Uri uri = Context.Request.Url;         
var scheme = uri.Scheme // returns http, https
var scheme2 = uri.Scheme + Uri.SchemeDelimiter; // returns http://, https://
var host = uri.Host; // return www.mywebsite.com
var port = uri.Port; // returns port number

The Uri class provides a whole range of methods, many which I have not listed.

In my instance, I needed to grab LocalHost along with the Port Number, so this is what I did:

var Uri uri = Context.Request.Url;
var host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port; 

Which successfully grabbed: http://localhost:12345

How to turn off gcc compiler optimization to enable buffer overflow

On newer distros (as of 2016), it seems that PIE is enabled by default so you will need to disable it explicitly when compiling.

Here's a little summary of commands which can be helpful when playing locally with buffer overflow exercises in general:

Disable canary:

gcc vuln.c -o vuln_disable_canary -fno-stack-protector

Disable DEP:

gcc vuln.c -o vuln_disable_dep -z execstack

Disable PIE:

gcc vuln.c -o vuln_disable_pie -no-pie

Disable all of protection mechanisms listed above (warning: for local testing only):

gcc vuln.c -o vuln_disable_all -fno-stack-protector -z execstack -no-pie

For 32-bit machines, you'll need to add the -m32 parameter as well.

SQL Combine Two Columns in Select Statement

In MySQL you can use:

SELECT CONCAT(Address1, " ", Address2)
WHERE SOUNDEX(CONCAT(Address1, " ", Address2)) = SOUNDEX("Center St 3B")

The SOUNDEX function works similarly in most database systems, I can't think of the syntax for MSSQL at the minute, but it wouldn't be too far away from the above.

How can I stream webcam video with C#?

If you want a "capture/streamer in a box" component, there are several out there as others have mentioned.

If you want to get down to the low-level control over it all, you'll need to use DirectShow as thealliedhacker points out. The best way to use DirectShow in C# is through the DirectShow.Net library - it wraps all of the DirectShow COM APIs and includes many useful shortcut functions for you.

In addition to capturing and streaming, you can also do recording, audio and video format conversions, audio and video live filters, and a whole lot of stuff.

Microsoft claims DirectShow is going away, but they have yet to release a new library or API that does everything that DirectShow provides. I suspect many of the latest things they have released are still DirectShow under the hood. Because of its status at Microsoft, there aren't a whole lot of books or references on it other than MSDN and what you can find on forums. Last year when we started a project using it, the best book on the subject - Programming Microsoft DirectShow - was out of print and going for around $350 for a used copy!

Verilog generate/genvar in an always block

You need to reverse the nesting inside the generate block:

genvar c;
generate
    for (c = 0; c < ROWBITS; c = c + 1) begin: test
        always @(posedge sysclk) begin
            temp[c] <= 1'b0;
        end
    end
endgenerate

Technically, this generates four always blocks:

always @(posedge sysclk) temp[0] <= 1'b0;
always @(posedge sysclk) temp[1] <= 1'b0;
always @(posedge sysclk) temp[2] <= 1'b0;
always @(posedge sysclk) temp[3] <= 1'b0;

In this simple example, there's no difference in behavior between the four always blocks and a single always block containing four assignments, but in other cases there could be.

The genvar-dependent operation needs to be resolved when constructing the in-memory representation of the design (in the case of a simulator) or when mapping to logic gates (in the case of a synthesis tool). The always @posedge doesn't have meaning until the design is operating.

Subject to certain restrictions, you can put a for loop inside the always block, even for synthesizable code. For synthesis, the loop will be unrolled. However, in that case, the for loop needs to work with a reg, integer, or similar. It can't use a genvar, because having the for loop inside the always block describes an operation that occurs at each edge of the clock, not an operation that can be expanded statically during elaboration of the design.

Use of String.Format in JavaScript?

Adapt the code from MsAjax string.

Just remove all of the _validateParams code and you are most of the way to a full fledged .NET string class in JavaScript.

Okay, I liberated the msajax string class, removing all the msajax dependencies. It Works great, just like the .NET string class, including trim functions, endsWith/startsWith, etc.

P.S. - I left all of the Visual Studio JavaScript IntelliSense helpers and XmlDocs in place. They are innocuous if you don't use Visual Studio, but you can remove them if you like.

<script src="script/string.js" type="text/javascript"></script>
<script type="text/javascript">
    var a = String.format("Hello {0}!", "world");
    alert(a);

</script>

String.js

// String.js - liberated from MicrosoftAjax.js on 03/28/10 by Sky Sanders
// permalink: http://stackoverflow.com/a/2534834/2343

/*
    Copyright (c) 2009, CodePlex Foundation
    All rights reserved.

    Redistribution and use in source and binary forms, with or without modification, are permitted
    provided that the following conditions are met:

    *   Redistributions of source code must retain the above copyright notice, this list of conditions
        and the following disclaimer.

    *   Redistributions in binary form must reproduce the above copyright notice, this list of conditions
        and the following disclaimer in the documentation and/or other materials provided with the distribution.

    *   Neither the name of CodePlex Foundation nor the names of its contributors may be used to endorse or
        promote products derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED
    WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
    FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
    OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
    IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</textarea>
*/

(function(window) {

    $type = String;
    $type.__typeName = 'String';
    $type.__class = true;

    $prototype = $type.prototype;
    $prototype.endsWith = function String$endsWith(suffix) {
        /// <summary>Determines whether the end of this instance matches the specified string.</summary>
        /// <param name="suffix" type="String">A string to compare to.</param>
        /// <returns type="Boolean">true if suffix matches the end of this instance; otherwise, false.</returns>
        return (this.substr(this.length - suffix.length) === suffix);
    }

    $prototype.startsWith = function String$startsWith(prefix) {
        /// <summary >Determines whether the beginning of this instance matches the specified string.</summary>
        /// <param name="prefix" type="String">The String to compare.</param>
        /// <returns type="Boolean">true if prefix matches the beginning of this string; otherwise, false.</returns>
        return (this.substr(0, prefix.length) === prefix);
    }

    $prototype.trim = function String$trim() {
        /// <summary >Removes all leading and trailing white-space characters from the current String object.</summary>
        /// <returns type="String">The string that remains after all white-space characters are removed from the start and end of the current String object.</returns>
        return this.replace(/^\s+|\s+$/g, '');
    }

    $prototype.trimEnd = function String$trimEnd() {
        /// <summary >Removes all trailing white spaces from the current String object.</summary>
        /// <returns type="String">The string that remains after all white-space characters are removed from the end of the current String object.</returns>
        return this.replace(/\s+$/, '');
    }

    $prototype.trimStart = function String$trimStart() {
        /// <summary >Removes all leading white spaces from the current String object.</summary>
        /// <returns type="String">The string that remains after all white-space characters are removed from the start of the current String object.</returns>
        return this.replace(/^\s+/, '');
    }

    $type.format = function String$format(format, args) {
        /// <summary>Replaces the format items in a specified String with the text equivalents of the values of   corresponding object instances. The invariant culture will be used to format dates and numbers.</summary>
        /// <param name="format" type="String">A format string.</param>
        /// <param name="args" parameterArray="true" mayBeNull="true">The objects to format.</param>
        /// <returns type="String">A copy of format in which the format items have been replaced by the   string equivalent of the corresponding instances of object arguments.</returns>
        return String._toFormattedString(false, arguments);
    }

    $type._toFormattedString = function String$_toFormattedString(useLocale, args) {
        var result = '';
        var format = args[0];

        for (var i = 0; ; ) {
            // Find the next opening or closing brace
            var open = format.indexOf('{', i);
            var close = format.indexOf('}', i);
            if ((open < 0) && (close < 0)) {
                // Not found: copy the end of the string and break
                result += format.slice(i);
                break;
            }
            if ((close > 0) && ((close < open) || (open < 0))) {

                if (format.charAt(close + 1) !== '}') {
                    throw new Error('format stringFormatBraceMismatch');
                }

                result += format.slice(i, close + 1);
                i = close + 2;
                continue;
            }

            // Copy the string before the brace
            result += format.slice(i, open);
            i = open + 1;

            // Check for double braces (which display as one and are not arguments)
            if (format.charAt(i) === '{') {
                result += '{';
                i++;
                continue;
            }

            if (close < 0) throw new Error('format stringFormatBraceMismatch');


            // Find the closing brace

            // Get the string between the braces, and split it around the ':' (if any)
            var brace = format.substring(i, close);
            var colonIndex = brace.indexOf(':');
            var argNumber = parseInt((colonIndex < 0) ? brace : brace.substring(0, colonIndex), 10) + 1;

            if (isNaN(argNumber)) throw new Error('format stringFormatInvalid');

            var argFormat = (colonIndex < 0) ? '' : brace.substring(colonIndex + 1);

            var arg = args[argNumber];
            if (typeof (arg) === "undefined" || arg === null) {
                arg = '';
            }

            // If it has a toFormattedString method, call it.  Otherwise, call toString()
            if (arg.toFormattedString) {
                result += arg.toFormattedString(argFormat);
            }
            else if (useLocale && arg.localeFormat) {
                result += arg.localeFormat(argFormat);
            }
            else if (arg.format) {
                result += arg.format(argFormat);
            }
            else
                result += arg.toString();

            i = close + 1;
        }

        return result;
    }

})(window);

How to find out if an item is present in a std::vector?

You can try this code:

#include <algorithm>
#include <vector>

// You can use class, struct or primitive data type for Item
struct Item {
    //Some fields
};
typedef std::vector<Item> ItemVector;
typedef ItemVector::iterator ItemIterator;
//...
ItemVector vtItem;
//... (init data for vtItem)
Item itemToFind;
//...

ItemIterator itemItr;
itemItr = std::find(vtItem.begin(), vtItem.end(), itemToFind);
if (itemItr != vtItem.end()) {
    // Item found
    // doThis()
}
else {
    // Item not found
    // doThat()
}

ImportError: No module named 'django.core.urlresolvers'

To solve this either you down-grade the Django to any version lesser than 2.0. pip install Django==1.11.29.

SQL Inner join more than two tables

SELECT * 
FROM table1 
INNER JOIN table2
      ON table1.primaryKey=table2.table1Id
INNER JOIN table3
      ON table1.primaryKey=table3.table1Id

AWS - Disconnected : No supported authentication methods available (server sent :publickey)

During ssh session my connection broke, since then I cannot ssh my SRV, I had started a new instance, and I'm able to ssh the new instance (with the same key).

I mounted the old volume to the new machine, and check the .ssh/authorized_key and couldn't find any problem with permission or content.

Pandas - How to flatten a hierarchical index in columns

I think the easiest way to do this would be to set the columns to the top level:

df.columns = df.columns.get_level_values(0)

Note: if the to level has a name you can also access it by this, rather than 0.

.

If you want to combine/join your MultiIndex into one Index (assuming you have just string entries in your columns) you could:

df.columns = [' '.join(col).strip() for col in df.columns.values]

Note: we must strip the whitespace for when there is no second index.

In [11]: [' '.join(col).strip() for col in df.columns.values]
Out[11]: 
['USAF',
 'WBAN',
 'day',
 'month',
 's_CD sum',
 's_CL sum',
 's_CNT sum',
 's_PC sum',
 'tempf amax',
 'tempf amin',
 'year']

Open a URL without using a browser from a batch file

Not sure whether you have already gotten your owner solution. I have been using the following powshell command to achieve it:

powershell.exe -noprofile -command "Invoke-WebRequest -Uri http://your_url"

How do I insert a drop-down menu for a simple Windows Forms app in Visual Studio 2008?

You can use a ComboBox with its ComboBoxStyle (appears as DropDownStyle in later versions) set to DropDownList. See: http://msdn.microsoft.com/en-us/library/system.windows.forms.comboboxstyle.aspx

Java: export to an .jar file in eclipse

No need for external plugins. In the Export JAR dialog, make sure you select all the necessary resources you want to export. By default, there should be no problem exporting other resource files as well (pictures, configuration files, etc...), see screenshot below. JAR Export Dialog

Find all table names with column name?

You could do this:

SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%MyColumn%'
ORDER BY schema_name, table_name;

Reference:

How do you handle a "cannot instantiate abstract class" error in C++?

Visual Studio's Error List pane only shows you the first line of the error. Invoke View>Output and I bet you'll see something like:

c:\path\to\your\code.cpp(42): error C2259: 'AmbientOccluder' : cannot instantiate abstract class
          due to following members:
          'ULONG MysteryUnimplementedMethod(void)' : is abstract
          c:\path\to\some\include.h(8) : see declaration of 'MysteryUnimplementedMethod'

Update with two tables?

I was scratching my head, not being able to get John Sansom's Join syntax work, at least in MySQL 5.5.30 InnoDB.

It turns out that this doesn't work.

UPDATE A 
    SET A.x = 1
FROM A INNER JOIN B 
        ON A.name = B.name
WHERE A.x <> B.x

But this works:

UPDATE A INNER JOIN B 
    ON A.name = B.name
SET A.x = 1
WHERE A.x <> B.x

Filtering DataGridView without changing datasource

I found a simple way to fix that problem. At binding datagridview you've just done: datagridview.DataSource = dataSetName.Tables["TableName"];

If you code like:

datagridview.DataSource = dataSetName;
datagridview.DataMember = "TableName";

the datagridview will never load data again when filtering.

Cannot serve WCF services in IIS on Windows 8

For Windows Server 2012, the solution is very similar to faester's (see above). From the Server Manager, click on Add roles and features, select the appropriate server, then select Features. Under .NET Framework 4.5 Features, you'll see WCF Services, and under that, you'll find HTTP Activation.

tar: add all files and directories in current directory INCLUDING .svn and so on

tar -czf workspace.tar.gz .??* *

Specifying .??* will include "dot" files and directories that have at least 2 characters after the dot. The down side is it will not include files/directories with a single character after the dot, such as .a, if there are any.

Revert a jQuery draggable object back to its original container on out event of droppable

If you want to revert the element to the source position if it's not dropped inside a #droppable element, just save the original parent element of the draggable at the start of the script (instead of the position), and if you verify that it's not dropped into #droppable, then just restore the parent of #draggable to this original element.

So, replace this:

}).each(function() {
    var top = $(this).position().top;
    var left = $(this).position().left;
    $(this).data('orgTop', top);
    $(this).data('orgLeft', left);
});

with this:

}).each(function() {
    $(this).data('originalParent', $(this).parent())
});

Here, you'll have the original parent element of the draggable. Now, you have to restore it's parent in a precise moment.

drop is called every time the element is dragged out from the droppable, not at the stop. So, you're adding a lot of event callbacks. This is wrong, because you never clean the mouseup event. A good place where you can hook a callback and check if the element was dropped inside or outside the #droppable element, is revert, and you're doing it right now, so, just delete the drop callback.

When the element is dropped, and needs to know if it should be reverted or not, you know for sure that you'll not have any other interaction from the user until the new drag start. So, using the same condition you're using to know if it should revert or know, let's replace this alert with a fragment of code that: restores the parent element to the original div, and resets the originalPosition from the draggable internals. The originalPosition proeprty is setted at the time of _mouseStart, so, if you change the owner of the element, you should reset it, in order to make the animation of revert go to the proper place. So, let's set this to {top: 0, left: 0}, making the animation go to the origin point of the element:

revert: function(dropped) {
    var dropped = dropped && dropped[0].id == "droppable";
    if(!dropped) {
        $(this).data("draggable").originalPosition = {top:0, left:0}
        $(this).appendTo($(this).data('originalParent'))
    }
    return !dropped;
}

And that's it! You can check this working here: http://jsfiddle.net/eUs3e/1/

Take into consideration that, if in any jQuery's UI update, the behavior of revert or originalPosition changes, you'll need to update your code in order to make it work. Keep in mind that.

If you need a solution which doesn't make use of calls to the internals of ui.draggable, you can make your body an droppable element with greedy option defined as false. You'll have to make sure that your body elements take the full screen.

Good luck!

How to execute a command in a remote computer?

IMO, in your case you can try this:

  1. Map the shared folder to a drive or folder on your machine. (here's how)
  2. Access the mapped drive/folder as you normally would local files.

Nothing needs to be installed. No services need to be running except those that enable folder sharing.

If you can access the shared folder and maps it on your machine, most things should work just like local files, including command prompts and all explorer-enhancement tools.

This is different from using PsExec (or RDP-ing in) in that you do not need to have administrative rights and/or remote desktop/terminal services connection rights on the remote server, you just need to be able to access those shared folders.

Also make sure you have all the necessary security permissions to run whatever commands/tools you want to run on those shared folders as well.


If, however you wish the processing to be done on the target machine, then you can try PsExec as @divo and @recursive pointed out, something alongs:

PsExec \\yourServerName -u yourUserName cmd.exe

Which will brings gives you a command prompt at the remote machine. And from there you can execute whatever you want.

I am not sure but I think you need either the Server (lanmanserver) or the Terminal Services (TermService) service to be running (which should have already be running).

Encoding as Base64 in Java

I tried with the following code snippet. It worked well. :-)

com.sun.org.apache.xml.internal.security.utils.Base64.encode("The string to encode goes here");

Remove special symbols and extra spaces and replace with underscore using the replace method

It was not asked precisely to remove accent (only special characters), but I needed to.

The solutions givens here works but they don’t remove accent: é, è, etc.

So, before doing epascarello’s solution, you can also do:

_x000D_
_x000D_
var newString = "développeur & intégrateur";_x000D_
_x000D_
newString = replaceAccents(newString);_x000D_
newString = newString.replace(/[^A-Z0-9]+/ig, "_");_x000D_
alert(newString);_x000D_
_x000D_
/**_x000D_
 * Replaces all accented chars with regular ones_x000D_
 */_x000D_
function replaceAccents(str) {_x000D_
  // Verifies if the String has accents and replace them_x000D_
  if (str.search(/[\xC0-\xFF]/g) > -1) {_x000D_
    str = str_x000D_
      .replace(/[\xC0-\xC5]/g, "A")_x000D_
      .replace(/[\xC6]/g, "AE")_x000D_
      .replace(/[\xC7]/g, "C")_x000D_
      .replace(/[\xC8-\xCB]/g, "E")_x000D_
      .replace(/[\xCC-\xCF]/g, "I")_x000D_
      .replace(/[\xD0]/g, "D")_x000D_
      .replace(/[\xD1]/g, "N")_x000D_
      .replace(/[\xD2-\xD6\xD8]/g, "O")_x000D_
      .replace(/[\xD9-\xDC]/g, "U")_x000D_
      .replace(/[\xDD]/g, "Y")_x000D_
      .replace(/[\xDE]/g, "P")_x000D_
      .replace(/[\xE0-\xE5]/g, "a")_x000D_
      .replace(/[\xE6]/g, "ae")_x000D_
      .replace(/[\xE7]/g, "c")_x000D_
      .replace(/[\xE8-\xEB]/g, "e")_x000D_
      .replace(/[\xEC-\xEF]/g, "i")_x000D_
      .replace(/[\xF1]/g, "n")_x000D_
      .replace(/[\xF2-\xF6\xF8]/g, "o")_x000D_
      .replace(/[\xF9-\xFC]/g, "u")_x000D_
      .replace(/[\xFE]/g, "p")_x000D_
      .replace(/[\xFD\xFF]/g, "y");_x000D_
  }_x000D_
_x000D_
  return str;_x000D_
}
_x000D_
_x000D_
_x000D_

Source: https://gist.github.com/jonlabelle/5375315

How to add header data in XMLHttpRequest when using formdata?

Check to see if the key-value pair is actually showing up in the request:

In Chrome, found somewhere like: F12: Developer Tools > Network Tab > Whatever request you have sent > "view source" under Response Headers

Depending on your testing workflow, if whatever pair you added isn't there, you may just need to clear your browser cache. To verify that your browser is using your most up-to-date code, you can check the page's sources, in Chrome this is found somewhere like: F12: Developer Tools > Sources Tab > YourJavascriptSrc.js and check your code.

But as other answers have said:

xhttp.setRequestHeader(key, value);

should add a key-value pair to your request header, just make sure to place it after your open() and before your send()

How to get the HTML's input element of "file" type to only accept pdf files?

To get the HTML file input form element to only accept PDFs, you can use the accept attribute in modern browsers such as Firefox 9+, Chrome 16+, Opera 11+ and IE10+ like such:

<input name="file1" type="file" accept="application/pdf">

You can string together multiple mime types with a comma.

The following string will accept JPG, PNG, GIF, PDF, and EPS files:

<input name="foo" type="file" accept="image/jpeg,image/gif,image/png,application/pdf,image/x-eps">

In older browsers the native OS file dialog cannot be restricted – you'd have to use Flash or a Java applet or something like that to handle the file transfer.

And of course it goes without saying that this doesn't do anything to verify the validity of the file type. You'll do that on the server-side once the file has uploaded.

A little update – with javascript and the FileReader API you could do more validation client-side before uploading huge files to your server and checking them again.

Get Cell Value from a DataTable in C#

The DataRow has also an indexer:

Object cellValue = dt.Rows[i][j];

But i would prefer the strongly typed Field extension method which also supports nullable types:

int number = dt.Rows[i].Field<int>(j);

or even more readable and less error-prone with the name of the column:

double otherNumber = dt.Rows[i].Field<double>("DoubleColumn");

How to do URL decoding in Java?

Using java.net.URI class:

public String getDecodedURL(String encodedUrl) {
    try {
        URI uri = new URI(encodedUrl);
        return uri.getScheme() + ":" + uri.getSchemeSpecificPart();
    } catch (Exception e) {
        return "";
    }
}

Please note that exception handling can be better, but it's not much relevant for this example.

Case insensitive searching in Oracle

Since 10gR2, Oracle allows to fine-tune the behaviour of string comparisons by setting the NLS_COMP and NLS_SORT session parameters:

SQL> SET HEADING OFF
SQL> SELECT *
  2  FROM NLS_SESSION_PARAMETERS
  3  WHERE PARAMETER IN ('NLS_COMP', 'NLS_SORT');

NLS_SORT
BINARY

NLS_COMP
BINARY


SQL>
SQL> SELECT CASE WHEN 'abc'='ABC' THEN 1 ELSE 0 END AS GOT_MATCH
  2  FROM DUAL;

         0

SQL>
SQL> ALTER SESSION SET NLS_COMP=LINGUISTIC;

Session altered.

SQL> ALTER SESSION SET NLS_SORT=BINARY_CI;

Session altered.

SQL>
SQL> SELECT *
  2  FROM NLS_SESSION_PARAMETERS
  3  WHERE PARAMETER IN ('NLS_COMP', 'NLS_SORT');

NLS_SORT
BINARY_CI

NLS_COMP
LINGUISTIC


SQL>
SQL> SELECT CASE WHEN 'abc'='ABC' THEN 1 ELSE 0 END AS GOT_MATCH
  2  FROM DUAL;

         1

You can also create case insensitive indexes:

create index
   nlsci1_gen_person
on
   MY_PERSON
   (NLSSORT
      (PERSON_LAST_NAME, 'NLS_SORT=BINARY_CI')
   )
;

This information was taken from Oracle case insensitive searches. The article mentions REGEXP_LIKE but it seems to work with good old = as well.


In versions older than 10gR2 it can't really be done and the usual approach, if you don't need accent-insensitive search, is to just UPPER() both the column and the search expression.

static constructors in C++? I need to initialize private static objects

It certainly doesn't need to be as complicated as the currently accepted answer (by Daniel Earwicker). The class is superfluous. There's no need for a language war in this case.

.hpp file:

vector<char> const & letters();

.cpp file:

vector<char> const & letters()
{
  static vector<char> v = {'a', 'b', 'c', ...};
  return v;
}

How to detect the screen resolution with JavaScript?

You can also get the WINDOW width and height, avoiding browser toolbars and... (not just screen size).

To do this, use: window.innerWidth and window.innerHeight properties. See it at w3schools.

In most cases it will be the best way, in example, to display a perfectly centred floating modal dialog. It allows you to calculate positions on window, no matter which resolution orientation or window size is using the browser.

What's the purpose of git-mv?

There's a niche case where git mv remains very useful: when you want to change the casing of a file name on a case-insensitive file system. Both APFS (mac) and NTFS (windows) are, by default, case-insensitive (but case-preserving).

greg.kindel mentions this in a comment on CB Bailey's answer.

Suppose you are working on a mac and have a file Mytest.txt managed by git. You want to change the file name to MyTest.txt.

You could try:

$ mv Mytest.txt MyTest.txt
overwrite MyTest.txt? (y/n [n]) y
$ git status
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean

Oh dear. Git doesn't acknowledge there's been any change to the file.

You could work around this with by renaming the file completely then renaming it back:

$ mv Mytest.txt temp.txt
$ git rm Mytest.txt
rm 'Mytest.txt'
$ mv temp.txt MyTest.txt
$ git add MyTest.txt 
$ git status
On branch master
Your branch is up to date with 'origin/master'.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    renamed:    Mytest.txt -> MyTest.txt

Hurray!

Or you could save yourself all that bother by using git mv:

$ git mv Mytest.txt MyTest.txt
$ git status
On branch master
Your branch is up to date with 'origin/master'.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    renamed:    Mytest.txt -> MyTest.txt

align 3 images in same row with equal spaces?

This should be your answer

<div align="center">
 <img src="@Url.Content("~/images/image3.bmp")" alt="" align="right" style="float:right"/>
 <img src="@Url.Content("~/images/image1.bmp")" alt="" align="left" style="float:left" />
 <div id="content" align="center"> 
     <img src="@Url.Content("~/images/image2.bmp")" alt="" align="center" />
 </div>
 </div>

Get int value from enum in C#

If you want to get an integer for the enum value that is stored in a variable, for which the type would be Question, to use for example in a method, you can simply do this I wrote in this example:

enum Talen
{
    Engels = 1, Italiaans = 2, Portugees = 3, Nederlands = 4, Duits = 5, Dens = 6
}

Talen Geselecteerd;    

public void Form1()
{
    InitializeComponent()
    Geselecteerd = Talen.Nederlands;
}

// You can use the Enum type as a parameter, so any enumeration from any enumerator can be used as parameter
void VeranderenTitel(Enum e)
{
    this.Text = Convert.ToInt32(e).ToString();
}

This will change the window title to 4, because the variable Geselecteerd is Talen.Nederlands. If I change it to Talen.Portugees and call the method again, the text will change to 3.

java.net.UnknownHostException: Invalid hostname for server: local

Connect your mobile with different wifi connection with different service provider. I don't know the exact issue but i could not connect to server with a specific service provider but it work when i connected to other service provider. So try it!

Does my application "contain encryption"?

I had a lab with App Review team (WWDC20).

My questions were:

  1. My app is making calls through HTTPS only. Should I select Yes or No?
  2. Should I send report to the US government if my app available in Germany only (doesn't available in the USA)?

Answers:

  1. If you just use HTTPS you can select No

  2. The answer on the second question was unclear. Helpful link Looks like yes if you're using custom encryption.

Newline in JLabel

You can try and do this:

myLabel.setText("<html>" + myString.replaceAll("<","&lt;").replaceAll(">", "&gt;").replaceAll("\n", "<br/>") + "</html>")

The advantages of doing this are:

  • It replaces all newlines with <br/>, without fail.
  • It automatically replaces eventual < and > with &lt; and &gt; respectively, preventing some render havoc.

What it does is:

  • "<html>" + adds an opening html tag at the beginning
  • .replaceAll("<", "&lt;").replaceAll(">", "&gt;") escapes < and > for convenience
  • .replaceAll("\n", "<br/>") replaces all newlines by br (HTML line break) tags for what you wanted
  • ... and + "</html>" closes our html tag at the end.

P.S.: I'm very sorry to wake up such an old post, but whatever, you have a reliable snippet for your Java!

How do I get the latest version of my code?

I suspect that what's happened may be that you've deleted the files that you modified (because you didn't care about those changes) and now git is taking the deletion to be a change.

Here is an approach that moves your changes out of your working copy and into the "stash" (retrievable should it actually turn out that you ever need them again), so you can then pull the latest changes down from the upstream.

git stash  
git pull

If you ever want to retrieve your files (potential conflicts with upstream changes and all), run a git stash apply to stick those changes on top of your code. That way, you have an "undo" approach.

What is the difference between char * const and const char *?

The const modifier is applied to the term immediately to its left. The only exception to this is when there is nothing to its left, then it applies to what is immediately on its right.

These are all equivalent ways of saying "constant pointer to a constant char":

  • const char * const
  • const char const *
  • char const * const
  • char const const *

org.apache.jasper.JasperException: Unable to compile class for JSP:

I was facing the issue, i found that that older ecj library is present in Apache Tomcat directory 1)remove old jar from Apache Tomcat library 2)clean the project 3)build it. It started working as expected.

SVG gradient using CSS

Just use in the CSS whatever you would use in a fill attribute. Of course, this requires that you have defined the linear gradient somewhere in your SVG.

Here is a complete example:

_x000D_
_x000D_
rect {_x000D_
    cursor: pointer;_x000D_
    shape-rendering: crispEdges;_x000D_
    fill: url(#MyGradient);_x000D_
}
_x000D_
<svg width="100" height="50" version="1.1" xmlns="http://www.w3.org/2000/svg">_x000D_
      <style type="text/css">_x000D_
        rect{fill:url(#MyGradient)}_x000D_
      </style>_x000D_
      <defs>_x000D_
        <linearGradient id="MyGradient">_x000D_
          <stop offset="5%" stop-color="#F60" />_x000D_
          <stop offset="95%" stop-color="#FF6" />_x000D_
        </linearGradient>_x000D_
      </defs>_x000D_
      _x000D_
      <rect width="100" height="50"/>_x000D_
    </svg>
_x000D_
_x000D_
_x000D_

slashes in url variables

You need to escape the slashes as %2F.

Executing command line programs from within python

If you're concerned about server performance then look at capping the number of running sox processes. If the cap has been hit you can always cache the request and inform the user when it's finished in whichever way suits your application.

Alternatively, have the n worker scripts on other machines that pull requests from the db and call sox, and then push the resulting output file to where it needs to be.

force line break in html table cell

You could put the text into a div (or other container) with a width of 50%.

http://jsfiddle.net/6gjsd/

Batch script to install MSI

Although it might look out of topic nobody bothered to check the ERRORLEVEL. When I used your suggestions I tried to check for errors straight after the MSI installation. I made it fail on purpose and noticed that on the command line all works beautifully whilst in a batch file msiexec dosn't seem to set errors. Tried different things there like

  • Using start /wait
  • Using !ERRORLEVEL! variable instead of %ERRORLEVEL%
  • Using SetLocal EnableDelayedExpansion

Nothing works and what mostly annoys me it's the fact that it works in the command line.

Case Insensitive String comp in C

I've found built-in such method named from which contains additional string functions to the standard header .

Here's the relevant signatures :

int  strcasecmp(const char *, const char *);
int  strncasecmp(const char *, const char *, size_t);

I also found it's synonym in xnu kernel (osfmk/device/subrs.c) and it's implemented in the following code, so you wouldn't expect to have any change of behavior in number compared to the original strcmp function.

tolower(unsigned char ch) {
    if (ch >= 'A' && ch <= 'Z')
        ch = 'a' + (ch - 'A');
    return ch;
 }

int strcasecmp(const char *s1, const char *s2) {
    const unsigned char *us1 = (const u_char *)s1,
                        *us2 = (const u_char *)s2;

    while (tolower(*us1) == tolower(*us2++))
        if (*us1++ == '\0')
            return (0);
    return (tolower(*us1) - tolower(*--us2));
}

How to mark-up phone numbers?

this worked for me:

1.make a standards compliant link:

        <a href="tel:1500100900">

2.replace it when mobile browser is not detected, for skype:

$("a.phone")
    .each(function()
{ 
  this.href = this.href.replace(/^tel/, 
     "callto");
});

Selecting link to replace via class seems more efficient. Of course it works only on anchors with .phone class.

I have put it in function if( !isMobile() ) { ... so it triggers only when detects desktop browser. But this one is problably obsolete...

function isMobile() {
    return (
        ( navigator.userAgent.indexOf( "iPhone" ) > -1 ) ||
        ( navigator.userAgent.indexOf( "iPod" ) > -1 ) ||
        ( navigator.userAgent.indexOf( "iPad" ) > -1 ) ||
        ( navigator.userAgent.indexOf( "Android" ) > -1 ) ||
        ( navigator.userAgent.indexOf( "webOS" ) > -1 )
    );
}

What is the difference between Python and IPython?

IPython is basically the "recommended" Python shell, which provides extra features. There is no language called IPython.

Call Python script from bash with argument

Beside sys.argv, also take a look at the argparse module, which helps define options and arguments for scripts.

The argparse module makes it easy to write user-friendly command-line interfaces.

How do I get rid of the b-prefix in a string in python?

On python 3.6 with django 2.0, decode on a byte literal does not works as expected. Yeah i get the right result when i print it, but the b'value' is still there even if you print it right.

This is what im encoding

uid': urlsafe_base64_encode(force_bytes(user.pk)),

This is what im decoding:

uid = force_text(urlsafe_base64_decode(uidb64))

This is what django 2.0 says :

urlsafe_base64_encode(s)[source]

Encodes a bytestring in base64 for use in URLs, stripping any trailing equal signs.

urlsafe_base64_decode(s)[source]

Decodes a base64 encoded string, adding back any trailing equal signs that might have been stripped.


This is my account_activation_email_test.html file

{% autoescape off %}
Hi {{ user.username }},

Please click on the link below to confirm your registration:

http://{{ domain }}{% url 'accounts:activate' uidb64=uid token=token %}
{% endautoescape %}

This is my console response:

Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Activate Your MySite Account From: webmaster@localhost To: [email protected] Date: Fri, 20 Apr 2018 06:26:46 -0000 Message-ID: <152420560682.16725.4597194169307598579@Dash-U>

Hi testuser,

Please click on the link below to confirm your registration:

http://127.0.0.1:8000/activate/b'MjU'/4vi-fasdtRf2db2989413ba/

as you can see uid = b'MjU'

expected uid = MjU


test in console:

$ python
Python 3.6.4 (default, Apr  7 2018, 00:45:33) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
>>> from django.utils.encoding import force_bytes, force_text
>>> var1=urlsafe_base64_encode(force_bytes(3))
>>> print(var1)
b'Mw'
>>> print(var1.decode())
Mw
>>> 

After investigating it seems like its related to python 3. My workaround was quite simple:

'uid': user.pk,

i receive it as uidb64 on my activate function:

user = User.objects.get(pk=uidb64)

and voila:

Content-Transfer-Encoding: 7bit
Subject: Activate Your MySite Account
From: webmaster@localhost
To: [email protected]
Date: Fri, 20 Apr 2018 20:44:46 -0000
Message-ID: <152425708646.11228.13738465662759110946@Dash-U>


Hi testuser,

Please click on the link below to confirm your registration:

http://127.0.0.1:8000/activate/45/4vi-3895fbb6b74016ad1882/

now it works fine. :)

String.strip() in Python

No, it is better practice to leave them out.

Without strip(), you can have empty keys and values:

apples<tab>round, fruity things
oranges<tab>round, fruity things
bananas<tab>

Without strip(), bananas is present in the dictionary but with an empty string as value. With strip(), this code will throw an exception because it strips the tab of the banana line.

How to store .pdf files into MySQL as BLOBs using PHP?

EDITED TO ADD: The following code is outdated and won't work in PHP 7. See the note towards the bottom of the answer for more details.


Assuming a table structure of an integer ID and a blob DATA column, and assuming MySQL functions are being used to interface with the database, you could probably do something like this:

$result = mysql_query 'INSERT INTO table (
    data
) VALUES (
    \'' . mysql_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf')) . '\'
);';

A word of warning though, storing blobs in databases is generally not considered to be the best idea as it can cause table bloat and has a number of other problems associated with it. A better approach would be to move the file somewhere in the filesystem where it can be retrieved, and store the path to the file in the database instead of the file itself.

Also, using mysql_* function calls is discouraged as those methods are effectively deprecated and aren't really built with versions of MySQL newer than 4.x in mind. You should switch to mysqli or PDO instead.

UPDATE: mysql_* functions are deprecated in PHP 5.x and are REMOVED COMPLETELY IN PHP 7! You now have no choice but to switch to a more modern Database Abstraction (MySQLI, PDO). I've decided to leave the original answer above intact for historical reasons but don't actually use it

Here's how to do it with mysqli in procedural mode:

$result = mysqli_query ($db, 'INSERT INTO table (
    data
) VALUES (
    \'' . mysqli_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf'), $db) . '\'
);');

The ideal way of doing it is with MySQLI/PDO prepared statements.

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

For those still struggling with the error, make sure that you also import ReactiveFormsModule in your component 's module.ts file

meaning that you will import your ReactiveFormsModule in your app.module.ts and also in your mycomponent.module.ts file

Is having an 'OR' in an INNER JOIN condition a bad idea?

I use following code for get different result from condition That worked for me.


Select A.column, B.column
FROM TABLE1 A
INNER JOIN
TABLE2 B
ON A.Id = (case when (your condition) then b.Id else (something) END)

How do you list all triggers in a MySQL database?

I hope following code will give you more information.

select * from information_schema.triggers where 
information_schema.triggers.trigger_schema like '%your_db_name%'

This will give you total 22 Columns in MySQL version: 5.5.27 and Above

TRIGGER_CATALOG 
TRIGGER_SCHEMA
TRIGGER_NAME
EVENT_MANIPULATION
EVENT_OBJECT_CATALOG
EVENT_OBJECT_SCHEMA 
EVENT_OBJECT_TABLE
ACTION_ORDER
ACTION_CONDITION
ACTION_STATEMENT
ACTION_ORIENTATION
ACTION_TIMING
ACTION_REFERENCE_OLD_TABLE
ACTION_REFERENCE_NEW_TABLE
ACTION_REFERENCE_OLD_ROW
ACTION_REFERENCE_NEW_ROW
CREATED 
SQL_MODE
DEFINER 
CHARACTER_SET_CLIENT
COLLATION_CONNECTION
DATABASE_COLLATION

Finding import static statements for Mockito constructs

Here's what I've been doing to cope with the situation.

I use global imports on a new test class.

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;

When you are finished writing your test and need to commit, you just CTRL+SHIFT+O to organize the packages. For example, you may just be left with:

import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyString;

This allows you to code away without getting 'stuck' trying to find the correct package to import.

How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?

We can add "AwaitTerminationSeconds" property for both taskExecutor and taskScheduler as below,

<property name="awaitTerminationSeconds" value="${taskExecutor .awaitTerminationSeconds}" />

<property name="awaitTerminationSeconds" value="${taskScheduler .awaitTerminationSeconds}" />

Documentation for "waitForTasksToCompleteOnShutdown" property says, when shutdown is called

"Spring's container shutdown continues while ongoing tasks are being completed. If you want this executor to block and wait for the termination of tasks before the rest of the container continues to shut down - e.g. in order to keep up other resources that your tasks may need -, set the "awaitTerminationSeconds" property instead of or in addition to this property."

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/concurrent/ExecutorConfigurationSupport.html#setWaitForTasksToCompleteOnShutdown-boolean-

So it is always advised to use waitForTasksToCompleteOnShutdown and awaitTerminationSeconds properties together. Value of awaitTerminationSeconds depends on our application.

Configure hibernate to connect to database via JNDI Datasource

I was getting the same error in my IBM Websphere with c3p0 jar files. I have Oracle 10g database. I simply added the oraclejdbc.jar files in the Application server JVM in IBM Classpath using Websphere Console and the error was resolved.

The oraclejdbc.jar should be set with your C3P0 jar files in your Server Class path whatever it be tomcat, glassfish of IBM.

What is a NoReverseMatch error, and how do I fix it?

And make sure your route in the list of routes:

./manage.py show_urls | grep path_or_name

https://github.com/django-extensions/django-extensions

TCPDF Save file to folder?

$pdf->Output() takes a second parameter $dest, which accepts a single character. The default, $dest='I' opens the PDF in the browser.

Use F to save to file

$pdf->Output('/path/to/file.pdf', 'F')

Adding values to specific DataTable cells

If anyone is looking for an updated correct syntax for this as I was, try the following:

Example:
dg.Rows[0].Cells[6].Value = "test";

How can I copy columns from one sheet to another with VBA in Excel?

I'm not sure why you'd be getting subscript out of range unless your sheets weren't actually called Sheet1 or Sheet2. When I rename my Sheet2 to Sheet_2, I get that same problem.

In addition, some of your code seems the wrong way about (you paste before selecting the second sheet). This code works fine for me.

Sub OneCell()
    Sheets("Sheet1").Select
    Range("A1:A3").Copy
    Sheets("Sheet2").Select
    Range("b1:b3").Select
    ActiveSheet.Paste
End Sub

If you don't want to know about what the sheets are called, you can use integer indexes as follows:

Sub OneCell()
    Sheets(1).Select
    Range("A1:A3").Copy
    Sheets(2).Select
    Range("b1:b3").Select
    ActiveSheet.Paste
End Sub

How to Use -confirm in PowerShell

This is a simple loop that keeps prompting unless the user selects 'y' or 'n'

$confirmation = Read-Host "Ready? [y/n]"
while($confirmation -ne "y")
{
    if ($confirmation -eq 'n') {exit}
    $confirmation = Read-Host "Ready? [y/n]"
}

Moving items around in an ArrayList

As Mikkel posted before Collections.rotate is a simple way. I'm using this method for moving items up- and downward in a List.

public static <T> void moveItem(int sourceIndex, int targetIndex, List<T> list) {
    if (sourceIndex <= targetIndex) {
        Collections.rotate(list.subList(sourceIndex, targetIndex + 1), -1);
    } else {
        Collections.rotate(list.subList(targetIndex, sourceIndex + 1), 1);
    }
}