Programs & Examples On #Xlrd

xlrd is a python library to extract data from Microsoft Excel spreadsheet files

Pandas: Looking up the list of sheets in an excel file

This is the fastest way I have found, inspired by @divingTobi's answer. All The answers based on xlrd, openpyxl or pandas are slow for me, as they all load the whole file first.

from zipfile import ZipFile
from bs4 import BeautifulSoup  # you also need to install "lxml" for the XML parser

with ZipFile(file) as zipped_file:
    summary = zipped_file.open(r'xl/workbook.xml').read()
soup = BeautifulSoup(summary, "xml")
sheets = [sheet.get("name") for sheet in soup.find_all("sheet")]

Read Excel File in Python

Here is the code to read an excel file and and print all the cells present in column 1 (except the first cell i.e the header):

import xlrd

file_location="C:\pythonprog\xxx.xlsv"
workbook=xlrd.open_workbook(file_location)
sheet=workbook.sheet_by_index(0)
print(sheet.cell_value(0,0))

for row in range(1,sheet.nrows):
     print(sheet.cell_value(row,0))

Create a .csv file with values from a Python list

To create and write into a csv file

The below example demonstrate creating and writing a csv file. to make a dynamic file writer we need to import a package import csv, then need to create an instance of the file with file reference Ex:- with open("D:\sample.csv","w",newline="") as file_writer

here if the file does not exist with the mentioned file directory then python will create a same file in the specified directory, and "w" represents write, if you want to read a file then replace "w" with "r" or to append to existing file then "a". newline="" specifies that it removes an extra empty row for every time you create row so to eliminate empty row we use newline="", create some field names(column names) using list like fields=["Names","Age","Class"], then apply to writer instance like writer=csv.DictWriter(file_writer,fieldnames=fields) here using Dictionary writer and assigning column names, to write column names to csv we use writer.writeheader() and to write values we use writer.writerow({"Names":"John","Age":20,"Class":"12A"}) ,while writing file values must be passed using dictionary method , here the key is column name and value is your respective key value

import csv 

with open("D:\\sample.csv","w",newline="") as file_writer:

   fields=["Names","Age","Class"]

   writer=csv.DictWriter(file_writer,fieldnames=fields)

   writer.writeheader()

   writer.writerow({"Names":"John","Age":21,"Class":"12A"})

xlrd.biffh.XLRDError: Excel xlsx file; not supported

The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:

pip install xlrd==1.2.0

writing to existing workbook using xlwt

The code example is exactly this:

from xlutils.copy import copy
from xlrd import *
w = copy(open_workbook('book1.xls'))
w.get_sheet(0).write(0,0,"foo")
w.save('book2.xls')

You'll need to create book1.xls to test, but you get the idea.

Edit existing excel workbooks and sheets with xlrd and xlwt

Here's another way of doing the code above using the openpyxl module that's compatible with xlsx. From what I've seen so far, it also keeps formatting.

from openpyxl import load_workbook
wb = load_workbook('names.xlsx')
ws = wb['SheetName']
ws['A1'] = 'A1'
wb.save('names.xlsx')

python xlrd unsupported format, or corrupt file.

I had the same issue. Those old files are formatted like a tab-delimited file. I've been able to open my problem files with read_table; ie df = pd.read_table('trouble_maker.xls').

Getting year in moment.js

_x000D_
_x000D_
var year1 = moment().format('YYYY');_x000D_
var year2 = moment().year();_x000D_
_x000D_
console.log('using format("YYYY") : ',year1);_x000D_
console.log('using year(): ',year2);_x000D_
_x000D_
// using javascript _x000D_
_x000D_
var year3 = new Date().getFullYear();_x000D_
console.log('using javascript :',year3);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

android pick images from gallery

If you are only looking for images and multiple selection.

Look @ once https://stackoverflow.com/a/15029515/1136023

It's helpful for future.I personally feel great by using MultipleImagePick.

Open URL in Java to get the content

public class UrlContent{
    public static void main(String[] args) {

        URL url;

        try {
            // get URL content

            String a="http://localhost:8080/TestWeb/index.jsp";
            url = new URL(a);
            URLConnection conn = url.openConnection();

            // open the stream and put it into BufferedReader
            BufferedReader br = new BufferedReader(
                               new InputStreamReader(conn.getInputStream()));

            String inputLine;
            while ((inputLine = br.readLine()) != null) {
                    System.out.println(inputLine);
            }
            br.close();

            System.out.println("Done");

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

You can have the @Transactional in the child class, but you have to override each of the methods and call the super method in order to get it to work.

Example:

@Transactional(readOnly = true)
public class Bob<SomeClass> {
   @Override
   public SomeClass getValue() {
       return super.getValue();
   }
}

This allows it to set it up for each of the methods it's needed for.

Counting the number of occurences of characters in a string

Try this:

import java.util.Scanner;

    /* Logic: Consider first character in the string and start counting occurrence of        
              this character in the entire string. Now add this character to a empty
              string "temp" to keep track of the already counted characters.
              Next start counting from next character and start counting the character        
              only if it is not present in the "temp" string( which means only if it is
              not counted already)
public class Counting_Occurences {

    public static void main(String[] args) {


        Scanner input=new Scanner(System.in);
        System.out.println("Enter String");
        String str=input.nextLine();

        int count=0;
        String temp=""; // An empty string to keep track of counted
                                    // characters


        for(int i=0;i<str.length();i++)
        {

            char c=str.charAt(i);  // take one character (c) in string

            for(int j=i;j<str.length();j++)
            {

                char k=str.charAt(j);  
    // take one character (c) and compare with each character (k) in the string
            // also check that character (c) is not already counted.
            // if condition passes then increment the count.
                if(c==k && temp.indexOf(c)==-1)                                                                          
                {

                    count=count+1;

                }

            }

             if(temp.indexOf(c)==-1)  // if it is not already counted
             {


            temp=temp+c; // append the character to the temp indicating
                                         // that you have already counted it.

System.out.println("Character   " + c + "   occurs   " + count + "    times");
             }  
            // reset the counter for next iteration 
              count=0;

        }


    }


}

Add borders to cells in POI generated Excel File

HSSFCellStyle style=workbook.createCellStyle();
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);

Use jquery click to handle anchor onClick()

The first time you click the link, the openSolution function is executed. That function binds the click event handler to the link, but it won't execute it. The second time you click the link, the click event handler will be executed.

What you are doing seems to kind of defeat the point of using jQuery in the first place. Why not just bind the click event to the elements in the first place:

$(document).ready(function() {
    $("#solTitle a").click(function() {
        //Do stuff when clicked
    });
});

This way you don't need onClick attributes on your elements.

It also looks like you have multiple elements with the same id value ("solTitle"), which is invalid. You would need to find some other common characteristic (class is usually a good option). If you change all occurrences of id="solTitle" to class="solTitle", you can then use a class selector:

$(".solTitle a")

Since duplicate id values is invalid, the code will not work as expected when facing multiple copies of the same id. What tends to happen is that the first occurrence of the element with that id is used, and all others are ignored.

Select rows of a matrix that meet a condition

If your matrix is called m, just use :

R> m[m$three == 11, ]

php: Get html source code with cURL

Try the following:

$ch = curl_init("http://www.example-webpage.com/file.html");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);

I would only recommend this for small files. Big files are read as a whole and are likely to produce a memory error.


EDIT: after some discussion in the comments we found out that the problem was that the server couldn't resolve the host name and the page was in addition a HTTPS resource so here comes your temporary solution (until your server admin fixes the name resolving).

what i did is just pinging graph.facebook.com to see the IP address, replace the host name with the IP address and instead specify the header manually. This however renders the SSL certificate invalid so we have to suppress peer verification.

//$url = "https://graph.facebook.com/19165649929?fields=name";
$url = "https://66.220.146.224/19165649929?fields=name";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: graph.facebook.com'));
$output = curl_exec($ch);
curl_close($ch); 

Keep in mind that the IP address might change and this is an error source. you should also do some error handling using curl_error();.

How to set the title text color of UIButton?

func setTitleColor(_ color: UIColor?, 
               for state: UIControl.State)

Parameters:

color:
The color of the title to use for the specified state.

state:
The state that uses the specified color. The possible values are described in UIControl.State.

Sample:

let MyButton = UIButton()
MyButton.setTitle("Click Me..!", for: .normal)
MyButton.setTitleColor(.green, for: .normal)

ssl_error_rx_record_too_long and Apache SSL

In my case the problem was that https was unable to start correctly because Listen 443 was in "IfDefine SSL" derective, but my apache didnt start with -DSSL option. The fix was to change my apachectl script in:

$HTTPD -k $ARGV

to:

$HTTPD -k $ARGV -DSSL

Hope that helps somebody.

installing apache: no VCRUNTIME140.dll

I had same problem, my issue was that downloaded Apache 2.4 but 32 bits. Then re-download 64bits version and it's works.

I hope it helps you

How does numpy.histogram() work?

Another useful thing to do with numpy.histogram is to plot the output as the x and y coordinates on a linegraph. For example:

arr = np.random.randint(1, 51, 500)
y, x = np.histogram(arr, bins=np.arange(51))
fig, ax = plt.subplots()
ax.plot(x[:-1], y)
fig.show()

enter image description here

This can be a useful way to visualize histograms where you would like a higher level of granularity without bars everywhere. Very useful in image histograms for identifying extreme pixel values.

Splitting templated C++ classes into .hpp/.cpp files--is it possible?

I believe there are two main reasons for trying to seperate templated code into a header and a cpp:

One is for mere elegance. We all like to write code that is wasy to read, manage and is reusable later.

Other is reduction of compilation times.

I am currently (as always) coding simulation software in conjuction with OpenCL and we like to keep code so it can be run using float (cl_float) or double (cl_double) types as needed depending on HW capability. Right now this is done using a #define REAL at the beginning of the code, but this is not very elegant. Changing desired precision requires recompiling the application. Since there are no real run-time types, we have to live with this for the time being. Luckily OpenCL kernels are compiled runtime, and a simple sizeof(REAL) allows us to alter the kernel code runtime accordingly.

The much bigger problem is that even though the application is modular, when developing auxiliary classes (such as those that pre-calculate simulation constants) also have to be templated. These classes all appear at least once on the top of the class dependency tree, as the final template class Simulation will have an instance of one of these factory classes, meaning that practically every time I make a minor change to the factory class, the entire software has to be rebuilt. This is very annoying, but I cannot seem to find a better solution.

Which concurrent Queue implementation should I use in Java?

ArrayBlockingQueue has lower memory footprint, it can reuse element node, not like LinkedBlockingQueue that have to create a LinkedBlockingQueue$Node object for each new insertion.

How to force Sequential Javascript Execution?

I tried the callback way and could not get this to work, what you have to understand is that values are still atomic even though execution is not. For example:

alert('1'); <--- these two functions will be executed at the same time

alert('2'); <--- these two functions will be executed at the same time

but doing like this will force us to know the order of execution:

loop=2;
total=0;
for(i=0;i<loop;i++) {
           total+=1;
           if(total == loop)
                      alert('2');
           else
                      alert('1');
}

How to source virtualenv activate in a Bash script

You can also do this using a subshell to better contain your usage - here's a practical example:

#!/bin/bash

commandA --args

# Run commandB in a subshell and collect its output in $VAR
# NOTE
#  - PATH is only modified as an example
#  - output beyond a single value may not be captured without quoting
#  - it is important to discard (or separate) virtualenv activation stdout
#    if the stdout of commandB is to be captured
#
VAR=$(
    PATH="/opt/bin/foo:$PATH"
    . /path/to/activate > /dev/null  # activate virtualenv
    commandB  # tool from /opt/bin/ which requires virtualenv
)

# Use the output from commandB later
commandC "$VAR"

This style is especially helpful when

  • a different version of commandA or commandC exists under /opt/bin
  • commandB exists in the system PATH or is very common
  • these commands fail under the virtualenv
  • one needs a variety of different virtualenvs

Find text string using jQuery?

Just adding to Tony Miller's answer as this got me 90% towards what I was looking for but still didn't work. Adding .length > 0; to the end of his code got my script working.

 $(function() {
    var foundin = $('*:contains("I am a simple string")').length > 0;
 });

How to add number of days to today's date?

Date.prototype.addDays = function(days)
{
    var dat = new Date(this.valueOf() + days * 24 * 60 * 60 * 1000 );
    return dat;
}

how to assign a block of html code to a javascript variable

Just for reference, here is a benchmark of different technique rendering performances,

http://jsperf.com/zp-string-concatenation/6

m,

Add swipe to delete UITableViewCell

use it :

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == UITableViewCellEditingStyle.Delete {
        langData.removeAtIndex(indexPath.row) //langData is array from i delete values
        tableView.deleteRowsAtIndexPaths([indexPath],  withRowAnimation: UITableViewRowAnimation.Automatic)
    }
}

hope it helps you

Centering text in a table in Twitter Bootstrap

I had the same problem and a better way to solve it without using !important was defining the following in my CSS:

table th.text-center, table td.text-center { 
    text-align: center;
}

That way the specifity of the text-center class works correctly in tables.

Is it possible to pull just one file in Git?

Yes, here is the process:

# Navigate to a directory and initiate a local repository
git init        

# Add remote repository to be tracked for changes:   
git remote add origin https://github.com/username/repository_name.git

# Track all changes made on above remote repository
# This will show files on remote repository not available on local repository
git fetch

# Add file present in staging area for checkout
git check origin/master -m /path/to/file
# NOTE: /path/to/file is a relative path from repository_name
git add /path/to/file

# Verify track of file(s) being committed to local repository
git status

# Commit to local repository
git commit -m "commit message"

# You may perform a final check of the staging area again with git status

How to trigger button click in MVC 4

yo can try this code

@using (Html.BeginForm("SignUp", "Account", FormMethod.Post)){<fieldset>
    <legend>Sign Up</legend>
    <table>
        <tr>
            <td>
                @Html.Label("User Name")
            </td>
            <td>
                @Html.TextBoxFor(account => account.Username)
            </td>
        </tr>
        <tr>
            <td>
                @Html.Label("Email")
            </td>
            <td>
                @Html.TextBoxFor(account => account.Email)
            </td>
        </tr>
        <tr>
            <td>
                @Html.Label("Password")
            </td>
            <td>
                @Html.TextBoxFor(account => account.Password)
            </td>
        </tr>
        <tr>
            <td>
                @Html.Label("Confirm Password")
            </td>
            <td>
                @Html.Password("txtPassword")
            </td>
        </tr>
        <tr>
            <td>
                <input type="submit" name="btnSubmit" value="Sign Up" />
            </td>
        </tr>
    </table>
</fieldset>}

Install sbt on ubuntu

It seems like you installed a zip version of sbt, which is fine. But I suggest you install the native debian package if you are on Ubuntu. That is how I managed to install it on my Ubuntu 12.04. Check it out here: http://www.scala-sbt.org/release/docs/Installing-sbt-on-Linux.html Or simply directly download it from here.

JavaScript null check

An “undefined variable” is different from the value undefined.

An undefined variable:

var a;
alert(b); // ReferenceError: b is not defined

A variable with the value undefined:

var a;
alert(a); // Alerts “undefined”

When a function takes an argument, that argument is always declared even if its value is undefined, and so there won’t be any error. You are right about != null followed by !== undefined being useless, though.

How to hide columns in HTML table?

You can use the nth-child CSS selector to hide a whole column:

#myTable tr > *:nth-child(2) {
    display: none;
}

This works under assumption that a cell of column N (be it a th or td) is always the Nth child element of its row.

Here's a demo.


? If you want the column number to be dynamic, you could do that using querySelectorAll or any framework presenting similar functionality, like jQuery here:

$('#myTable tr > *:nth-child(2)').hide();

Demo with jQuery

(The jQuery solution also works on legacy browsers that don't support nth-child).

Adding a module (Specifically pymorph) to Spyder (Python IDE)

This is assuming a Conda Environment. At a high level, what worked for me was simply configuring my Conda path in Spyder. Here is how I did it:

First, determine the path your env exists at

  1. Create your environment

  2. In the Anaconda navigator, click to "environments" and then hit the play button on the environment you want to open.

  3. Click "Open with Python," you should get an interactive Python shell

  4. Type "import numpy" (choose any package)

  5. Type "numpy" and take a look at the path that looks like this:

C:\\Users\My Name\\.conda\\envs\\pytorch-three\\lib\\site-packages\\numpy\\__init__.py

The important part is the path all the way down to site-packages

For Spyder to be able to read your packages, do the following within Spyder.

  1. Open Spyder from anywhere

  2. Click "tools" and "preferences"

  3. In your Python Interpreter click "Use the following Python interpreter"

  4. From the path above, navigate to your environment and select the Python executable. For me it was here: C:\\Users\My Name\\.conda\\envs\\pytorch-three\\python.exe

  5. Finally, add the C:\\Users\\My Name\\.conda\\envs\\pytorch-three\\libs\\site-libs folder to the path (which will exist in your environment). This is easily done through the little Python icon with the tooltip of "add to path"

I personally didn't need to restart my IDE, but you may need to.

Serialize form data to JSON

I know this doesn't meet the helper function requirement, but the way I've done this is using jQuery's $.each() method

var loginForm = $('.login').serializeArray();
var loginFormObject = {};
$.each(loginForm,
    function(i, v) {
        loginFormObject[v.name] = v.value;
    });

Then I can pass loginFormObject to my backend, or you could create a userobject and save() it in backbone as well.

What is default session timeout in ASP.NET?

The Default Expiration Period for Session is 20 Minutes.

You can update sessionstate and configure the minutes under timeout

<sessionState 
timeout="30">
</sessionState>

How can I add (simple) tracing in C#?

I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String) method where the TraceSource object was initialised with a string making it a 'named source'.

For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt. For the following code:

TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");

I successfully managed to log with the following diagnostics configuration:

<system.diagnostics>
    <sources>
        <source name="sourceName" switchName="switchName">
            <listeners>
                <add
                    name="textWriterTraceListener"
                    type="System.Diagnostics.TextWriterTraceListener"
                    initializeData="tracelog.txt" />
            </listeners>
        </source>
    </sources>

    <switches>
        <add name="switchName" value="Verbose" />
    </switches>
</system.diagnostics>

iPhone X / 8 / 8 Plus CSS media queries

I noticed that the answers here are using: device-width, device-height, min-device-width, min-device-height, max-device-width, max-device-height.

Please refrain from using them since they are deprecated. see MDN for reference. Instead use the regular min-width, max-width and so on. For extra assurance, you can set the min and max to the same px amount. For example:

iPhone X

@media only screen 
    and (width : 375px) 
    and (height : 635px)
    and (orientation : portrait)  
    and (-webkit-device-pixel-ratio : 3) { }

You may also notice that I am using 635px for height. Try it yourself the window height is actually 635px. run iOS simulator for iPhone X and in Safari Web inspector do window.innerHeight. Here are a few useful links on this subject:

Display Images Inline via CSS

You have a line break <br> in-between the second and third images in your markup. Get rid of that, and it'll show inline.

ByRef argument type mismatch in Excel VBA

I don't know why, but it is very important to declare the variables separately if you want to pass variables (as variables) into other procedure or function.

For example there is a procedure which make some manipulation with data: based on ID returns Part Number and Quantity information. ID as constant value, other two arguments are variables.

Public Sub GetPNQty(ByVal ID As String, PartNumber As String, Quantity As Long)

the next main code gives me a "ByRef argument mismatch":

Sub KittingScan()  
Dim BoxPN As String
Dim BoxQty, BoxKitQty As Long

  Call GetPNQty(InputBox("Enter ID:"), BoxPN, BoxQty) 

End sub

and the next one is working as well:

Sub KittingScan()
Dim BoxPN As String
Dim BoxQty As Long
Dim BoxKitQty As Long

  Call GetPNQty(InputBox("Enter ID:"), BoxPN, BoxQty)

End sub

Call Activity method from adapter

In Kotlin there is now a cleaner way by using lambda functions, no need for interfaces:

class MyAdapter(val adapterOnClick: (Any) -> Unit) {
    fun setItem(item: Any) {
        myButton.setOnClickListener { adapterOnClick(item) }
    }
}

class MyActivity {
    override fun onCreate(savedInstanceState: Bundle?) {
        var myAdapter = MyAdapter { item -> doOnClick(item) }
    }


    fun doOnClick(item: Any) {

    }
}

How can I set the maximum length of 6 and minimum length of 6 in a textbox?

You can't set a minimum length on a text field. Otherwise, users wouldn't be able to type in the first five characters.

Your best bet is to validate the input when the form is submitted to ensure that the length is six.

maxlength is not a validation attribute. It is designed to prevent the user from physically typing in more than six characters. The corresponding minlengh is not in scope of the HTML specification, because its implementation would render the textbox unusable.

CSS white space at bottom of page despite having both min-height and height tag

This will remove the margin and padding from your page elements, since there is a paragraph with a script inside that is causing an added margin. this way you should reset it and then you can style the other elements of your page, or you could give that paragraph an id and set margin to zero only for it.

<style>
* {
   margin: 0;
   padding: 0;
}
</style>

Try to put this as the first style.

Calculating and printing the nth prime number

You are trying to do too much in the main method. You need to break this up into more manageable parts. Write a method boolean isPrime(int n) that returns true if a number is prime, and false otherwise. Then modify the main method to use isPrime.

How to find a text inside SQL Server procedures / triggers?

You can find it like

SELECT DISTINCT OBJECT_NAME(id) FROM syscomments WHERE [text] LIKE '%User%'

It will list distinct stored procedure names that contain text like 'User' inside stored procedure. More info

Insert images to XML file

I always convert the byte data to a Base64 encoding and then insert the image.

This is also the way that Word does it, for it's XML files (not that Word is a good example on how to work with XML :P).

AngularJS UI Router - change url without reloading state

Calling

$state.go($state.current, {myParam: newValue}, {notify: false});

will still reload the controller, meaning you will lose state data.

To avoid it, simply declare the parameter as dynamic:

$stateProvider.state({
    name: 'myState',
    url: '/my_state?myParam',
    params: {
        myParam: {
          dynamic: true,    // <----------
        }
    },
    ...
});

Then you don't even need the notify, just calling

$state.go($state.current, {myParam: newValue})

suffices. Neato!

From the documentation:

When dynamic is true, changes to the parameter value will not cause the state to be entered/exited. The resolves will not be re-fetched, nor will views be reloaded.

This can be useful to build UI where the component updates itself when the param values change.

Initializing default values in a struct

You don't even need to define a constructor

struct foo {
    bool a = true;
    bool b = true;
    bool c;
 } bar;

To clarify: these are called brace-or-equal-initializers (because you may also use brace initialization instead of equal sign). This is not only for aggregates: you can use this in normal class definitions. This was added in C++11.

How do you get the logical xor of two variables in Python?

Some of the implementations suggested here will cause repeated evaluation of the operands in some cases, which may lead to unintended side effects and therefore must be avoided.

That said, a xor implementation that returns either True or False is fairly simple; one that returns one of the operands, if possible, is much trickier, because no consensus exists as to which operand should be the chosen one, especially when there are more than two operands. For instance, should xor(None, -1, [], True) return None, [] or False? I bet each answer appears to some people as the most intuitive one.

For either the True- or the False-result, there are as many as five possible choices: return first operand (if it matches end result in value, else boolean), return first match (if at least one exists, else boolean), return last operand (if ... else ...), return last match (if ... else ...), or always return boolean. Altogether, that's 5 ** 2 = 25 flavors of xor.

def xor(*operands, falsechoice = -2, truechoice = -2):
  """A single-evaluation, multi-operand, full-choice xor implementation
  falsechoice, truechoice: 0 = always bool, +/-1 = first/last operand, +/-2 = first/last match"""
  if not operands:
    raise TypeError('at least one operand expected')
  choices = [falsechoice, truechoice]
  matches = {}
  result = False
  first = True
  value = choice = None
  # avoid using index or slice since operands may be an infinite iterator
  for operand in operands:
    # evaluate each operand once only so as to avoid unintended side effects
    value = bool(operand)
    # the actual xor operation
    result ^= value
    # choice for the current operand, which may or may not match end result
    choice = choices[value]
    # if choice is last match;
    # or last operand and the current operand, in case it is last, matches result;
    # or first operand and the current operand is indeed first;
    # or first match and there hasn't been a match so far
    if choice < -1 or (choice == -1 and value == result) or (choice == 1 and first) or (choice > 1 and value not in matches):
      # store the current operand
      matches[value] = operand
    # next operand will no longer be first
    first = False
  # if choice for result is last operand, but they mismatch
  if (choices[result] == -1) and (result != value):
    return result
  else:
    # return the stored matching operand, if existing, else result as bool
    return matches.get(result, result)

testcases = [
  (-1, None, True, {None: None}, [], 'a'),
  (None, -1, {None: None}, 'a', []),
  (None, -1, True, {None: None}, 'a', []),
  (-1, None, {None: None}, [], 'a')]
choices = {-2: 'last match', -1: 'last operand', 0: 'always bool', 1: 'first operand', 2: 'first match'}
for c in testcases:
  print(c)
  for f in sorted(choices.keys()):
    for t in sorted(choices.keys()):
      x = xor(*c, falsechoice = f, truechoice = t)
      print('f: %d (%s)\tt: %d (%s)\tx: %s' % (f, choices[f], t, choices[t], x))
  print()

Using pip behind a proxy with CNTLM

This is what works for me:

pip --proxy proxy url:port command package

Using both Python 2.x and Python 3.x in IPython Notebook

If you’re running Jupyter on Python 3, you can set up a Python 2 kernel like this:

python2 -m pip install ipykernel

python2 -m ipykernel install --user

http://ipython.readthedocs.io/en/stable/install/kernel_install.html

Starting Docker as Daemon on Ubuntu

I had the same issue on 14.04 with docker 1.9.1.

The upstart service command did work when I used sudo, even though I was root:

$ whoami
root
$ service docker status
status: Unbekannter Auftrag: docker

$ sudo service docker status
docker start/running, process 7394

It seems to depend on the environment variables.

service docker status works when becoming root with su -, but not when only using su:

$ su
Password:
$ service docker status
status: unknown job: docker
$ exit
$ su -
Password:
$ service docker status
docker start/running, process 2342

UTC Date/Time String to Timezone

PHP's DateTime object is pretty flexible.

Since the user asked for more than one timezone option, then you can make it generic.

Generic Function

function convertDateFromTimezone($date,$timezone,$timezone_to,$format){
 $date = new DateTime($date,new DateTimeZone($timezone));
 $date->setTimezone( new DateTimeZone($timezone_to) );
 return $date->format($format);
}

Usage:

echo  convertDateFromTimezone('2011-04-21 13:14','UTC','America/New_York','Y-m-d H:i:s');

Output:

2011-04-21 09:14:00

How do I select last 5 rows in a table without sorting?

Well, the "last five rows" are actually the last five rows depending on your clustered index. Your clustered index, by definition, is the way that he rows are ordered. So you really can't get the "last five rows" without some order. You can, however, get the last five rows as it pertains to the clustered index.

SELECT TOP 5 * FROM MyTable
ORDER BY MyCLusteredIndexColumn1, MyCLusteredIndexColumnq, ..., MyCLusteredIndexColumnN DESC

setTimeout in React Native

You can bind this to your function by adding .bind(this) directly to the end of your function definition. You would rewrite your code block as:

setTimeout(function () {
  this.setState({ timePassed: true });
}.bind(this), 1000);

Where can I find php.ini?

find / -name php.ini

Hey... it worked for me!

Get most recent row for given ID

Select [insert your fields here]
from tablename 
where signin = (select max(signin) from tablename where ID = 1)

How to use a variable from a cursor in the select statement of another cursor in pl/sql

You can certainly do something like

SQL> ed
Wrote file afiedt.buf

  1  begin
  2    for d in (select * from dept)
  3    loop
  4      for e in (select * from emp where deptno=d.deptno)
  5      loop
  6        dbms_output.put_line( 'Employee ' || e.ename ||
  7                              ' in department ' || d.dname );
  8      end loop;
  9    end loop;
 10* end;
SQL> /
Employee CLARK in department ACCOUNTING
Employee KING in department ACCOUNTING
Employee MILLER in department ACCOUNTING
Employee smith in department RESEARCH
Employee JONES in department RESEARCH
Employee SCOTT in department RESEARCH
Employee ADAMS in department RESEARCH
Employee FORD in department RESEARCH
Employee ALLEN in department SALES
Employee WARD in department SALES
Employee MARTIN in department SALES
Employee BLAKE in department SALES
Employee TURNER in department SALES
Employee JAMES in department SALES

PL/SQL procedure successfully completed.

Or something equivalent using explicit cursors.

SQL> ed
Wrote file afiedt.buf

  1  declare
  2    cursor dept_cur
  3        is select *
  4             from dept;
  5    d dept_cur%rowtype;
  6    cursor emp_cur( p_deptno IN dept.deptno%type )
  7        is select *
  8             from emp
  9            where deptno = p_deptno;
 10    e emp_cur%rowtype;
 11  begin
 12    open dept_cur;
 13    loop
 14      fetch dept_cur into d;
 15      exit when dept_cur%notfound;
 16      open emp_cur( d.deptno );
 17      loop
 18        fetch emp_cur into e;
 19        exit when emp_cur%notfound;
 20        dbms_output.put_line( 'Employee ' || e.ename ||
 21                              ' in department ' || d.dname );
 22      end loop;
 23      close emp_cur;
 24    end loop;
 25    close dept_cur;
 26* end;
 27  /
Employee CLARK in department ACCOUNTING
Employee KING in department ACCOUNTING
Employee MILLER in department ACCOUNTING
Employee smith in department RESEARCH
Employee JONES in department RESEARCH
Employee SCOTT in department RESEARCH
Employee ADAMS in department RESEARCH
Employee FORD in department RESEARCH
Employee ALLEN in department SALES
Employee WARD in department SALES
Employee MARTIN in department SALES
Employee BLAKE in department SALES
Employee TURNER in department SALES
Employee JAMES in department SALES

PL/SQL procedure successfully completed.

However, if you find yourself using nested cursor FOR loops, it is almost always more efficient to let the database join the two results for you. After all, relational databases are really, really good at joining. I'm guessing here at what your tables look like and how they relate based on the code you posted but something along the lines of

FOR x IN (SELECT *
            FROM all_users,
                 org
           WHERE length(all_users.username) = 3
             AND all_users.username = org.username )
LOOP
  <<do something>>
END LOOP;

Substring with reverse index

Although this is an old question, to support answer by user187291

In case of fixed length of desired substring I would use substr() with negative argument for its short and readable syntax

"xxx_456".substr(-3)

For now it is compatible with common browsers and not yet strictly deprecated.

How to change the author and committer name and e-mail of multiple commits in Git?

I should point out that if the only problem is that the author/email is different from your usual, this is not a problem. The correct fix is to create a file called .mailmap at the base of the directory with lines like

Name you want <email you want> Name you don't want <email you don't want>

And from then on, commands like git shortlog will consider those two names to be the same (unless you specifically tell them not to). See http://schacon.github.com/git/git-shortlog.html for more information.

This has the advantage of all the other solutions here in that you don't have to rewrite history, which can cause problems if you have an upstream, and is always a good way to accidentally lose data.

Of course, if you committed something as yourself and it should really be someone else, and you don't mind rewriting history at this point, changing the commit author is probably a good idea for attribution purposes (in which case I direct you to my other answer here).

Interview question: Check if one string is a rotation of other string

Opera's simple pointer rotation trick works, but it is extremely inefficient in the worst case in running time. Simply imagine a string with many long repetitive runs of characters, ie:

S1 = HELLOHELLOHELLO1HELLOHELLOHELLO2

S2 = HELLOHELLOHELLO2HELLOHELLOHELLO1

The "loop until there's a mismatch, then increment by one and try again" is a horrible approach, computationally.

To prove that you can do the concatenation approach in plain C without too much effort, here is my solution:

  int isRotation(const char* s1, const char* s2) {
        assert(s1 && s2);

        size_t s1Len = strlen(s1);

        if (s1Len != strlen(s2)) return 0;

        char s1SelfConcat[ 2 * s1Len + 1 ];

        sprintf(s1SelfConcat, "%s%s", s1, s1);   

        return (strstr(s1SelfConcat, s2) ? 1 : 0);
}

This is linear in running time, at the expense of O(n) memory usage in overhead.

(Note that the implementation of strstr() is platform-specific, but if particularly brain-dead, can always be replaced with a faster alternative such as the Boyer-Moore algorithm)

Where and why do I have to put the "template" and "typename" keywords?

C++11

Problem

While the rules in C++03 about when you need typename and template are largely reasonable, there is one annoying disadvantage of its formulation

template<typename T>
struct A {
  typedef int result_type;

  void f() {
    // error, "this" is dependent, "template" keyword needed
    this->g<float>();

    // OK
    g<float>();

    // error, "A<T>" is dependent, "typename" keyword needed
    A<T>::result_type n1;

    // OK
    result_type n2; 
  }

  template<typename U>
  void g();
};

As can be seen, we need the disambiguation keyword even if the compiler could perfectly figure out itself that A::result_type can only be int (and is hence a type), and this->g can only be the member template g declared later (even if A is explicitly specialized somewhere, that would not affect the code within that template, so its meaning cannot be affected by a later specialization of A!).

Current instantiation

To improve the situation, in C++11 the language tracks when a type refers to the enclosing template. To know that, the type must have been formed by using a certain form of name, which is its own name (in the above, A, A<T>, ::A<T>). A type referenced by such a name is known to be the current instantiation. There may be multiple types that are all the current instantiation if the type from which the name is formed is a member/nested class (then, A::NestedClass and A are both current instantiations).

Based on this notion, the language says that CurrentInstantiation::Foo, Foo and CurrentInstantiationTyped->Foo (such as A *a = this; a->Foo) are all member of the current instantiation if they are found to be members of a class that is the current instantiation or one of its non-dependent base classes (by just doing the name lookup immediately).

The keywords typename and template are now not required anymore if the qualifier is a member of the current instantiation. A keypoint here to remember is that A<T> is still a type-dependent name (after all T is also type dependent). But A<T>::result_type is known to be a type - the compiler will "magically" look into this kind of dependent types to figure this out.

struct B {
  typedef int result_type;
};

template<typename T>
struct C { }; // could be specialized!

template<typename T>
struct D : B, C<T> {
  void f() {
    // OK, member of current instantiation!
    // A::result_type is not dependent: int
    D::result_type r1;

    // error, not a member of the current instantiation
    D::questionable_type r2;

    // OK for now - relying on C<T> to provide it
    // But not a member of the current instantiation
    typename D::questionable_type r3;        
  }
};

That's impressive, but can we do better? The language even goes further and requires that an implementation again looks up D::result_type when instantiating D::f (even if it found its meaning already at definition time). When now the lookup result differs or results in ambiguity, the program is ill-formed and a diagnostic must be given. Imagine what happens if we defined C like this

template<>
struct C<int> {
  typedef bool result_type;
  typedef int questionable_type;
};

A compiler is required to catch the error when instantiating D<int>::f. So you get the best of the two worlds: "Delayed" lookup protecting you if you could get in trouble with dependent base classes, and also "Immediate" lookup that frees you from typename and template.

Unknown specializations

In the code of D, the name typename D::questionable_type is not a member of the current instantiation. Instead the language marks it as a member of an unknown specialization. In particular, this is always the case when you are doing DependentTypeName::Foo or DependentTypedName->Foo and either the dependent type is not the current instantiation (in which case the compiler can give up and say "we will look later what Foo is) or it is the current instantiation and the name was not found in it or its non-dependent base classes and there are also dependent base classes.

Imagine what happens if we had a member function h within the above defined A class template

void h() {
  typename A<T>::questionable_type x;
}

In C++03, the language allowed to catch this error because there could never be a valid way to instantiate A<T>::h (whatever argument you give to T). In C++11, the language now has a further check to give more reason for compilers to implement this rule. Since A has no dependent base classes, and A declares no member questionable_type, the name A<T>::questionable_type is neither a member of the current instantiation nor a member of an unknown specialization. In that case, there should be no way that that code could validly compile at instantiation time, so the language forbids a name where the qualifier is the current instantiation to be neither a member of an unknown specialization nor a member of the current instantiation (however, this violation is still not required to be diagnosed).

Examples and trivia

You can try this knowledge on this answer and see whether the above definitions make sense for you on a real-world example (they are repeated slightly less detailed in that answer).

The C++11 rules make the following valid C++03 code ill-formed (which was not intended by the C++ committee, but will probably not be fixed)

struct B { void f(); };
struct A : virtual B { void f(); };

template<typename T>
struct C : virtual B, T {
  void g() { this->f(); }
};

int main() { 
  C<A> c; c.g(); 
}

This valid C++03 code would bind this->f to A::f at instantiation time and everything is fine. C++11 however immediately binds it to B::f and requires a double-check when instantiating, checking whether the lookup still matches. However when instantiating C<A>::g, the Dominance Rule applies and lookup will find A::f instead.

FFMPEG mp4 from http live streaming m3u8 file?

Your command is completely incorrect. The output format is not rawvideo and you don't need the bitstream filter h264_mp4toannexb which is used when you want to convert the h264 contained in an mp4 to the Annex B format used by MPEG-TS for example. What you want to use instead is the aac_adtstoasc for the AAC streams.

ffmpeg -i http://.../playlist.m3u8 -c copy -bsf:a aac_adtstoasc output.mp4

jQuery date/time picker

Just to add to the info here, The Fluid Project has a nice wiki write-up overviewing a large number of date and/or time pickers here.

Upload Image using POST form data in Python-requests

In case if you were to pass the image as part of JSON along with other attributes, you can use the below snippet.
client.py

import base64
import json                    

import requests

api = 'http://localhost:8080/test'
image_file = 'sample_image.png'

with open(image_file, "rb") as f:
    im_bytes = f.read()        
im_b64 = base64.b64encode(im_bytes).decode("utf8")

headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
  
payload = json.dumps({"image": im_b64, "other_key": "value"})
response = requests.post(api, data=payload, headers=headers)
try:
    data = response.json()     
    print(data)                
except requests.exceptions.RequestException:
    print(response.text)

server.py

import io
import json                    
import base64                  
import logging             
import numpy as np
from PIL import Image

from flask import Flask, request, jsonify, abort

app = Flask(__name__)          
app.logger.setLevel(logging.DEBUG)
  
  
@app.route("/test", methods=['POST'])
def test_method():         
    # print(request.json)      
    if not request.json or 'image' not in request.json: 
        abort(400)
             
    # get the base64 encoded string
    im_b64 = request.json['image']

    # convert it into bytes  
    img_bytes = base64.b64decode(im_b64.encode('utf-8'))

    # convert bytes data to PIL Image object
    img = Image.open(io.BytesIO(img_bytes))

    # PIL image object to numpy array
    img_arr = np.asarray(img)      
    print('img shape', img_arr.shape)

    # process your img_arr here    
    
    # access other keys of json
    # print(request.json['other_key'])

    result_dict = {'output': 'output_key'}
    return result_dict
  
  
def run_server_api():
    app.run(host='0.0.0.0', port=8080)
  
  
if __name__ == "__main__":     
    run_server_api()

Error in strings.xml file in Android

You may be able to use unicode equivalent both apostrophe and other characters which are not supported in xml string. Apostrophe's equivalent is "\u0027" .

Can regular expressions be used to match nested patterns?

as zsolt mentioned, some regex engines support recursion -- of course, these are typically the ones that use a backtracking algorithm so it won't be particularly efficient. example: /(?>[^{}]*){(?>[^{}]*)(?R)*(?>[^{}]*)}/sm

Check if a process is running or not on Windows with Python

Would you be happy with your Python command running another program to get the info?

If so, I'd suggest you have a look at PsList and all its options. For example, The following would tell you about any running iTunes process

PsList itunes

If you can work out how to interpret the results, this should hopefully get you going.

Edit:

When I'm not running iTunes, I get the following:

pslist v1.29 - Sysinternals PsList
Copyright (C) 2000-2009 Mark Russinovich
Sysinternals

Process information for CLARESPC:

Name                Pid Pri Thd  Hnd   Priv        CPU Time    Elapsed Time
iTunesHelper       3784   8  10  229   3164     0:00:00.046     3:41:05.053

With itunes running, I get this one extra line:

iTunes              928   8  24  813 106168     0:00:08.734     0:02:08.672

However, the following command prints out info only about the iTunes program itself, i.e. with the -e argument:

pslist -e itunes

How to get the xml node value in string

You should use .Load and not .LoadXML

MSDN Link

"The LoadXml method is for loading an XML string directly. You want to use the Load method instead."

ref : Link

How do I pass data to Angular routed components?

<div class="button" click="routeWithData()">Pass data and route</div>

well the easiest way to do it in angular 6 or other versions I hope is to simply to define your path with the amount of data you want to pass

{path: 'detailView/:id', component: DetailedViewComponent}

as you can see from my routes definition, I have added the /:id to stand to the data I want to pass to the component via router navigation. Therefore your code will look like

<a class="btn btn-white-view" [routerLink]="[ '/detailView',list.id]">view</a>

in order to read the id on the component, just import ActivatedRoute like

import { ActivatedRoute } from '@angular/router'

and on the ngOnInit is where you retrieve the data

ngOnInit() {
       this.sub = this.route.params.subscribe(params => {
        this.id = params['id'];
        });
        console.log(this.id);
      }

you can read more in this article https://www.tektutorialshub.com/angular-passing-parameters-to-route/

How do I compare two Integers?

This is what the equals method does:

public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
    return false;
}

As you can see, there's no hash code calculation, but there are a few other operations taking place there. Although x.intValue() == y.intValue() might be slightly faster, you're getting into micro-optimization territory there. Plus the compiler might optimize the equals() call anyway, though I don't know that for certain.

I generally would use the primitive int, but if I had to use Integer, I would stick with equals().

Sum the digits of a number

Here is a solution without any loop or recursion but works for non-negative integers only (Python3):

def sum_digits(n):
    if n > 0:
        s = (n-1) // 9    
        return n-9*s
    return 0

Commenting out a set of lines in a shell script

As per this site:

#!/bin/bash
foo=bar
: '
This is a test comment
Author foo bar
Released under GNU 
'

echo "Init..."
# rest of script

powershell - list local users and their groups

try this one :),

Get-LocalGroup | %{ $groups = "$(Get-LocalGroupMember -Group $_.Name | %{ $_.Name } | Out-String)"; Write-Output "$($_.Name)>`r`n$($groups)`r`n" }

Best way to pass parameters to jQuery's .load()

As Davide Gualano has been told. This one

$("#myDiv").load("myScript.php?var=x&var2=y&var3=z")

use GET method for sending the request, and this one

$("#myDiv").load("myScript.php", {var:x, var2:y, var3:z})

use POST method for sending the request. But any limitation that is applied to each method (post/get) is applied to the alternative usages that has been mentioned in the question.

For example: url length limits the amount of sending data in GET method.

Close window automatically after printing dialog closes

The following solution is working for IE9, IE8, Chrome, and FF newer versions as of 2014-03-10. The scenario is this: you are in a window (A), where you click a button/link to launch the printing process, then a new window (B) with the contents to be printed is opened, the printing dialog is shown immediately, and you can either cancel or print, and then the new window (B) closes automatically.

The following code allows this. This javascript code is to be placed in the html for window A (not for window B):

/**
 * Opens a new window for the given URL, to print its contents. Then closes the window.
 */
function openPrintWindow(url, name, specs) {
  var printWindow = window.open(url, name, specs);
    var printAndClose = function() {
        if (printWindow.document.readyState == 'complete') {
            clearInterval(sched);
            printWindow.print();
            printWindow.close();
        }
    }
    var sched = setInterval(printAndClose, 200);
};

The button/link to launch the process has simply to invoke this function, as in:

openPrintWindow('http://www.google.com', 'windowTitle', 'width=820,height=600');

Android: Storing username and password?

You can also look at the SampleSyncAdapter sample from the SDK. It may help you.

Background blur with CSS

You can use a pseudo-element to position as the background of the content with the same image as the background, but blurred with the new CSS3 filter.

You can see it in action here: http://codepen.io/jiserra/pen/JzKpx

I made that for customizing a select, but I added the blur background effect.

How do I get the current date and time in PHP?

According to the article How to Get Current Datetime (NOW) with PHP, there are two common ways to get the current date. To get current datetime (now) with PHP, you can use the date class with any PHP version, or better the datetime class with PHP >= 5.2.

Various date format expressions are available here.

Example using date

This expression will return NOW in format Y-m-d H:i:s.

<?php
    echo date('Y-m-d H:i:s');
?>

Example using datetime class

This expression will return NOW in format Y-m-d H:i:s.

<?php
    $dt = new DateTime();
    echo $dt->format('Y-m-d H:i:s');
?>

How do I get an apk file from an Android device?

Yet another bash script (i.e. will work for most unix-based systems). Based on the answer by Pedro Rodrigues, but is slightly easier to use.

Improvements over Pedro's version:

  1. Original approach did not work for me on Android 7: adb pull kept complaining about no such file or directory while adb shell could access the file. Hence I used different approach, with temporary file.
  2. When launched with no arguments, my script will just list all available packages. When partial package name is provided, it will try to guess the full package name. It will complain if there are several possible expansions.
  3. I don't hardcode destination path; instead APKs are saved to current working directory.

Save this to an executable file:

#!/bin/bash
# Obtain APK file for given package from the device connected over ADB

if [ -z "$1" ]; then
    echo "Available packages: "
    adb shell pm list packages | sed 's/^package://'
    echo "You must pass a package to this function!"
    echo "Ex.: android_pull_apk \"com.android.contacts\""
    exit 1
fi

fullname=$(adb shell pm list packages | sed 's/^package://' | grep $1)
if [ -z "$fullname" ]; then
    echo "Could not find package matching $1"
    exit 1
fi
if [ $(echo "$fullname" | wc -l) -ne 1 ]; then
    echo "Too many packages matched:"
    echo "$fullname"
    exit 1
fi
echo "Will fetch APK for package $fullname"

apk_path="`adb shell pm path $fullname | sed -e 's/package://g' | tr '\n' ' ' | tr -d '[:space:]'`"
apk_name="`basename ${apk_path} | tr '\n' ' ' | tr -d '[:space:]'`"

destination="${fullname}.apk"

tmp=$(mktemp --dry-run --tmpdir=/sdcard --suffix=.apk)
adb shell cp "${apk_path}" "$tmp"
adb pull "$tmp" "$destination"
adb shell rm "$tmp"

[ $? -eq 0 ] && echo -e "\nAPK saved in \"$destination\""

SQL Server - after insert trigger - update another column in the same table

Another option would be to enclose the update statement in an IF statement and call TRIGGER_NESTLEVEL() to restrict the update being run a second time.

CREATE TRIGGER Table_A_Update ON Table_A AFTER UPDATE 
AS
IF ((SELECT TRIGGER_NESTLEVEL()) < 2)
BEGIN
    UPDATE a
    SET Date_Column = GETDATE()
    FROM Table_A a
    JOIN inserted i ON a.ID = i.ID
END

When the trigger initially runs the TRIGGER_NESTLEVEL is set to 1 so the update statement will be executed. That update statement will in turn fire that same trigger except this time the TRIGGER_NESTLEVEL is set to 2 and the update statement will not be executed.

You could also check the TRIGGER_NESTLEVEL first and if its greater than 1 then call RETURN to exit out of the trigger.

IF ((SELECT TRIGGER_NESTLEVEL()) > 1) RETURN;

How do you get an iPhone's device name

From the UIDevice class:

As an example: [[UIDevice currentDevice] name];

The UIDevice is a class that provides information about the iPhone or iPod Touch device.

Some of the information provided by UIDevice is static, such as device name or system version.

source: http://servin.com/iphone/uidevice/iPhone-UIDevice.html

Offical Documentation: Apple Developer Documentation > UIDevice Class Reference

Change the background color in a twitter bootstrap modal?

remove bootstrap modal background try this one

.modal-backdrop {
   background: none;
}

List append() in for loop

No need to re-assign.

a=[]
for i in range(5):    
    a.append(i)
a

Access cell value of datatable

data d is in row 0 and column 3 for value d :

DataTable table;
String d = (String)table.Rows[0][3];

TSQL How do you output PRINT in a user defined function?

Tip: generate error.

declare @Day int, @Config_Node varchar(50)

    set @Config_Node = 'value to trace'

    set @Day = @Config_Node

You will get this message:

Conversion failed when converting the varchar value 'value to trace' to data type int.

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

Any way to return PHP `json_encode` with encode UTF-8 and not Unicode?

I resolved my problem doing this:

  • The .php file is encoded to ANSI. In this file is the function to create the .json file.
  • I use json_encode($array, JSON_UNESCAPED_UNICODE) to encode the data;

The result is a .json file encoded to ANSI as UTF-8.

struct in class

I declared class B inside class A, how do I access it?

Just because you declare your struct B inside class A does not mean that an instance of class A automatically has the properties of struct B as members, nor does it mean that it automatically has an instance of struct B as a member.

There is no true relation between the two classes (A and B), besides scoping.


struct A { 
  struct B { 
    int v;
  };  

  B inner_object;
};

int
main (int argc, char *argv[]) {
  A object;
    object.inner_object.v = 123;
}

Using an HTML button to call a JavaScript function

There are a few ways to handle events with HTML/DOM. There's no real right or wrong way but different ways are useful in different situations.

1: There's defining it in the HTML:

<input id="clickMe" type="button" value="clickme" onclick="doFunction();" />

2: There's adding it to the DOM property for the event in Javascript:

//- Using a function pointer:
document.getElementById("clickMe").onclick = doFunction;

//- Using an anonymous function:
document.getElementById("clickMe").onclick = function () { alert('hello!'); };

3: And there's attaching a function to the event handler using Javascript:

var el = document.getElementById("clickMe");
if (el.addEventListener)
    el.addEventListener("click", doFunction, false);
else if (el.attachEvent)
    el.attachEvent('onclick', doFunction);

Both the second and third methods allow for inline/anonymous functions and both must be declared after the element has been parsed from the document. The first method isn't valid XHTML because the onclick attribute isn't in the XHTML specification.

The 1st and 2nd methods are mutually exclusive, meaning using one (the 2nd) will override the other (the 1st). The 3rd method will allow you to attach as many functions as you like to the same event handler, even if the 1st or 2nd method has been used too.

Most likely, the problem lies somewhere in your CapacityChart() function. After visiting your link and running your script, the CapacityChart() function runs and the two popups are opened (one is closed as per the script). Where you have the following line:

CapacityWindow.document.write(s);

Try the following instead:

CapacityWindow.document.open("text/html");
CapacityWindow.document.write(s);
CapacityWindow.document.close();

EDIT
When I saw your code I thought you were writing it specifically for IE. As others have mentioned you will need to replace references to document.all with document.getElementById. However, you will still have the task of fixing the script after this so I would recommend getting it working in at least IE first as any mistakes you make changing the code to work cross browser could cause even more confusion. Once it's working in IE it will be easier to tell if it's working in other browsers whilst you're updating the code.

Are the decimal places in a CSS width respected?

Although fractional pixels may appear to round up on individual elements (as @SkillDrick demonstrates very well) it's important to know that the fractional pixels are actually respected in the actual box model.

This can best be seen when elements are stacked next to (or on top of) each other; in other words, if I were to place 400 0.5 pixel divs side by side, they would have the same width as a single 200 pixel div. If they all actually rounded up to 1px (as looking at individual elements would imply) we'd expect the 200px div to be half as long.

This can be seen in this runnable code snippet:

_x000D_
_x000D_
body {_x000D_
  color:            white;_x000D_
  font-family:      sans-serif;_x000D_
  font-weight:      bold;_x000D_
  background-color: #334;_x000D_
}_x000D_
_x000D_
.div_house div {_x000D_
  height:           10px;_x000D_
  background-color: orange;_x000D_
  display:          inline-block;_x000D_
}_x000D_
_x000D_
div#small_divs div {_x000D_
  width:            0.5px;_x000D_
}_x000D_
_x000D_
div#large_div div {_x000D_
  width:            200px;_x000D_
}
_x000D_
<div class="div_house" id="small_divs">_x000D_
  <p>0.5px div x 400</p>_x000D_
  <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>_x000D_
</div>_x000D_
<br>_x000D_
<div class="div_house" id="large_div">_x000D_
  <p>200px div x 1</p>_x000D_
  <div></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Printing string variable in Java

You could also use BufferedReader:

import java.io.*;

public class TestApplication {
   public static void main (String[] args) {
      System.out.print("Enter a password: ");
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      String password = null;
      try {
         password = br.readLine();
      } catch (IOException e) {
         System.out.println("IO error trying to read your password!");
         System.exit(1);
      }
      System.out.println("Successfully read your password.");
   }
}

Pass C# ASP.NET array to Javascript array

This is to supplement zerkms's answer.

To pass data across language barriers, you would need a way to represent the data as a string by serializing the data. One of the serialization methods for JavaScript is JSON. In zerkms's example, the code would be placed inside of an aspx page. To combine his example and yours together on one aspx page, you would have,

<%
    int[] numbers = new int[5];
    // Fill up numbers...

    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
%>

somewhere later on the aspx page

<script type="text/javascript">
    var jsVariable = <%= serializer.Serialize(numbers) %>;
</script>

This answer though, assumes that you are generating JavaScript from the initial page load. As per the comments in your post, this could have been done via AJAX. In that case, you would have the server respond with the result of the serialization and then deserialize it in JavaScript using your favorite framework.

Note: Also do not mark this as an answer since I wanted the syntax highlighting to make another answer more clear.

How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?

SELECT c1, c2, c3, c4, c5 FROM table1 WHERE c3 = (select max(c3) from table)

SELECT * FROM table1 WHERE c3 = (select max(c3) from table1)

How to add an UIViewController's view as subview

Use:

[self.view addSubview:obj.view];

how to instanceof List<MyType>?

That is not possible because the datatype erasure at compile time of generics. Only possible way of doing this is to write some kind of wrapper that holds which type the list holds:

public class GenericList <T> extends ArrayList<T>
{
     private Class<T> genericType;

     public GenericList(Class<T> c)
     {
          this.genericType = c;
     }

     public Class<T> getGenericType()
     {
          return genericType;
     }
}

Want to move a particular div to right

For me, I used margin-left: auto; which is more responsive with horizontal resizing.

Returning a value from thread?

I'm no kind of expert in threading, that's why I did it like this:

I created a Settings file and

Inside the new thread:

Setting.Default.ValueToBeSaved;
Setting.Default.Save();

Then I pick up that value whenever I need it.

Excel formula to reference 'CELL TO THE LEFT'

You could use a VBA script that changes the conditional formatting of a selection (you might have to adjust the condition & formatting accordingly):

For Each i In Selection
i.FormatConditions.Delete
i.FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, Formula1:="=" & i.Offset(0, -1).Address
With i.FormatConditions(1).Font
    .Bold = True
End With
Next i

Assembly - JG/JNLE/JL/JNGE after CMP

Wikibooks has a fairly good summary of jump instructions. Basically, there's actually two stages:

cmp_instruction op1, op2

Which sets various flags based on the result, and

jmp_conditional_instruction address

which will execute the jump based on the results of those flags.

Compare (cmp) will basically compute the subtraction op1-op2, however, this is not stored; instead only flag results are set. So if you did cmp eax, ebx that's the same as saying eax-ebx - then deciding based on whether that is positive, negative or zero which flags to set.

More detailed reference here.

TypeScript sorting an array

Numbers

When sorting numbers, you can use the compact comparison:

var numericArray: number[] = [2, 3, 4, 1, 5, 8, 11];

var sortedArray: number[] = numericArray.sort((n1,n2) => n1 - n2);

i.e. - rather than <.

Other Types

If you are comparing anything else, you'll need to convert the comparison into a number.

var stringArray: string[] = ['AB', 'Z', 'A', 'AC'];

var sortedArray: string[] = stringArray.sort((n1,n2) => {
    if (n1 > n2) {
        return 1;
    }

    if (n1 < n2) {
        return -1;
    }

    return 0;
});

Objects

For objects, you can sort based on a property, bear in mind the above information about being able to short-hand number types. The below example works irrespective of the type.

var objectArray: { age: number; }[] = [{ age: 10}, { age: 1 }, {age: 5}];

var sortedArray: { age: number; }[] = objectArray.sort((n1,n2) => {
    if (n1.age > n2.age) {
        return 1;
    }

    if (n1.age < n2.age) {
        return -1;
    }

    return 0;
});

How to prevent form from submitting multiple times from client side?

This works very fine for me. It submit the farm and make button disable and after 2 sec active the button.

<button id="submit" type="submit" onclick="submitLimit()">Yes</button>

function submitLimit() {
var btn = document.getElementById('submit')
setTimeout(function() {
    btn.setAttribute('disabled', 'disabled');
}, 1);

setTimeout(function() {
    btn.removeAttribute('disabled');
}, 2000);}

In ECMA6 Syntex

function submitLimit() {
submitBtn = document.getElementById('submit');

setTimeout(() => { submitBtn.setAttribute('disabled', 'disabled') }, 1);

setTimeout(() => { submitBtn.removeAttribute('disabled') }, 4000);}

Converting SVG to PNG using C#

To add to the response from @Anish, if you are having issues with not seeing the text when exporting the SVG to an image, you can create a recursive function to loop through the children of the SVGDocument, try to cast it to a SvgText if possible (add your own error checking) and set the font family and style.

    foreach(var child in svgDocument.Children)
    {
        SetFont(child);
    }

    public void SetFont(SvgElement element)
    {
        foreach(var child in element.Children)
        {
            SetFont(child); //Call this function again with the child, this will loop
                            //until the element has no more children
        }

        try
        {
            var svgText = (SvgText)parent; //try to cast the element as a SvgText
                                           //if it succeeds you can modify the font

            svgText.Font = new Font("Arial", 12.0f);
            svgText.FontSize = new SvgUnit(12.0f);
        }
        catch
        {

        }
    }

Let me know if there are questions.

Line break in SSRS expression

It wasn't working for me either. vbcrlf and Environment.Newline() both had no effect. My problem was that the Placeholder Properties had a Markup type of HTML. When I changed it to None, it worked like a champ!

Sqlite primary key on multiple columns

PRIMARY KEY (id, name) didn't work for me. Adding a constraint did the job instead.

CREATE TABLE IF NOT EXISTS customer (
    id INTEGER, name TEXT,
    user INTEGER,
    CONSTRAINT PK_CUSTOMER PRIMARY KEY (user, id)
)

Is there an onSelect event or equivalent for HTML <select>?

So my goal was to be able to select the same value multiple times which essentially overwrites the the onchange() function and turn it into a useful onclick() method.

Based on the suggestions above I came up with this which works for me.

<select name="ab" id="hi" onchange="if (typeof(this.selectedIndex) != undefined) {alert($('#hi').val()); this.blur();}" onfocus="this.selectedIndex = -1;">
    <option value="-1">--</option>
    <option value="1">option 1</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
</select>

http://jsfiddle.net/dR9tH/19/

Xcode - iPhone - profile doesn't match any valid certificate-/private-key pair in the default keychain

My problem was my Target profile didn't have the proper code signing option selected:

Target Menu -> Code Signing -> Code Signing Identity

Choose "iPhone developer" then select the provisional profile you created.

Bad Request - Invalid Hostname IIS7

Make sure IIS is listening to your port.

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

Change a Nullable column to NOT NULL with Default Value

You may have to first update all the records that are null to the default value then use the alter table statement.

Update dbo.TableName
Set
Created="01/01/2000"
where Created is NULL

How to split a comma-separated value to columns

;WITH Split_Names (Value,Name, xmlname)
AS
(
    SELECT Value,
    Name,
    CONVERT(XML,'<Names><name>'  
    + REPLACE(Name,',', '</name><name>') + '</name></Names>') AS xmlname
      FROM tblnames
)

 SELECT Value,      
 xmlname.value('/Names[1]/name[1]','varchar(100)') AS Name,    
 xmlname.value('/Names[1]/name[2]','varchar(100)') AS Surname
 FROM Split_Names

and also check the link below for reference

http://jahaines.blogspot.in/2009/06/converting-delimited-string-of-values.html

How to properly create composite primary keys - MYSQL

I would use a composite (multi-column) key.

CREATE TABLE INFO (
    t1ID INT,
    t2ID INT,
    PRIMARY KEY (t1ID, t2ID)
) 

This way you can have t1ID and t2ID as foreign keys pointing to their respective tables as well.

Get exit code for command in bash/ksh

It should be $cmd instead of $($cmd). Works fine with that on my box.

Edit: Your script works only for one-word commands, like ls. It will not work for "ls cpp". For this to work, replace cmd="$1"; $cmd with "$@". And, do not run your script as command="some cmd"; safeRun command, run it as safeRun some cmd.

Also, when you have to debug your bash scripts, execute with '-x' flag. [bash -x s.sh].

Does static constexpr variable inside a function make sense?

In addition to given answer, it's worth noting that compiler is not required to initialize constexpr variable at compile time, knowing that the difference between constexpr and static constexpr is that to use static constexpr you ensure the variable is initialized only once.

Following code demonstrates how constexpr variable is initialized multiple times (with same value though), while static constexpr is surely initialized only once.

In addition the code compares the advantage of constexpr against const in combination with static.

#include <iostream>
#include <string>
#include <cassert>
#include <sstream>

const short const_short = 0;
constexpr short constexpr_short = 0;

// print only last 3 address value numbers
const short addr_offset = 3;

// This function will print name, value and address for given parameter
void print_properties(std::string ref_name, const short* param, short offset)
{
    // determine initial size of strings
    std::string title = "value \\ address of ";
    const size_t ref_size = ref_name.size();
    const size_t title_size = title.size();
    assert(title_size > ref_size);

    // create title (resize)
    title.append(ref_name);
    title.append(" is ");
    title.append(title_size - ref_size, ' ');

    // extract last 'offset' values from address
    std::stringstream addr;
    addr << param;
    const std::string addr_str = addr.str();
    const size_t addr_size = addr_str.size();
    assert(addr_size - offset > 0);

    // print title / ref value / address at offset
    std::cout << title << *param << " " << addr_str.substr(addr_size - offset) << std::endl;
}

// here we test initialization of const variable (runtime)
void const_value(const short counter)
{
    static short temp = const_short;
    const short const_var = ++temp;
    print_properties("const", &const_var, addr_offset);

    if (counter)
        const_value(counter - 1);
}

// here we test initialization of static variable (runtime)
void static_value(const short counter)
{
    static short temp = const_short;
    static short static_var = ++temp;
    print_properties("static", &static_var, addr_offset);

    if (counter)
        static_value(counter - 1);
}

// here we test initialization of static const variable (runtime)
void static_const_value(const short counter)
{
    static short temp = const_short;
    static const short static_var = ++temp;
    print_properties("static const", &static_var, addr_offset);

    if (counter)
        static_const_value(counter - 1);
}

// here we test initialization of constexpr variable (compile time)
void constexpr_value(const short counter)
{
    constexpr short constexpr_var = constexpr_short;
    print_properties("constexpr", &constexpr_var, addr_offset);

    if (counter)
        constexpr_value(counter - 1);
}

// here we test initialization of static constexpr variable (compile time)
void static_constexpr_value(const short counter)
{
    static constexpr short static_constexpr_var = constexpr_short;
    print_properties("static constexpr", &static_constexpr_var, addr_offset);

    if (counter)
        static_constexpr_value(counter - 1);
}

// final test call this method from main()
void test_static_const()
{
    constexpr short counter = 2;

    const_value(counter);
    std::cout << std::endl;

    static_value(counter);
    std::cout << std::endl;

    static_const_value(counter);
    std::cout << std::endl;

    constexpr_value(counter);
    std::cout << std::endl;

    static_constexpr_value(counter);
    std::cout << std::endl;
}

Possible program output:

value \ address of const is               1 564
value \ address of const is               2 3D4
value \ address of const is               3 244

value \ address of static is              1 C58
value \ address of static is              1 C58
value \ address of static is              1 C58

value \ address of static const is        1 C64
value \ address of static const is        1 C64
value \ address of static const is        1 C64

value \ address of constexpr is           0 564
value \ address of constexpr is           0 3D4
value \ address of constexpr is           0 244

value \ address of static constexpr is    0 EA0
value \ address of static constexpr is    0 EA0
value \ address of static constexpr is    0 EA0

As you can see yourself constexpr is initilized multiple times (address is not the same) while static keyword ensures that initialization is performed only once.

Tkinter: "Python may not be configured for Tk"

To anyone using Windows and Windows Subsystem for Linux, make sure that when you run the python command from the command line, it's not accidentally running the python installation from WSL! This gave me quite a headache just now. A quick check you can do for this is just
which <python command you're using>
If that prints something like /usr/bin/python2 even though you're in powershell, that's probably what's going on.

HtmlEncode from Class Library

Import System.Web Or call the System.Web.HttpUtility which contains it

You will need to add the reference to the DLL if it isn't there already

string TestString = "This is a <Test String>.";
string EncodedString = System.Web.HttpUtility.HtmlEncode(TestString);

File Upload to HTTP server in iphone programming

This is a great wrapper, but when posting to a asp.net web page, two additional post values need to be set:

    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    //ADD THESE, BECAUSE ASP.NET is Expecting them for validation
    //Even if they are empty you will be able to post the file
    [request setPostValue:@"" forKey:@"__VIEWSTATE"];
    [request setPostValue:@"" forKey:@"__EVENTVALIDATION"]; 
    ///

    [request setFile:FIleName forKey:@"fileupload_control_Name"];
    [request startSynchronous];

CharSequence VS String in Java?

CharSequence

A CharSequence is an interface, not an actual class. An interface is just a set of rules (methods) that a class must contain if it implements the interface. In Android a CharSequence is an umbrella for various types of text strings. Here are some of the common ones:

(You can read more about the differences between these here.)

If you have a CharSequence object, then it is actually an object of one of the classes that implement CharSequence. For example:

CharSequence myString = "hello";
CharSequence mySpannableStringBuilder = new SpannableStringBuilder();

The benefit of having a general umbrella type like CharSequence is that you can handle multiple types with a single method. For example, if I have a method that takes a CharSequence as a parameter, I could pass in a String or a SpannableStringBuilder and it would handle either one.

public int getLength(CharSequence text) {
    return text.length();
}

String

You could say that a String is just one kind of CharSequence. However, unlike CharSequence, it is an actual class, so you can make objects from it. So you could do this:

String myString = new String();

but you can't do this:

CharSequence myCharSequence = new CharSequence(); // error: 'CharSequence is abstract; cannot be instantiated

Since CharSequence is just a list of rules that String conforms to, you could do this:

CharSequence myString = new String();

That means that any time a method asks for a CharSequence, it is fine to give it a String.

String myString = "hello";
getLength(myString); // OK

// ...

public int getLength(CharSequence text) {
    return text.length();
}

However, the opposite is not true. If the method takes a String parameter, you can't pass it something that is only generally known to be a CharSequence, because it might actually be a SpannableString or some other kind of CharSequence.

CharSequence myString = "hello";
getLength(myString); // error

// ...

public int getLength(String text) {
    return text.length();
}

MySQL Delete all rows from table and reset ID to zero

If you cannot use TRUNCATE (e.g. because of foreign key constraints) you can use an alter table after deleting all rows to restart the auto_increment:

ALTER TABLE mytable AUTO_INCREMENT = 1

how to install Lex and Yacc in Ubuntu?

Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:

sudo apt-get install bison flex

There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.

Which MySQL data type to use for storing boolean values

You can use BOOL, BOOLEAN data type for storing boolean values.

These types are synonyms for TINYINT(1)

However, the BIT(1) data type makes more sense to store a boolean value (either true[1] or false[0]) but TINYINT(1) is easier to work with when you're outputting the data, querying and so on and to achieve interoperability between MySQL and other databases. You can also check this answer or thread.

MySQL also converts BOOL, BOOLEAN data types to TINYINT(1).

Further, read documentation

Why can't I inherit static classes?

Although you can access "inherited" static members through the inherited classes name, static members are not really inherited. This is in part why they can't be virtual or abstract and can't be overridden. In your example, if you declared a Base.Method(), the compiler will map a call to Inherited.Method() back to Base.Method() anyway. You might as well call Base.Method() explicitly. You can write a small test and see the result with Reflector.

So... if you can't inherit static members, and if static classes can contain only static members, what good would inheriting a static class do?

SQL Query to fetch data from the last 30 days?

SELECT COUNT(job_id) FROM jobs WHERE posted_date < NOW()-30;

Now() returns the current Date and Time.

Android Service Stops When App Is Closed

Just override onDestroy method in your first visible activity like after splash you have home page and while redirecting from splash to home page you have already finish splash. so put on destroy in home page. and stop service in that method.

How can I capitalize the first letter of each word in a string?

A quick function worked for Python 3

Python 3.6.9 (default, Nov  7 2019, 10:44:02) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> capitalizeFirtChar = lambda s: s[:1].upper() + s[1:]
>>> print(capitalizeFirtChar('??????? ????? ????????. ???????? ?? ?????? ? ??????????????!'))
??????? ????? ????????. ???????? ?? ?????? ? ??????????????!
>>> print(capitalizeFirtChar('??? ???? ?????? ???????! ??? ???? ?????? ????? ???.'))
??? ???? ?????? ???????! ??? ???? ?????? ????? ???.
>>> print(capitalizeFirtChar('faith and Labour make Dreams come true.'))
Faith and Labour make Dreams come true.

Create a user with all privileges in Oracle

My issue was, i am unable to create a view with my "scott" user in oracle 11g edition. So here is my solution for this

Error in my case

SQL>create view v1 as select * from books where id=10;

insufficient privileges.

Solution

1)open your cmd and change your directory to where you install your oracle database. in my case i was downloaded in E drive so my location is E:\app\B_Amar\product\11.2.0\dbhome_1\BIN> after reaching in the position you have to type sqlplus sys as sysdba

E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba

2) Enter password: here you have to type that password that you give at the time of installation of oracle software.

3) Here in this step if you want create a new user then you can create otherwise give all the privileges to existing user.

for creating new user

SQL> create user abc identified by xyz;

here abc is user and xyz is password.

giving all the privileges to abc user

SQL> grant all privileges to abc;

 grant succeeded. 

if you are seen this message then all the privileges are giving to the abc user.

4) Now exit from cmd, go to your SQL PLUS and connect to the user i.e enter your username & password.Now you can happily create view.

In My case

in cmd E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba

SQL> grant all privileges to SCOTT;

grant succeeded.

Now I can create views.

What is the difference between a 'closure' and a 'lambda'?

This question is old and got many answers.
Now with Java 8 and Official Lambda that are unofficial closure projects, it revives the question.

The answer in Java context (via Lambdas and closures — what’s the difference?):

"A closure is a lambda expression paired with an environment that binds each of its free variables to a value. In Java, lambda expressions will be implemented by means of closures, so the two terms have come to be used interchangeably in the community."

Format bytes to kilobytes, megabytes, gigabytes

Flexible solution:

function size($size, array $options=null) {

    $o = [
        'binary' => false,
        'decimalPlaces' => 2,
        'decimalSeparator' => '.',
        'thausandsSeparator' => '',
        'maxThreshold' => false, // or thresholds key
        'suffix' => [
            'thresholds' => ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'],
            'decimal' => ' {threshold}B',
            'binary' => ' {threshold}iB',
            'bytes' => ' B'
        ]
    ];

    if ($options !== null)
        $o = array_replace_recursive($o, $options);

    $base = $o['binary'] ? 1024 : 1000;
    $exp = $size ? floor(log($size) / log($base)) : 0;

    if (($o['maxThreshold'] !== false) &&
        ($o['maxThreshold'] < $exp)
    )
        $exp = $o['maxThreshold'];

    return !$exp
        ? (round($size) . $o['suffix']['bytes'])
        : (
            number_format(
                $size / pow($base, $exp),
                $o['decimalPlaces'],
                $o['decimalSeparator'],
                $o['thausandsSeparator']
            ) .
            str_replace(
                '{threshold}',
                $o['suffix']['thresholds'][$exp],
                $o['suffix'][$o['binary'] ? 'binary' : 'decimal']
            )
        );
}

var_dump(size(disk_free_space('/')));
// string(8) "14.63 GB"
var_dump(size(disk_free_space('/'), ['binary' => true]));
// string(9) "13.63 GiB"
var_dump(size(disk_free_space('/'), ['maxThreshold' => 2]));
// string(11) "14631.90 MB"
var_dump(size(disk_free_space('/'), ['binary' => true, 'maxThreshold' => 2]));
// string(12) "13954.07 MiB"

Max value of Xmx and Xms in Eclipse?

Why do you need -Xms768 (small heap must be at least 768...)?

That means any java process (search in eclipse) will start with 768m memory allocated, doesn't that? That is why your eclipse isn't able to start properly.

Try -Xms16 -Xmx2048m, for instance.

HTML+CSS: How to force div contents to stay in one line?

Everybody jumped on this one!!! I too made a fiddle:

http://jsfiddle.net/audetwebdesign/kh4aR/

RobAgar gets a point for pointing out white-space:nowrap first.

Couple of things here, you need overflow: hidden if you don't want to see the extra characters poking out into your layout.

Also, as mentioned, you could use white-space: pre (see EnderMB) keeping in mind that pre will not collapse white space whereas white-space: nowrap will.

how to create dynamic two dimensional array in java?

Since the number of columns is a constant, you can just have an List of int[].

    import java.util.*;
    //...

    List<int[]> rowList = new ArrayList<int[]>();

    rowList.add(new int[] { 1, 2, 3 });
    rowList.add(new int[] { 4, 5, 6 });
    rowList.add(new int[] { 7, 8 });

    for (int[] row : rowList) {
        System.out.println("Row = " + Arrays.toString(row));
    } // prints:
      // Row = [1, 2, 3]
      // Row = [4, 5, 6]
      // Row = [7, 8]

    System.out.println(rowList.get(1)[1]); // prints "5"

Since it's backed by a List, the number of rows can grow and shrink dynamically. Each row is backed by an int[], which is static, but you said that the number of columns is fixed, so this is not a problem.

ASP.net vs PHP (What to choose)

This is impossible to answer and has been brought up many many times before. Do a search, read those threads, then pick the framework you and your team have experience with.

How can I convert a Timestamp into either Date or DateTime object?

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTest {

    public static void main(String[] args) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        Date date = new Date(timestamp.getTime());

        // S is the millisecond
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss:S");

        System.out.println(simpleDateFormat.format(timestamp));
        System.out.println(simpleDateFormat.format(date));
    }
}

Convert NSData to String?

Objective-C

You can use (see NSString Class Reference)

- (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding

Example:

NSString *myString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];

Remark: Please notice the NSData value must be valid for the encoding specified (UTF-8 in the example above), otherwise nil will be returned:

Returns nil if the initialization fails for some reason (for example if data does not represent valid data for encoding).

Prior Swift 3.0

String(data: yourData, encoding: NSUTF8StringEncoding)

Swift 3.0 Onwards

String(data: yourData, encoding: .utf8)

See String#init(data:encoding:) Reference

How do I put a clear button inside my HTML text input box like the iPhone does?

Firefox doesn't seem to support the clear search field functionality... I found this pure CSS solution that works nicely: Textbox with a clear button completely in CSS | Codepen | 2013. The magic happens at

.search-box:not(:valid) ~ .close-icon {
    display: none;
}

_x000D_
_x000D_
body {
    background-color: #f1f1f1;
    font-family: Helvetica,Arial,Verdana;

}
h2 {
    color: green;
    text-align: center;
}
.redfamily {
    color: red; 
}
.search-box,.close-icon,.search-wrapper {
    position: relative;
    padding: 10px;
}
.search-wrapper {
    width: 500px;
    margin: auto;
}
.search-box {
    width: 80%;
    border: 1px solid #ccc;
  outline: 0;
  border-radius: 15px;
}
.search-box:focus {
    box-shadow: 0 0 15px 5px #b0e0ee;
    border: 2px solid #bebede;
}
.close-icon {
    border:1px solid transparent;
    background-color: transparent;
    display: inline-block;
    vertical-align: middle;
  outline: 0;
  cursor: pointer;
}
.close-icon:after {
    content: "X";
    display: block;
    width: 15px;
    height: 15px;
    position: absolute;
    background-color: #FA9595;
    z-index:1;
    right: 35px;
    top: 0;
    bottom: 0;
    margin: auto;
    padding: 2px;
    border-radius: 50%;
    text-align: center;
    color: white;
    font-weight: normal;
    font-size: 12px;
    box-shadow: 0 0 2px #E50F0F;
    cursor: pointer;
}
.search-box:not(:valid) ~ .close-icon {
    display: none;
}
_x000D_
<h2>
    Textbox with a clear button completely in CSS <br> <span class="redfamily">< 0 lines of JavaScript ></span>
</h2>
<div class="search-wrapper">
    <form>
    <input type="text" name="focus" required class="search-box" placeholder="Enter search term" />
        <button class="close-icon" type="reset"></button>
    </form>
</div>
_x000D_
_x000D_
_x000D_

I needed more functionality and added this jQuery in my code:

$('.close-icon').click(function(){ /* my code */ });

Resolving LNK4098: defaultlib 'MSVCRT' conflicts with

Right-click the project, select Properties then under 'Configuration properties | Linker | Input | Ignore specific Library and write msvcrtd.lib

How do I split a string on a delimiter in Bash?

I've seen a couple of answers referencing the cut command, but they've all been deleted. It's a little odd that nobody has elaborated on that, because I think it's one of the more useful commands for doing this type of thing, especially for parsing delimited log files.

In the case of splitting this specific example into a bash script array, tr is probably more efficient, but cut can be used, and is more effective if you want to pull specific fields from the middle.

Example:

$ echo "[email protected];[email protected]" | cut -d ";" -f 1
[email protected]
$ echo "[email protected];[email protected]" | cut -d ";" -f 2
[email protected]

You can obviously put that into a loop, and iterate the -f parameter to pull each field independently.

This gets more useful when you have a delimited log file with rows like this:

2015-04-27|12345|some action|an attribute|meta data

cut is very handy to be able to cat this file and select a particular field for further processing.

"X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE"

If you support IE, for versions of Internet Explorer 8 and above, this:

<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7" />

Forces the browser to render as that particular version's standards. It is not supported for IE7 and below.

If you separate with semi-colon, it sets compatibility levels for different versions. For example:

<meta http-equiv="X-UA-Compatible" content="IE=7; IE=9" />

Renders IE7 and IE8 as IE7, but IE9 as IE9. It allows for different levels of backwards compatibility. In real life, though, you should only chose one of the options:

<meta http-equiv="X-UA-Compatible" content="IE=8" />

This allows for much easier testing and maintenance. Although generally the more useful version of this is using Emulate:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />

For this:

<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

It forces the browser the render at whatever the most recent version's standards are.

For more information, there is plenty to read about on MSDN,

nodemon not found in npm

Instructions for Windows,

Open Command Prompt.
type npm i -g nodemon --save
"--save" is to save the addition of this node package in your project's package.json file

MS Access - execute a saved query by name in VBA

To use CurrentDb.Execute, your query must be an action query, AND in quotes.

CurrentDb.Execute "queryname"

How can I refresh a page with jQuery?

If you are using jQuery and want to refresh, then try adding your jQuery in a javascript function:

I wanted to hide an iframe from a page when clicking oh an h3, for me it worked but I wasn't able to click the item that allowed me to view the iframe to begin with unless I refreshed the browser manually...not ideal.

I tried the following:

var hide = () => {
    $("#frame").hide();//jQuery
    location.reload(true);//javascript
};

Mixing plain Jane javascript with your jQuery should work.

// code where hide (where location.reload was used)function was integrated, below    
    iFrameInsert = () => {
        var file = `Fe1FVoW0Nt4`;
        $("#frame").html(`<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/${file}\" frameborder=\"0\" allow=\"autoplay; encrypted-media\" allowfullscreen></iframe><h3>Close Player</h3>`);
        $("h3").enter code hereclick(hide);
}

// View Player 
$("#id-to-be-clicked").click(iFrameInsert);

Rails - passing parameters in link_to

Try this

link_to "+ Service", my_services_new_path(:account_id => acct.id)

it will pass the account_id as you want.

For more details on link_to use this http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

How to prevent custom views from losing state across screen orientation changes

Based on @Fletcher Johns answer I came up with:

  • custom layout
  • can inflate from XML
  • is able to save/restore direct and indirect children. I improved @Fletcher Johns' answer to save the ids in String->Id map instead of IntArray.
  • the only small drawback is that you must declare your saveable child views beforehand.

open class AddressView @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0,
        defStyleRes: Int = 0
) : LinearLayout(context, attrs, defStyleAttr, defStyleRes) {

    protected lateinit var countryInputLayout: TextInputLayout
    protected lateinit var countryAutoCompleteTextView: CountryAutoCompleteTextView
    protected lateinit var cityInputLayout: TextInputLayout
    protected lateinit var cityEditText: CityEditText
    protected lateinit var postCodeInputLayout: TextInputLayout
    protected lateinit var postCodeEditText: PostCodeEditText
    protected lateinit var streetInputLayout: TextInputLayout
    protected lateinit var streetEditText: StreetEditText
    
    init {
        initView()
    }

    private fun initView() {
        val view = inflate(context, R.layout.view_address, this)

        orientation = VERTICAL

        countryInputLayout = view.findViewById(R.id.countryInputLayout)
        countryAutoCompleteTextView = view.findViewById(R.id.countryAutoCompleteTextView)

        streetInputLayout = view.findViewById(R.id.streetInputLayout)
        streetEditText = view.findViewById(R.id.streetEditText)

        cityInputLayout = view.findViewById(R.id.cityInputLayout)
        cityEditText = view.findViewById(R.id.cityEditText)

        postCodeInputLayout = view.findViewById(R.id.postCodeInputLayout)
        postCodeEditText = view.findViewById(R.id.postCodeEditText)
    }

    // Declare your direct and indirect child views that need to be saved
    private val childrenToSave get() = mapOf<String, View>(
            "coutryIL" to countryInputLayout,
            "countryACTV" to countryAutoCompleteTextView,
            "streetIL" to streetInputLayout,
            "streetET" to streetEditText,
            "cityIL" to cityInputLayout,
            "cityET" to cityEditText,
            "postCodeIL" to postCodeInputLayout,
            "postCodeET" to postCodeEditText,
    )
    private var viewIds: HashMap<String, Int>? = null

    override fun onSaveInstanceState(): Parcelable? {
        // Create a bundle to put super parcelable in
        val bundle = Bundle()
        bundle.putParcelable(SUPER_INSTANCE_STATE, super.onSaveInstanceState())
        // Store viewIds in the bundle - initialize if necessary.
        if (viewIds == null) {
            childrenToSave.values.forEach { view -> view.id = generateViewId() }
            viewIds = HashMap<String, Int>(childrenToSave.mapValues { (key, view) -> view.id })
        }

        bundle.putSerializable(STATE_VIEW_IDS, viewIds)

        return bundle
    }

    override fun onRestoreInstanceState(state: Parcelable?) {
        // We know state is a Bundle:
        val bundle = state as Bundle
        // Get mViewIds out of the bundle
        viewIds = bundle.getSerializable(STATE_VIEW_IDS) as HashMap<String, Int>
        // For each id, assign to the view of same index
        if (viewIds != null) {
            viewIds!!.forEach { (key, id) -> childrenToSave[key]!!.id = id }
        }
        super.onRestoreInstanceState(bundle.getParcelable(SUPER_INSTANCE_STATE))
    }

    companion object {
        private const val SUPER_INSTANCE_STATE = "saved_instance_state_parcelable"
        private const val STATE_VIEW_IDS = "state_view_ids"
    }
}

Programmatically create a UIView with color gradient

You can create a custom class GradientView:

Swift 5

class GradientView: UIView {
    override open class var layerClass: AnyClass {
       return CAGradientLayer.classForCoder()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        let gradientLayer = layer as! CAGradientLayer
        gradientLayer.colors = [UIColor.white.cgColor, UIColor.black.cgColor]
    }
}

In the storyboard, set the class type to any view that you want to have gradient background:

enter image description here

This is better in the following ways:

  • No need to set frame of CLayer
  • Use NSConstraint as usual on the UIView
  • Don't need to create sublayers (less memory use)

C# Clear Session

Found this article on net, very relevant to this topic. So posting here.

ASP.NET Internals - Clearing ASP.NET Session variables

show/hide a div on hover and hover out

You could use jQuery to show the div, and set it at wherever your mouse is:

html:

<!DOCTYPE html>
<html>

  <head>
    <link href="style.css" rel="stylesheet" />
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  </head>

  <body>
    <div id="trigger">
      <h1>Hover me!</h1>
      <p>Ill show you wonderful things</p>
    </div>
    <div id="secret">
     shhhh
    </div>
    <script src="script.js"></script>
  </body>

</html>

styles:

#trigger {
  border: 1px solid black;
}
#secret {
  display:none;
  top:0;  
  position:absolute;
  background: grey;
  color:white;
  width: 50%;
}

js:

$("#trigger").hover(function(e){
    $("#secret").show().css('top', e.pageY + "px").css('left', e.pageX + "px");
  },function(e){
    $("#secret").hide()
})

You can find the example here Cheers! http://plnkr.co/edit/LAhs8X9F8N3ft7qFvjzy?p=preview

Install tkinter for Python

Actually, you just need to use the following to install the tkinter for python3:

sudo apt-get install python3-tk

In addition, for Fedora users, use the following command:

sudo dnf install python3-tkinter

How to put the legend out of the plot

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

fontP = FontProperties()
fontP.set_size('xx-small')

p1, = plt.plot([1, 2, 3], label='Line 1')
p2, = plt.plot([3, 2, 1], label='Line 2')
plt.legend(handles=[p1, p2], title='title', bbox_to_anchor=(1.05, 1), loc='upper left', prop=fontP)

enter image description here

  • As noted by Mateen Ulhaq, fontsize='xx-small' also works, without importing FontProperties.
plt.legend(handles=[p1, p2], title='title', bbox_to_anchor=(1.05, 1), loc='upper left', fontsize='xx-small')

How to grep for two words existing on the same line?

The main issue is that you haven't supplied the first grep with any input. You will need to reorder your command something like

grep "word1" logs | grep "word2"

If you want to count the occurences, then put a '-c' on the second grep.

How to access private data members outside the class without making "friend"s?

http://bloglitb.blogspot.com/2010/07/access-to-private-members-thats-easy.html

this guy's blog shows you how to do it using templates. With some modifications, you can adapt this method to access a private data member, although I found it tricky despite having 10+ years experience.

I wanted to point out like everyone else, that there is an extremely few number of cases where doing this is legitimate. However, I want to point out one: I was writing unit tests for a software suite. A federal regulatory agency requires every single line of code to be exercised and tested, without modifying the original code. Due to (IMHO) poor design, a static constant was in the 'private' section, but I needed to use it in the unit test. So the method seemed to me like the best way to do it.

I'm sure the way could be simplified, and I'm sure there are other ways. I'm not posting this for the OP, since it's been 5 months, but hopefully this will be useful to some future googler.

How to create Gmail filter searching for text only at start of subject line?

I was wondering how to do this myself; it seems Gmail has since silently implemented this feature. I created the following filter:

Matches: subject:([test])
Do this: Skip Inbox

And then I sent a message with the subject

[test] foo

And the message was archived! So it seems all that is necessary is to create a filter for the subject prefix you wish to handle.

Send and Receive a file in socket programming in Linux with C/C++ (GCC/G++)

The most portable solution is just to read the file in chunks, and then write the data out to the socket, in a loop (and likewise, the other way around when receiving the file). You allocate a buffer, read into that buffer, and write from that buffer into your socket (you could also use send and recv, which are socket-specific ways of writing and reading data). The outline would look something like this:

while (1) {
    // Read data into buffer.  We may not have enough to fill up buffer, so we
    // store how many bytes were actually read in bytes_read.
    int bytes_read = read(input_file, buffer, sizeof(buffer));
    if (bytes_read == 0) // We're done reading from the file
        break;

    if (bytes_read < 0) {
        // handle errors
    }

    // You need a loop for the write, because not all of the data may be written
    // in one call; write will return how many bytes were written. p keeps
    // track of where in the buffer we are, while we decrement bytes_read
    // to keep track of how many bytes are left to write.
    void *p = buffer;
    while (bytes_read > 0) {
        int bytes_written = write(output_socket, p, bytes_read);
        if (bytes_written <= 0) {
            // handle errors
        }
        bytes_read -= bytes_written;
        p += bytes_written;
    }
}

Make sure to read the documentation for read and write carefully, especially when handling errors. Some of the error codes mean that you should just try again, for instance just looping again with a continue statement, while others mean something is broken and you need to stop.

For sending the file to a socket, there is a system call, sendfile that does just what you want. It tells the kernel to send a file from one file descriptor to another, and then the kernel can take care of the rest. There is a caveat that the source file descriptor must support mmap (as in, be an actual file, not a socket), and the destination must be a socket (so you can't use it to copy files, or send data directly from one socket to another); it is designed to support the usage you describe, of sending a file to a socket. It doesn't help with receiving the file, however; you would need to do the loop yourself for that. I cannot tell you why there is a sendfile call but no analogous recvfile.

Beware that sendfile is Linux specific; it is not portable to other systems. Other systems frequently have their own version of sendfile, but the exact interface may vary (FreeBSD, Mac OS X, Solaris).

In Linux 2.6.17, the splice system call was introduced, and as of 2.6.23 is used internally to implement sendfile. splice is a more general purpose API than sendfile. For a good description of splice and tee, see the rather good explanation from Linus himself. He points out how using splice is basically just like the loop above, using read and write, except that the buffer is in the kernel, so the data doesn't have to transferred between the kernel and user space, or may not even ever pass through the CPU (known as "zero-copy I/O").

Graphical HTTP client for windows

You can use Microsoft's WFetch tool also. This is a good tool for all HTTP operations.

Convert JSONObject to Map

You can use Gson() (com.google.gson) library if you find any difficulty using Jackson.

HashMap<String, Object> yourHashMap = new Gson().fromJson(yourJsonObject.toString(), HashMap.class);

stale element reference: element is not attached to the page document

This errors have two common causes: The element has been deleted entirely, or the element is no longer attached to the DOM.

If you already checked if it is not your case, you could be facing the same problem as me.

The element in the DOM is not found because your page is not entirely loaded when Selenium is searching for the element. To solve that, you can put an explicit wait condition that tells Selenium to wait until the element is available to be clicked on.

from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID, 'someid')))

See: https://selenium-python.readthedocs.io/waits.html

Auto-increment primary key in SQL tables

for those who are having the issue of it still not letting you save once it is changed according to answer below, do the following:

tools -> options -> designers -> Table and Database Designers -> uncheck "prevent saving changes that require table re-creation" box -> OK

and try to save as it should work now

Convert a secure string to plain text

In PS 7, you can use ConvertFrom-SecureString and -AsPlainText:

 $UnsecurePassword = ConvertFrom-SecureString -SecureString $SecurePassword -AsPlainText

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.security/ConvertFrom-SecureString?view=powershell-7#parameters

ConvertFrom-SecureString
           [-SecureString] <SecureString>
           [-AsPlainText]
           [<CommonParameters>]

How do I drop table variables in SQL-Server? Should I even do this?

Table variables are automatically local and automatically dropped -- you don't have to worry about it.

Setting Curl's Timeout in PHP

Your code sets the timeout to 1000 seconds. For milliseconds, use CURLOPT_TIMEOUT_MS.

How to check if a std::thread is still running?

Surely have a mutex-wrapped variable initialised to false, that the thread sets to true as the last thing it does before exiting. Is that atomic enough for your needs?

Print an integer in binary format in Java

I think it's the simplest algorithm so far (for those who don't want to use built-in functions):

public static String convertNumber(int a)  { 
              StringBuilder sb=new StringBuilder();
              sb.append(a & 1);
              while ((a>>=1) != 0)  { 
                  sb.append(a & 1);
               }
              sb.append("b0");
              return sb.reverse().toString();
  }

Example:

convertNumber(1) --> "0b1"

convertNumber(5) --> "0b101"

convertNumber(117) --> "0b1110101"

How it works: while-loop moves a-number to the right (replacing the last bit with second-to-last, etc), gets the last bit's value and puts it in StringBuilder, repeats until there are no bits left (that's when a=0).

How can I change the date format in Java?

Use SimpleDateFormat

    String DATE_FORMAT = "yyyy/MM/dd";
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
    System.out.println("Formated Date " + sdf.format(date));

Complete Example:

import java.text.SimpleDateFormat;
import java.util.Date;

public class JavaSimpleDateFormatExample {
    public static void main(String args[]) {
        // Create Date object.
        Date date = new Date();
        // Specify the desired date format
        String DATE_FORMAT = "yyyy/MM/dd";
        // Create object of SimpleDateFormat and pass the desired date format.
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        /*
         * Use format method of SimpleDateFormat class to format the date.
         */
        System.out.println("Today is " + sdf.format(date));
    }
}

How to determine programmatically the current active profile using Spring boot

It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment to your bean.

@Autowired
private Environment environment;
....

this.environment.getActiveProfiles();

Why are my PHP files showing as plain text?

You need to configure Apache (the webserver) to process PHP scripts as PHP. Check Apache's configuration. You need to load the module (the path may differ on your system):

LoadModule php5_module "c:/php/php5apache.dll"

And you also need to tell Apache what to process with PHP:

AddType application/x-httpd-php .php

See the documentation for more details.

VBA Macro to compare all cells of two Excel files

A very simple check you can do with Cell formulas:

Sheet 1 (new - old)

=(if(AND(Ref_New<>"";Ref_Old="");Ref_New;"")

Sheet 2 (old - new)

=(if(AND(Ref_Old<>"";Ref_New="");Ref_Old;"")

This formulas should work for an ENGLISH Excel. For other languages they need to be translated. (For German i can assist)

You need to open all three Excel Documents, then copy the first formula into A1 of your sheet 1 and the second into A1 of sheet 2. Now click in A1 of the first cell and mark "Ref_New", now you can select your reference, go to the new file and click in the A1, go back to sheet1 and do the same for "Ref_Old" with the old file. Replace also the other "Ref_New".

Doe the same for Sheet two.

Now copy the formaula form A1 over the complete range where zour data is in the old and the new file.

But two cases are not covered here:

  1. In the compared cell of New and Old is the same data (Resulting Cell will be empty)
  2. In the compared cell of New and Old is diffe data (Resulting Cell will be empty)

To cover this two cases also, you should create your own function, means learn VBA. A very useful Excel page is cpearson.com

How to convert a SVG to a PNG with ImageMagick?

why don't you give a try to inkscape command line, this is my bat file to convert all svg in this dir to png:

FOR %%x IN (*.svg) DO C:\Ink\App\Inkscape\inkscape.exe %%x -z --export-dpi=500 --export-area-drawing --export-png="%%~nx.png"

How to get a file or blob from an object URL?

As gengkev alludes to in his comment above, it looks like the best/only way to do this is with an async xhr2 call:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'blob:http%3A//your.blob.url.here', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
  if (this.status == 200) {
    var myBlob = this.response;
    // myBlob is now the blob that the object URL pointed to.
  }
};
xhr.send();

Update (2018): For situations where ES5 can safely be used, Joe has a simpler ES5-based answer below.

Display an image into windows forms

Here (http://www.dotnetperls.com/picturebox) there 3 ways to do this:

  • Like you are doing.
  • Using ImageLocation property of the PictureBox like:

    private void Form1_Load(object sender, EventArgs e)
    {
        PictureBox pb1 = new PictureBox();            
        pb1.ImageLocation = "../SamuderaJayaMotor.png";
        pb1.SizeMode = PictureBoxSizeMode.AutoSize;
    }
    
  • Using an image from the web like:

    private void Form1_Load(object sender, EventArgs e)
    {
        PictureBox pb1 = new PictureBox();            
        pb1.ImageLocation = "http://www.dotnetperls.com/favicon.ico";
        pb1.SizeMode = PictureBoxSizeMode.AutoSize;
    }
    

And please, be sure that "../SamuderaJayaMotor.png" is the correct path of the image that you are using.

.NET obfuscation tools/strategy

the free way would be to use dotfuscator from within visual studio, otherwise youd have to go out and buy an obfuscator like Postbuild (http://www.xenocode.com/Landing/Obfuscation.aspx)

getResourceAsStream() vs FileInputStream

The FileInputStream class works directly with the underlying file system. If the file in question is not physically present there, it will fail to open it. The getResourceAsStream() method works differently. It tries to locate and load the resource using the ClassLoader of the class it is called on. This enables it to find, for example, resources embedded into jar files.

How to get HttpClient returning status code and response body?

If you are using Spring

return new ResponseEntity<String>("your response", HttpStatus.ACCEPTED);

Where is HttpContent.ReadAsAsync?

It looks like it is an extension method (in System.Net.Http.Formatting):

HttpContentExtensions Class

Update:

PM> install-package Microsoft.AspNet.WebApi.Client

According to the System.Net.Http.Formatting NuGet package page, the System.Net.Http.Formatting package is now legacy and can instead be found in the Microsoft.AspNet.WebApi.Client package available on NuGet here.

Configure nginx with multiple locations with different root folders on subdomain

server {

    index index.html index.htm;
    server_name test.example.com;

    location / {
        root /web/test.example.com/www;
    }

    location /static {
        root /web/test.example.com;
    }
}

http://nginx.org/r/root

What is the use of "object sender" and "EventArgs e" parameters?

EventArgs e is a parameter called e that contains the event data, see the EventArgs MSDN page for more information.

Object Sender is a parameter called Sender that contains a reference to the control/object that raised the event.

Event Arg Class: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx

Example:

protected void btn_Click (object sender, EventArgs e){
   Button btn = sender as Button;
   btn.Text = "clicked!";
}

Edit: When Button is clicked, the btn_Click event handler will be fired. The "object sender" portion will be a reference to the button which was clicked

How to force composer to reinstall a library?

I didn't want to delete all the packages in vendor/ directory, so here is how I did it:

  1. rm -rf vendor/package-i-messed-up
  2. composer install again

What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)

forward

Control can be forward to resources available within the server from where the call is made. This transfer of control is done by the container internally and browser / client is not involved. This is the major difference between forward and sendRedirect. When the forward is done, the original request and response objects are transfered along with additional parameters if needed.

redirect

Control can be redirect to resources to different servers or domains. This transfer of control task is delegated to the browser by the container. That is, the redirect sends a header back to the browser / client. This header contains the resource url to be redirected by the browser. Then the browser initiates a new request to the given url. Since it is a new request, the old request and response object is lost.

For example, sendRedirect can transfer control from http://google.com to http://anydomain.com but forward cannot do this.

‘session’ is not lost in both forward and redirect.

To feel the difference between forward and sendRedirect visually see the address bar of your browser, in forward, you will not see the forwarded address (since the browser is not involved) in redirect, you can see the redirected address.

How can I remove the first line of a text file using bash/sed script?

Could use vim to do this:

vim -u NONE +'1d' +'wq!' /tmp/test.txt

This should be faster, since vim won't read whole file when process.

What are WSDL, SOAP and REST?

SOAP stands for Simple (sic) Object Access Protocol. It was intended to be a way to do Remote Procedure Calls to remote objects by sending XML over HTTP.

WSDL is Web Service Description Language. A request ending in '.wsdl' to an endpoint will result in an XML message describing request and response that a use can expect. It descibes the contract between service & client.

REST uses HTTP to send messages to services.

SOAP is a spec, REST is a style.

Excel how to find values in 1 column exist in the range of values in another

This is what you need:

 =NOT(ISERROR(MATCH(<cell in col A>,<column B>, 0)))  ## pseudo code

For the first cell of A, this would be:

 =NOT(ISERROR(MATCH(A2,$B$2:$B$5, 0)))

Enter formula (and drag down) as follows:

enter image description here

You will get:

enter image description here

Test method is inconclusive: Test wasn't run. Error?

Hope it'll help other, my fix was to update packages, there was a consolidation, and making all work with same packs fixed this issue for me. GL!

How to get a thread and heap dump of a Java process on Windows that's not running in a console

You are confusing two different java dumps. kill -3 generates a thread dump, not a heap dump.

Thread dump = stack traces for each thread in the JVM output to stdout as text.

Heap dump = memory contents for the JVM process output to a binary file.

To take a thread dump on Windows, CTRL+BREAK if your JVM is the foreground process is the simplest way. If you have a unix-like shell on Windows like Cygwin or MobaXterm, you can use kill -3 {pid} like you can in Unix.

To take a thread dump in Unix, CTRL+C if your JVM is the foreground process or kill -3 {pid} will work as long as you get the right PID for the JVM.

With either platform, Java comes with several utilities that can help. For thread dumps, jstack {pid} is your best bet. http://docs.oracle.com/javase/1.5.0/docs/tooldocs/share/jstack.html

Just to finish the dump question out: Heap dumps are not commonly used because they are difficult to interpret. But, they have a lot of useful information in them if you know where/how to look at them. The most common usage is to locate memory leaks. It is a good practice to set the -D on the java command-line so that the heap dump is generated automatically upon an OutOfMemoryError, -XX:+HeapDumpOnOutOfMemoryError But, you can manually trigger a heap dump, also. The most common way is to use the java utility jmap.

NOTE: this utility is not available on all platforms. As of JDK 1.6, jmap is available on Windows.

An example command-line would look something like

jmap -dump:file=myheap.bin {pid of the JVM}

The output "myheap.bin" is not human readable (for most of us), and you will need a tool to analyze it. My preference is MAT. http://www.eclipse.org/mat/

The HTTP request is unauthorized with client authentication scheme 'Ntlm'

For me the solution was besides using "Ntlm" as credential type, similar as Jeroen K's solution. If I had the permission level I would plus on his post, but let me post my whole code here, which will support both Windows and other credential types like basic auth:

    XxxSoapClient xxxClient = new XxxSoapClient();
    ApplyCredentials(userName, password, xxxClient.ClientCredentials);

    private static void ApplyCredentials(string userName, string password, ClientCredentials clientCredentials)
    {
        clientCredentials.UserName.UserName = userName;
        clientCredentials.UserName.Password = password;
        clientCredentials.Windows.ClientCredential.UserName = userName;
        clientCredentials.Windows.ClientCredential.Password = password;
        clientCredentials.Windows.AllowNtlm = true;
        clientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
    }  

What would be the Unicode character for big bullet in the middle of the character?

You can use a span with 50% border radius.

_x000D_
_x000D_
 .mydot{_x000D_
     background: rgb(66, 183, 42);_x000D_
     border-radius: 50%;_x000D_
     display: inline-block;_x000D_
     height: 20px;_x000D_
     margin-left: 4px;_x000D_
     margin-right: 4px;_x000D_
     width: 20px;_x000D_
}    
_x000D_
<span class="mydot"></span>
_x000D_
_x000D_
_x000D_

Return Boolean Value on SQL Select Statement

Use 'Exists' which returns either 0 or 1.

The query will be like:

SELECT EXISTS(SELECT * FROM USER WHERE UserID = 20070022)

Using Chrome, how to find to which events are bound to an element

Edit: in lieu of my own answer, this one is quite excellent: How to debug JavaScript/jQuery event bindings with Firebug (or similar tool)

Google Chromes developer tools has a search function built into the scripts section

If you are unfamiliar with this tool: (just in case)

  • right click anywhere on a page (in chrome)
  • click 'Inspect Element'
  • click the 'Scripts' tab
  • Search bar in the top right

Doing a quick search for the #ID should take you to the binding function eventually.

Ex: searching for #foo would take you to

$('#foo').click(function(){ alert('bar'); })

enter image description here

Dead simple example of using Multiprocessing Queue, Pool and Locking

The best solution for your problem is to utilize a Pool. Using Queues and having a separate "queue feeding" functionality is probably overkill.

Here's a slightly rearranged version of your program, this time with only 2 processes coralled in a Pool. I believe it's the easiest way to go, with minimal changes to original code:

import multiprocessing
import time

data = (
    ['a', '2'], ['b', '4'], ['c', '6'], ['d', '8'],
    ['e', '1'], ['f', '3'], ['g', '5'], ['h', '7']
)

def mp_worker((inputs, the_time)):
    print " Processs %s\tWaiting %s seconds" % (inputs, the_time)
    time.sleep(int(the_time))
    print " Process %s\tDONE" % inputs

def mp_handler():
    p = multiprocessing.Pool(2)
    p.map(mp_worker, data)

if __name__ == '__main__':
    mp_handler()

Note that mp_worker() function now accepts a single argument (a tuple of the two previous arguments) because the map() function chunks up your input data into sublists, each sublist given as a single argument to your worker function.

Output:

Processs a  Waiting 2 seconds
Processs b  Waiting 4 seconds
Process a   DONE
Processs c  Waiting 6 seconds
Process b   DONE
Processs d  Waiting 8 seconds
Process c   DONE
Processs e  Waiting 1 seconds
Process e   DONE
Processs f  Waiting 3 seconds
Process d   DONE
Processs g  Waiting 5 seconds
Process f   DONE
Processs h  Waiting 7 seconds
Process g   DONE
Process h   DONE

Edit as per @Thales comment below:

If you want "a lock for each pool limit" so that your processes run in tandem pairs, ala:

A waiting B waiting | A done , B done | C waiting , D waiting | C done, D done | ...

then change the handler function to launch pools (of 2 processes) for each pair of data:

def mp_handler():
    subdata = zip(data[0::2], data[1::2])
    for task1, task2 in subdata:
        p = multiprocessing.Pool(2)
        p.map(mp_worker, (task1, task2))

Now your output is:

 Processs a Waiting 2 seconds
 Processs b Waiting 4 seconds
 Process a  DONE
 Process b  DONE
 Processs c Waiting 6 seconds
 Processs d Waiting 8 seconds
 Process c  DONE
 Process d  DONE
 Processs e Waiting 1 seconds
 Processs f Waiting 3 seconds
 Process e  DONE
 Process f  DONE
 Processs g Waiting 5 seconds
 Processs h Waiting 7 seconds
 Process g  DONE
 Process h  DONE

foreach with index

I just figured out interesting solution:

public class DepthAware<T> : IEnumerable<T>
{
    private readonly IEnumerable<T> source;

    public DepthAware(IEnumerable<T> source)
    {
        this.source = source;
        this.Depth = 0;
    }

    public int Depth { get; private set; }

    private IEnumerable<T> GetItems()
    {
        foreach (var item in source)
        {
            yield return item;
            ++this.Depth;
        }
    }

    public IEnumerator<T> GetEnumerator()
    {
        return GetItems().GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

// Generic type leverage and extension invoking
public static class DepthAware
{
    public static DepthAware<T> AsDepthAware<T>(this IEnumerable<T> source)
    {
        return new DepthAware<T>(source);
    }

    public static DepthAware<T> New<T>(IEnumerable<T> source)
    {
        return new DepthAware<T>(source);
    }
}

Usage:

var chars = new[] {'a', 'b', 'c', 'd', 'e', 'f', 'g'}.AsDepthAware();

foreach (var item in chars)
{
    Console.WriteLine("Char: {0}, depth: {1}", item, chars.Depth);
}

How to square all the values in a vector in R?

This is another simple way:

sq_data <- data**2

A keyboard shortcut to comment/uncomment the select text in Android Studio

Windows 10 and Android Studio: Ctrl + / (on small num pad), don't use Ctrl + Shift-7!

Unable to open a file with fopen()

A little error checking goes a long way -- you can always test the value of errno or call perror() or strerror() to get more information about why the fopen() call failed.

Otherwise the suggestions about checking the path are probably correct... most likely you're not in the directory you think you are from the IDE and don't have the permissions you expect.

How to get a jqGrid selected row cells value

Just Checkout This :

Solution 1 :

In Subgrid Function You have to write following :

var selectid = $(this).jqGrid('getCell', row_id, 'id');
alert(selectid);

Where row_id is the variable which you define in subgrid as parameter. And id is the column name which you want to get value of the cell.

Solution 2 :

If You Get Jqgrid Row Id In alert Then set your primary key id as key:true In ColModels. So You will get value of your database id in alert. Like this :

{name:"id",index:"id",hidden:true, width:15,key:true, jsonmap:"id"},

How do I get textual contents from BLOB in Oracle SQL

Use TO_CHAR function.

select TO_CHAR(BLOB_FIELD) from TABLE_WITH_BLOB where ID = '<row id>'

Converts NCHAR, NVARCHAR2, CLOB, or NCLOB data to the database character set. The value returned is always VARCHAR2.

How to increase MaximumErrorCount in SQL Server 2008 Jobs or Packages?

If I have open a package in BIDS ("Business Intelligence Development Studio", the tool you use to design the packages), and do not select any item in it, I have a "Properties" pane in the bottom right containing - among others, the MaximumErrorCount property. If you do not see it, maybe it is minimized and you have to open it (have a look at tabs in the right).

If you cannot find it this way, try the menu: View/Properties Window.

Or try the F4 key.

SQL Server stored procedure Nullable parameter

It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.

Other than that, I would suggest two things...

First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...

    ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0

Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.

Creating composite primary key in SQL Server

How about this:

ALTER TABLE dbo.testRequest
ADD CONSTRAINT PK_TestRequest 
PRIMARY KEY (wardNo, BHTNo, TestID) 

Overlapping elements in CSS

the easiest way is to use position:absolute on both elements. You can absolutely position relative to the page, or you can absolutely position relative to a container div by setting the container div to position:relative

<div id="container" style="position:relative;">
    <div id="div1" style="position:absolute; top:0; left:0;"></div>
    <div id="div2" style="position:absolute; top:0; left:0;"></div>
</div>

How to access nested elements of json object using getJSONArray method

I suggest you to use Gson library. It allows to parse JSON string into object data model. Please, see my example:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;

public class GsonProgram {

    public static void main(String... args) {
        String response = "{\"result\":{\"map\":{\"entry\":[{\"key\":{\"@xsi.type\":\"xs:string\",\"$\":\"ContentA\"},\"value\":\"fsdf\"},{\"key\":{\"@xsi.type\":\"xs:string\",\"$\":\"ContentB\"},\"value\":\"dfdf\"}]}}}";

        Gson gson = new GsonBuilder().serializeNulls().create();
        Response res = gson.fromJson(response, Response.class);

        System.out.println("Entries: " + res.getResult().getMap().getEntry());
    }
}

class Response {

    private Result result;

    public Result getResult() {
        return result;
    }

    public void setResult(Result result) {
        this.result = result;
    }

    @Override
    public String toString() {
        return result.toString();
    }
}

class Result {

    private MapNode map;

    public MapNode getMap() {
        return map;
    }

    public void setMap(MapNode map) {
        this.map = map;
    }

    @Override
    public String toString() {
        return map.toString();
    }
}

class MapNode {

    List<Entry> entry = new ArrayList<Entry>();

    public List<Entry> getEntry() {
        return entry;
    }

    public void setEntry(List<Entry> entry) {
        this.entry = entry;
    }

    @Override
    public String toString() {
        return Arrays.toString(entry.toArray());
    }
}

class Entry {

    private Key key;
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public Key getKey() {
        return key;
    }

    public void setKey(Key key) {
        this.key = key;
    }

    @Override
    public String toString() {
        return "[key=" + key + ", value=" + value + "]";
    }
}

class Key {

    @SerializedName("$")
    private String value;

    @SerializedName("@xsi.type")
    private String type;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return "[value=" + value + ", type=" + type + "]";
    }
}

Program output:

Entries: [[key=[value=ContentA, type=xs:string], value=fsdf], [key=[value=ContentB, type=xs:string], value=dfdf]]

If you not familiar with this library, then you can find a lot of informations in "Gson User Guide".

Response.Redirect to new window

The fixform trick is neat, but:

  1. You may not have access to the code of what loads in the new window.

  2. Even if you do, you are depending on the fact that it always loads, error free.

  3. And you are depending on the fact that the user won't click another button before the other page gets a chance to load and run fixform.

I would suggest doing this instead:

OnClientClick="aspnetForm.target ='_blank';setTimeout('fixform()', 500);"

And set up fixform on the same page, looking like this:

function fixform() {
   document.getElementById("aspnetForm").target = '';
}

SQL update query using joins

Try like this...

Update t1.Column1 = value 
from tbltemp as t1 
inner join tblUser as t2 on t2.ID = t1.UserID 
where t1.[column1]=value and t2.[Column1] = value;

How can I convert a date into an integer?

Using the builtin Date.parse function which accepts input in ISO8601 format and directly returns the desired integer return value:

var dates_as_int = dates.map(Date.parse);