Programs & Examples On #Runtime.exec

The Runtime.exec() method allows Java apps. to create a new OS Process.

Running Command Line in Java

Have you tried the exec command within the Runtime class?

Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug")

Runtime - Java Documentation

How do I run a batch file from my Java Application?

Runtime runtime = Runtime.getRuntime();
try {
    Process p1 = runtime.exec("cmd /c start D:\\temp\\a.bat");
    InputStream is = p1.getInputStream();
    int i = 0;
    while( (i = is.read() ) != -1) {
        System.out.print((char)i);
    }
} catch(IOException ioException) {
    System.out.println(ioException.getMessage() );
}

How to run Linux commands in Java?

The suggested solutions could be optimized using commons.io, handling the error stream, and using Exceptions. I would suggest to wrap like this for use in Java 8 or later:

public static List<String> execute(final String command) throws ExecutionFailedException, InterruptedException, IOException {
    try {
        return execute(command, 0, null, false);
    } catch (ExecutionTimeoutException e) { return null; } /* Impossible case! */
}

public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException {
    return execute(command, 0, null, true);
}

public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit, boolean destroyOnTimeout) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException {
    Process process = new ProcessBuilder().command("bash", "-c", command).start();
    if(timeUnit != null) {
        if(process.waitFor(timeout, timeUnit)) {
            if(process.exitValue() == 0) {
                return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
            } else {
                throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8));
            }
        } else {
            if(destroyOnTimeout) process.destroy();
            throw new ExecutionTimeoutException("Execution timed out: " + command);
        }
    } else {
        if(process.waitFor() == 0) {
            return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
        } else {
            throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8));
        }
    }
}

public static class ExecutionFailedException extends Exception {

    private static final long serialVersionUID = 1951044996696304510L;

    private final int exitCode;
    private final List<String> errorOutput;

    public ExecutionFailedException(final String message, final int exitCode, final List<String> errorOutput) {
        super(message);
        this.exitCode = exitCode;
        this.errorOutput = errorOutput;
    }

    public int getExitCode() {
        return this.exitCode;
    }

    public List<String> getErrorOutput() {
        return this.errorOutput;
    }

}

public static class ExecutionTimeoutException extends Exception {

    private static final long serialVersionUID = 4428595769718054862L;

    public ExecutionTimeoutException(final String message) {
        super(message);
    }

}

process.waitFor() never returns

As others have mentioned you have to consume stderr and stdout.

Compared to the other answers, since Java 1.7 it is even more easy. You do not have to create threads yourself anymore to read stderr and stdout.

Just use the ProcessBuilder and use the methods redirectOutput in combination with either redirectError or redirectErrorStream.

String directory = "/working/dir";
File out = new File(...); // File to write stdout to
File err = new File(...); // File to write stderr to
ProcessBuilder builder = new ProcessBuilder();
builder.directory(new File(directory));
builder.command(command);
builder.redirectOutput(out); // Redirect stdout to file
if(out == err) { 
  builder.redirectErrorStream(true); // Combine stderr into stdout
} else { 
  builder.redirectError(err); // Redirect stderr to file
}
Process process = builder.start();

Difference between ProcessBuilder and Runtime.exec()

The various overloads of Runtime.getRuntime().exec(...) take either an array of strings or a single string. The single-string overloads of exec() will tokenise the string into an array of arguments, before passing the string array onto one of the exec() overloads that takes a string array. The ProcessBuilder constructors, on the other hand, only take a varargs array of strings or a List of strings, where each string in the array or list is assumed to be an individual argument. Either way, the arguments obtained are then joined up into a string that is passed to the OS to execute.

So, for example, on Windows,

Runtime.getRuntime().exec("C:\DoStuff.exe -arg1 -arg2");

will run a DoStuff.exe program with the two given arguments. In this case, the command-line gets tokenised and put back together. However,

ProcessBuilder b = new ProcessBuilder("C:\DoStuff.exe -arg1 -arg2");

will fail, unless there happens to be a program whose name is DoStuff.exe -arg1 -arg2 in C:\. This is because there's no tokenisation: the command to run is assumed to have already been tokenised. Instead, you should use

ProcessBuilder b = new ProcessBuilder("C:\DoStuff.exe", "-arg1", "-arg2");

or alternatively

List<String> params = java.util.Arrays.asList("C:\DoStuff.exe", "-arg1", "-arg2");
ProcessBuilder b = new ProcessBuilder(params);

How to solve "java.io.IOException: error=12, Cannot allocate memory" calling Runtime#exec()?

As weird as this may sound, one work around is to reduce the amount of memory allocated to the JVM. Since fork() duplicates the process and its memory, if your JVM process does not really need as much memory as is allocated via -Xmx, the memory allocation to git will work.

Of course you can try other solutions mentioned here (like over-committing or upgrading to a JVM that has the fix). You can try reducing the memory if you are desperate for a solution that keeps all software intact with no environment impact. Also keep in mind that reducing -Xmx aggressively can cause OOMs. I'd recommend upgrading the JDK as a long-term stable solution.

Execute external program

This is not right. Here's how you should use Runtime.exec(). You might also try its more modern cousin, ProcessBuilder:

Java Runtime.getRuntime().exec() alternatives

How to get first and last day of the current week in JavaScript

var dt = new Date()  //current date of week
var currentWeekDay = dt.getDay();
var lessDays = currentWeekDay == 0 ? 6 : currentWeekDay-1
var wkStart = new Date(new Date(dt).setDate(dt.getDate()- lessDays));
var wkEnd = new Date(new Date(wkStart).setDate(wkStart.getDate()+6));

This will be useful for any date scenario.

'dict' object has no attribute 'has_key'

has_key was removed in Python 3. From the documentation:

  • Removed dict.has_key() – use the in operator instead.

Here's an example:

if start not in graph:
    return None

Convert char array to a int number in C

So, the idea is to convert character numbers (in single quotes, e.g. '8') to integer expression. For instance char c = '8'; int i = c - '0' //would yield integer 8; And sum up all the converted numbers by the principle that 908=9*100+0*10+8, which is done in a loop.

char t[5] = {'-', '9', '0', '8', '\0'}; //Should be terminated properly.

int s = 1;
int i = -1;
int res = 0;

if (c[0] == '-') {
  s = -1;
  i = 0;
}

while (c[++i] != '\0') { //iterate until the array end
  res = res*10 + (c[i] - '0'); //generating the integer according to read parsed numbers.
}

res = res*s; //answer: -908

LINQ to SQL Left Outer Join

You don't need the into statements:

var query = 
    from customer in dc.Customers
    from order in dc.Orders
         .Where(o => customer.CustomerId == o.CustomerId)
         .DefaultIfEmpty()
    select new { Customer = customer, Order = order } 
    //Order will be null if the left join is null

And yes, the query above does indeed create a LEFT OUTER join.

Link to a similar question that handles multiple left joins: Linq to Sql: Multiple left outer joins

Using the last-child selector

Another way to do it is using the last-child selector in jQuery and then use the .css() method. Be weary though because some people are still in the stone age using JavaScript disabled browsers.

`React/RCTBridgeModule.h` file not found

For viewers who got this error after upgrading React Native to 0.40+, you may need to run react-native upgrade on the command line.

Difference between opening a file in binary vs text

The link you gave does actually describe the differences, but it's buried at the bottom of the page:

http://www.cplusplus.com/reference/cstdio/fopen/

Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.

The conversion could be to normalize \r\n to \n (or vice-versa), or maybe ignoring characters beyond 0x7F (a-la 'text mode' in FTP). Personally I'd open everything in binary-mode and use a good text-encoding library for dealing with text.

width:auto for <input> fields

Because input's width is controlled by it's size attribute, this is how I initialize an input width according to its content:

<input type="text" class="form-list-item-name" [size]="myInput.value.length" #myInput>

How to draw rounded rectangle in Android UI?

Use CardView for Round Rectangle. CardView give more functionality like cardCornerRadius, cardBackgroundColor, cardElevation & many more. CardView make UI more suitable then Custom Round Rectangle drawable.

ActiveRecord find and only return selected columns

pluck(column_name)

This method is designed to perform select by a single column as direct SQL query Returns Array with values of the specified column name The values has same data type as column.

Examples:

Person.pluck(:id) # SELECT people.id FROM people
Person.uniq.pluck(:role) # SELECT DISTINCT role FROM people
Person.where(:confirmed => true).limit(5).pluck(:id)

see http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck

Its introduced rails 3.2 onwards and accepts only single column. In rails 4, it accepts multiple columns

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

How to find length of digits in an integer?

Here is a bulky but fast version :

def nbdigit ( x ):
    if x >= 10000000000000000 : # 17 -
        return len( str( x ))
    if x < 100000000 : # 1 - 8
        if x < 10000 : # 1 - 4
            if x < 100             : return (x >= 10)+1 
            else                   : return (x >= 1000)+3
        else: # 5 - 8                                                 
            if x < 1000000         : return (x >= 100000)+5 
            else                   : return (x >= 10000000)+7
    else: # 9 - 16 
        if x < 1000000000000 : # 9 - 12
            if x < 10000000000     : return (x >= 1000000000)+9 
            else                   : return (x >= 100000000000)+11
        else: # 13 - 16
            if x < 100000000000000 : return (x >= 10000000000000)+13 
            else                   : return (x >= 1000000000000000)+15

Only 5 comparisons for not too big numbers. On my computer it is about 30% faster than the math.log10 version and 5% faster than the len( str()) one. Ok... no so attractive if you don't use it furiously.

And here is the set of numbers I used to test/measure my function:

n = [ int( (i+1)**( 17/7. )) for i in xrange( 1000000 )] + [0,10**16-1,10**16,10**16+1]

NB: it does not manage negative numbers, but the adaptation is easy...

Count number of 1's in binary representation

In python or any other convert to bin string then split it with '0' to get rid of 0's then combine and get the length.

len(''.join(str(bin(122011)).split('0')))-1

How do you merge two Git repositories?

Similar to @Smar but uses file system paths, set in PRIMARY and SECONDARY:

PRIMARY=~/Code/project1
SECONDARY=~/Code/project2
cd $PRIMARY
git remote add test $SECONDARY && git fetch test
git merge test/master

Then you manually merge.

(adapted from post by Anar Manafov)

Update row values where certain condition is met in pandas

I think you can use loc if you need update two columns to same value:

df1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2        aaaa         aaaa
c       2        aaaa         aaaa
d       3  some_value   some_value

If you need update separate, one option is use:

df1.loc[df1['stream'] == 2, 'feat'] = 10
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2          10   some_value
c       2          10   some_value
d       3  some_value   some_value

Another common option is use numpy.where:

df1['feat'] = np.where(df1['stream'] == 2, 10,20)
print df1
   stream  feat another_feat
a       1    20   some_value
b       2    10   some_value
c       2    10   some_value
d       3    20   some_value

EDIT: If you need divide all columns without stream where condition is True, use:

print df1
   stream  feat  another_feat
a       1     4             5
b       2     4             5
c       2     2             9
d       3     1             7

#filter columns all without stream
cols = [col for col in df1.columns if col != 'stream']
print cols
['feat', 'another_feat']

df1.loc[df1['stream'] == 2, cols ] = df1 / 2
print df1
   stream  feat  another_feat
a       1   4.0           5.0
b       2   2.0           2.5
c       2   1.0           4.5
d       3   1.0           7.0

If working with multiple conditions is possible use multiple numpy.where or numpy.select:

df0 = pd.DataFrame({'Col':[5,0,-6]})

df0['New Col1'] = np.where((df0['Col'] > 0), 'Increasing', 
                          np.where((df0['Col'] < 0), 'Decreasing', 'No Change'))

df0['New Col2'] = np.select([df0['Col'] > 0, df0['Col'] < 0],
                            ['Increasing',  'Decreasing'], 
                            default='No Change')

print (df0)
   Col    New Col1    New Col2
0    5  Increasing  Increasing
1    0   No Change   No Change
2   -6  Decreasing  Decreasing

How to remove leading zeros from alphanumeric text?

Using Regexp with groups:

Pattern pattern = Pattern.compile("(0*)(.*)");
String result = "";
Matcher matcher = pattern.matcher(content);
if (matcher.matches())
{
      // first group contains 0, second group the remaining characters
      // 000abcd - > 000, abcd
      result = matcher.group(2);
}

return result;

Find a row in dataGridView based on column and value

If you just want to check if that item exists:

IEnumerable<DataGridViewRow> rows = grdPdfs.Rows
            .Cast<DataGridViewRow>()
            .Where(r => r.Cells["SystemId"].Value.ToString().Equals(searchValue));
if (rows.Count() == 0) 
{
    // Not Found
} 
else 
{
    // Found
}

Return HTML from ASP.NET Web API

Starting with AspNetCore 2.0, it's recommended to use ContentResult instead of the Produce attribute in this case. See: https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885

This doesn't rely on serialization nor on content negotiation.

[HttpGet]
public ContentResult Index() {
    return new ContentResult {
        ContentType = "text/html",
        StatusCode = (int)HttpStatusCode.OK,
        Content = "<html><body>Hello World</body></html>"
    };
}

Find if a String is present in an array

This can be done in java 8 using Stream.

import java.util.stream.Stream;

String[] stringList = {"Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue"};

boolean contains = Stream.of(stringList).anyMatch(x -> x.equals(say.getText());

How to check if a file is a valid image file?

A lot of times the first couple chars will be a magic number for various file formats. You could check for this in addition to your exception checking above.

Giving UIView rounded corners

if round corner not working in viewDidload() it's better to write code in viewDidLayoutSubview()

-(void)viewDidLayoutSubviews
{
    viewTextfield.layer.cornerRadius = 10.0 ;                                               
    viewTextfield.layer.borderWidth = 1.0f;
    viewTextfield.layer.masksToBounds =  YES;
    viewTextfield.layer.shadowRadius = 5;
    viewTextfield.layer.shadowOpacity = 0.3;
    viewTextfield.clipsToBounds = NO;
    viewTextfield.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
}

Hope this helps!

How to Iterate over a Set/HashSet without an Iterator?

Enumeration(?):

Enumeration e = new Vector(set).elements();
while (e.hasMoreElements())
    {
        System.out.println(e.nextElement());
    }

Another way (java.util.Collections.enumeration()):

for (Enumeration e1 = Collections.enumeration(set); e1.hasMoreElements();)
    {
        System.out.println(e1.nextElement());
    }

Java 8:

set.forEach(element -> System.out.println(element));

or

set.stream().forEach((elem) -> {
    System.out.println(elem);
});

How to override Bootstrap's Panel heading background color?

am assuming custom_class to be your class to override heading color of the panel. just add !important to it or add inline styles or a id and add styles as they will have more specificity over class added styles.

  • with !important

    .custom_class{ background-color: red !important; }

  • with !important

  • with ID :

    #custom_id{ background-color: red; }

-with inline styles :

<div id="custom_id" class="panel panel-default">
      <div class="panel-heading custom_class" style="background-color:red">
      </div>
    </div>

Uncaught TypeError: Cannot read property 'value' of null

Easier and more succinct with || ...:

$(document).ready(function(){


  var str = ((document.getElementById("cal_preview")||{}).value)||"";
  var str1 = ((document.getElementById("year")||{}).value)||"";
  var str2 = ((document.getElementById("holiday")||{}).value)||"";
  var str3 = ((document.getElementById("cal_option")||{}).value)||"";


    if (str=="" && str1=="" && str2=="" && str3=="" )
      {
        document.getElementById("calendar_preview").innerHTML="";
          return;
        } 
      if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
      }
      else
      {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }

      xmlhttp.onreadystatechange=function()
      {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
          {
            document.getElementById("calendar_preview").innerHTML=xmlhttp.responseText;
          }
      }

    var url = calendar_preview_vars.plugin_url + "?id=" + str +"&"+"y="+str1+"&"+"h="+str2+"&"+"opt="+str3;
    xmlhttp.open("GET",url,true);
    xmlhttp.send(); 


});

Dealing with float precision in Javascript

Check out this link.. It helped me a lot.

http://www.w3schools.com/jsref/jsref_toprecision.asp

The toPrecision(no_of_digits_required) function returns a string so don't forget to use the parseFloat() function to convert to decimal point of required precision.

How to use Greek symbols in ggplot2?

You do not need the latex2exp package to do what you wanted to do. The following code would do the trick.

ggplot(smr, aes(Fuel.Rate, Eng.Speed.Ave., color=Eng.Speed.Max.)) + 
  geom_point() + 
  labs(title=expression("Fuel Efficiency"~(alpha*Omega)), 
color=expression(alpha*Omega), x=expression(Delta~price))

enter image description here

Also, some comments (unanswered as of this point) asked about putting an asterisk (*) after a Greek letter. expression(alpha~"*") works, so I suggest giving it a try.

More comments asked about getting ? Price and I find the most straightforward way to achieve that is expression(Delta~price)). If you need to add something before the Greek letter, you can also do this: expression(Indicative~Delta~price) which gets you:

enter image description here

JOptionPane Yes or No window

Something along these lines ....

   //default icon, custom title
int n = JOptionPane.showConfirmDialog(null,"Would you like green eggs and ham?","An Inane Question",JOptionPane.YES_NO_OPTION);

String result = "?";
switch (n) {
case JOptionPane.YES_OPTION:
  result = "YES";
  break;
case JOptionPane.NO_OPTION:
  result = "NO";
  break;
default:
  ;
}
System.out.println("Replace? " + result);

you may also want to look at DialogDemo

When must we use NVARCHAR/NCHAR instead of VARCHAR/CHAR in SQL Server?

Greek would need UTF-8 on N column types: aß? ;)

Arrays with different datatypes i.e. strings and integers. (Objectorientend)

Why not create a class Book with properties: Number, Title, and Price. Then store them in a single dimensional array? That way instead of calling

Book[i][j] 

..to get your books title, call

Book[i].Title

Seems to me like it would be a bit more manageable and code friendly.

Check if a Windows service exists and delete in PowerShell

Combining Dmitri & dcx's answers I made this:

function Confirm-WindowsServiceExists($name)
{   
    if (Get-Service $name -ErrorAction SilentlyContinue)
    {
        return $true
    }
    return $false
}

function Remove-WindowsServiceIfItExists($name)
{   
    $exists = Confirm-WindowsServiceExists $name
    if ($exists)
    {    
        sc.exe \\server delete $name
    }       
}

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

Got to this answer ? probably the answers above are to long ...

just type in :

echo "setenv M2_HOME $M2_HOME" | sudo tee -a /etc/launchd.conf

and restart your mac (thats it!)

restarting is annoying ? just use the command :

grep -E "^setenv" /etc/launchd.conf | xargs -t -L 1 launchctl

and restart IntelliJ IDEA

Failed to resolve: com.android.support:appcompat-v7:26.0.0

My issue got resolved with the help of following steps:

For gradle 3.0.0 and above version

  1. add google() below jcenter()
  2. Change the compileSdkVersion to 26 and buildToolsVersion to 26.0.2
  3. Change to gradle-4.2.1-all.zip in the gradle_wrapper.properties file

How to connect with Java into Active Directory

You can use DDC (Domain Directory Controller). It is a new, easy to use, Java SDK. You don't even need to know LDAP to use it. It exposes an object-oriented API instead.

You can find it here.

SQLite string contains other string query

Using LIKE:

SELECT *
  FROM TABLE
 WHERE column LIKE '%cats%'  --case-insensitive

How to set HTML5 required attribute in Javascript?

And the jquery version:

$('input').attr('required', true)
$('input').attr('required', false)

I know it's beyond the question, but maybe someone will find this helpful :)

How can I convert ArrayList<Object> to ArrayList<String>?

Since this is actually not a list of strings, the easiest way is to loop over it and convert each item into a new list of strings yourself:

List<String> strings = list.stream()
   .map(object -> Objects.toString(object, null))
   .collect(Collectors.toList());

Or when you're not on Java 8 yet:

List<String> strings = new ArrayList<>(list.size());
for (Object object : list) {
    strings.add(Objects.toString(object, null));
}

Or when you're not on Java 7 yet:

List<String> strings = new ArrayList<String>(list.size());
for (Object object : list) {
    strings.add(object != null ? object.toString() : null);
}

Note that you should be declaring against the interface (java.util.List in this case), not the implementation.

Prevent form redirect OR refresh on submit?

Just handle the form submission on the submit event, and return false:

$('#contactForm').submit(function () {
 sendContactForm();
 return false;
});

You don't need any more the onclick event on the submit button:

<input class="submit" type="submit" value="Send" />

How to export DataTable to Excel

An elegant option is writing an extension method (see below) for the DataTable class of .net framework.

This extention method can be called as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data;
using System.Data.OleDb;

DataTable dt;
// fill table data in dt here 
...

// export DataTable to excel
// save excel file without ever making it visible if filepath is given
// don't save excel file, just make it visible if no filepath is given
dt.ExportToExcel(ExcelFilePath);

Extension method for DataTable class:

public static class My_DataTable_Extensions
{

    // Export DataTable into an excel file with field names in the header line
    // - Save excel file without ever making it visible if filepath is given
    // - Don't save excel file, just make it visible if no filepath is given
    public static void ExportToExcel(this DataTable tbl, string excelFilePath = null) {
        try {
            if (tbl == null || tbl.Columns.Count == 0)
                throw new Exception("ExportToExcel: Null or empty input table!\n");

            // load excel, and create a new workbook
            var excelApp = new Excel.Application();
            excelApp.Workbooks.Add();

            // single worksheet
            Excel._Worksheet workSheet = excelApp.ActiveSheet;

            // column headings
            for (var i = 0; i < tbl.Columns.Count; i++) {
                workSheet.Cells[1, i + 1] = tbl.Columns[i].ColumnName;
            }

            // rows
            for (var i = 0; i < tbl.Rows.Count; i++) {
                // to do: format datetime values before printing
                for (var j = 0; j < tbl.Columns.Count; j++) {
                    workSheet.Cells[i + 2, j + 1] = tbl.Rows[i][j];
                }
            }

            // check file path
            if (!string.IsNullOrEmpty(excelFilePath)) {
                try {
                    workSheet.SaveAs(excelFilePath);
                    excelApp.Quit();
                    MessageBox.Show("Excel file saved!");
                }
                catch (Exception ex) {
                    throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
                                        + ex.Message);
                }
            } else { // no file path is given
                excelApp.Visible = true;
            }
        }
        catch (Exception ex) {
            throw new Exception("ExportToExcel: \n" + ex.Message);
        }
    }
}

Delete topic in Kafka 0.8.1.1

The command:

bin/kafka-topics.sh --delete --zookeeper localhost:2181 --topic test

unfortunately only marks topic for deletion.

Deletion does not happen.

That makes troubles, while testing any scripts, which prepares Kafka configuration.

Connected threads:

Having Django serve downloadable files

I did a project on this. You can look at my github repo:

https://github.com/nishant-boro/django-rest-framework-download-expert

This module provides a simple way to serve files for download in django rest framework using Apache module Xsendfile. It also has an additional feature of serving downloads only to users belonging to a particular group

Warning comparison between pointer and integer

This: "\0" is a string, not a character. A character uses single quotes, like '\0'.

Is it wrong to place the <script> tag after the </body> tag?

As Andy said the document will be not valid, but nevertheless the script will still be interpreted. See the snippet from WebKit for example:

void HTMLParser::processCloseTag(Token* t)
{
    // Support for really broken html.
    // we never close the body tag, since some stupid web pages close it before 
    // the actual end of the doc.
    // let's rely on the end() call to close things.
    if (t->tagName == htmlTag || t->tagName == bodyTag 
                              || t->tagName == commentAtom)
        return;
    ...

T-SQL query to show table definition?

SELECT ORDINAL_POSITION, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
       , IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'EMPLOYEES'

How to download videos from youtube on java?

ytd2 is a fully functional YouTube video downloader. Check out its source code if you want to see how it's done.

Alternatively, you can also call an external process like youtube-dl to do the job. This is probably the easiest solution but it isn't in "pure" Java.

How to specify a multi-line shell variable?

I would like to give one additional answer, while the other ones will suffice in most cases.

I wanted to write a string over multiple lines, but its contents needed to be single-line.

sql="                       \
SELECT c1, c2               \
from Table1, ${TABLE2}      \
where ...                   \
"

I am sorry if this if a bit off-topic (I did not need this for SQL). However, this post comes up among the first results when searching for multi-line shell variables and an additional answer seemed appropriate.

Using VBA code, how to export Excel worksheets as image in Excel 2003?

Thanks everyone! I modified Winand's code slightly to export it to the user's desktop, no matter who is using the worksheet. I gave credit in the code to where I got the idea (thanks Kyle).

Sub ExportImage()


Dim sFilePath As String
Dim sView As String

'Captures current window view
sView = ActiveWindow.View

'Sets the current view to normal so there are no "Page X" overlays on the image
ActiveWindow.View = xlNormalView

'Temporarily disable screen updating
Application.ScreenUpdating = False

Set Sheet = ActiveSheet

'Set the file path to export the image to the user's desktop
'I have to give credit to Kyle for this solution, found it here:
'http://stackoverflow.com/questions/17551238/vba-how-to-save-excel-workbook-to-desktop-regardless-of-user
sFilePath = CreateObject("WScript.Shell").specialfolders("Desktop") & "\" & ActiveSheet.Name & ".png"

'Export print area as correctly scaled PNG image, courtasy of Winand
zoom_coef = 100 / Sheet.Parent.Windows(1).Zoom
Set area = Sheet.Range(Sheet.PageSetup.PrintArea)
area.CopyPicture xlPrinter
Set chartobj = Sheet.ChartObjects.Add(0, 0, area.Width * zoom_coef, area.Height * zoom_coef)
chartobj.Chart.Paste
chartobj.Chart.Export sFilePath, "png"
chartobj.Delete

'Returns to the previous view
ActiveWindow.View = sView

'Re-enables screen updating
Application.ScreenUpdating = True

'Tells the user where the image was saved
MsgBox ("Export completed! The file can be found here:" & Chr(10) & Chr(10) & sFilePath)

End Sub

Maven fails to find local artifact

I had the same error from a different cause: I'd created a starter POM containing our "good practice" dependencies, and built & installed it locally to test it. I could "see" it in the repo, but a project that used it got the above error. What I'd done was set the starter POM to pom, so there was no JAR. Maven was quite correct that it wasn't in Nexus -- but I wasn't expecting it to be, so the error was, ummm, unhelpful. Changing the starter POM to normal packaging & reinstalling fixed the issue.

Storage permission error in Marshmallow

Check multiple Permission in API level 23 Step 1:

 String[] permissions = new String[]{
        Manifest.permission.INTERNET,
        Manifest.permission.READ_PHONE_STATE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.VIBRATE,
        Manifest.permission.RECORD_AUDIO,
};

Step 2:

 private boolean checkPermissions() {
    int result;
    List<String> listPermissionsNeeded = new ArrayList<>();
    for (String p : permissions) {
        result = ContextCompat.checkSelfPermission(this, p);
        if (result != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(p);
        }
    }
    if (!listPermissionsNeeded.isEmpty()) {
        ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), 100);
        return false;
    }
    return true;
}

Step 3:

 @Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    if (requestCode == 100) {
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // do something
        }
        return;
    }
}

Step 4: in onCreate of Activity checkPermissions();

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

The problem:

java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer

indicates that you try to use the Jersey 2.x servlet, but you are supplying the Jersey 1.x libs.

For Jersey 1.x you have to do it like this:

<servlet>
  <servlet-name>Jersey REST Service</servlet-name>
<servlet-class>
  com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class>
  <init-param>
    <param-name>com.sun.jersey.config.property.packages</param-name>
    <param-value>sample.hello.resources</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>Jersey REST Service</servlet-name>
  <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

For more information check the Jersey 1.x documentation.

If you instead want to use Jersey 2.x then you'll have to supply the Jersey 2.x libs. In a maven based project you can use the following:

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>2.xx</version>
</dependency>
<!-- if you are using Jersey client specific features without the server side -->
<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-client</artifactId>
    <version>2.xx</version>
</dependency>

For Jersey 2.x you don't need to setup anything in your web.xml, it is sufficient to supply a class similar to this:

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("rest")
public class ApplicationConfig extends Application {

}

For more information, check the Jersey documentation.

See also:

Returning multiple objects in an R function

Is something along these lines what you are looking for?

x1 = function(x){
  mu = mean(x)
  l1 = list(s1=table(x),std=sd(x))
  return(list(l1,mu))
}

library(Ecdat)
data(Fair)
x1(Fair$age)

Select a dummy column with a dummy value in SQL?

Try this:

select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;

Incorrect integer value: '' for column 'id' at row 1

This is because your data sending column type is integer and your are sending a string value to it.

So, the following way worked for me. Try with this one.

$insertQuery = "INSERT INTO workorders VALUES (
                    null,
                    '$priority',
                    '$requestType',
                    '$purchaseOrder',
                    '$nte',
                    '$jobSiteNumber'
                )";

Don't use 'null'. use it as null without single quotes.

How can I check if a jQuery plugin is loaded?

If we're talking about a proper jQuery plugin (one that extends the fn namespace), then the proper way to detect the plugin would be:

if(typeof $.fn.pluginname !== 'undefined') { ... }

Or because every plugin is pretty much guaranteed to have some value that equates to true, you can use the shorter

if ($.fn.pluginname) { ... }

BTW, the $ and jQuery are interchangable, as the odd-looking wrapper around a plugin demonstrates:

(function($) {
    //
})(jQuery))

the closure

(function($) {
    //
})

is followed immediately by a call to that closure 'passing' jQuery as the parameter

(jQuery)

the $ in the closure is set equal to jQuery

Read from file in eclipse

Did you try refreshing (right click -> refresh) the project folder after copying the file in there? That will SYNC your file system with Eclipse's internal file system.

When you run Eclipse projects, the CWD (current working directory) is project's root directory. Not bin's directory. Not src's directory, but the root dir.

Also, if you're in Linux, remember that its file systems are usually case sensitive.

Presenting modal in iOS 13 fullscreen

Quick solution. There are already really great answers above. I am also adding my quick 2 points input, which is presented in the screenshot.

  1. If you are not using Navigation Controller then from Right Menu Inspector set the Presentation to Full Screen

  2. If you are using Navigation Controller then by default it will present full screen, you have to do nothing.

enter image description here

How to extract text from an existing docx file using python-docx

Using python-docx, as @Chinmoy Panda 's answer shows:

for para in doc.paragraphs:
    fullText.append(para.text)

However, para.text will lost the text in w:smarttag (Corresponding github issue is here: https://github.com/python-openxml/python-docx/issues/328), you should use the following function instead:

def para2text(p):
    rs = p._element.xpath('.//w:t')
    return u" ".join([r.text for r in rs])

How to use stringstream to separate comma separated strings

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
    std::string input = "abc,def,   ghi";
    std::istringstream ss(input);
    std::string token;
    size_t pos=-1;
    while(ss>>token) {
      while ((pos=token.rfind(',')) != std::string::npos) {
        token.erase(pos, 1);
      }
      std::cout << token << '\n';
    }
}

Changing the size of a column referenced by a schema-bound view in SQL Server

If anyone wants to "Increase the column width of the replicated table" in SQL Server 2008, then no need to change the property of "replicate_ddl=1". Simply follow below steps --

  1. Open SSMS
  2. Connect to Publisher database
  3. run command -- ALTER TABLE [Table_Name] ALTER COLUMN [Column_Name] varchar(22)
  4. It will increase the column width from varchar(x) to varchar(22) and same change you can see on subscriber (transaction got replicated). So no need to re-initialize the replication

Hope this will help all who are looking for it.

How to parse JSON response from Alamofire API in Swift?

in swift 5 we do like, Use typealias for the completion. Typlealias nothing just use to clean the code.

typealias response = (Bool,Any?)->()


static func postCall(_ url : String, param : [String : Any],completion : @escaping response){
    Alamofire.request(url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: [:]).responseJSON { (response) in

        switch response.result {
           case .success(let JSON):
               print("\n\n Success value and JSON: \(JSON)")

           case .failure(let error):
               print("\n\n Request failed with error: \(error)")

           }
    }
}

How does one parse XML files?

If you're processing a large amount of data (many megabytes) then you want to be using XmlReader to stream parse the XML.

Anything else (XPathNavigator, XElement, XmlDocument and even XmlSerializer if you keep the full generated object graph) will result in high memory usage and also a very slow load time.

Of course, if you need all the data in memory anyway, then you may not have much choice.

Best equivalent VisualStudio IDE for Mac to program .NET/C#

Whilst more of a workaround, if you're running an Intel Mac, you could go the virtualisation route - at least then you can run the same tools.

How to link an input button to a file select window?

If you want to allow the user to browse for a file, you need to have an input type="file" The closest you could get to your requirement would be to place the input type="file" on the page and hide it. Then, trigger the click event of the input when the button is clicked:

#myFileInput {
    display:none;
}

<input type="file" id="myFileInput" />
<input type="button"
       onclick="document.getElementById('myFileInput').click()" 
       value="Select a File" />

Here's a working fiddle.

Note: I would not recommend this approach. The input type="file" is the mechanism that users are accustomed to using for uploading a file.

How to include NA in ifelse?

@AnandaMahto has addressed why you're getting these results and provided the clearest way to get what you want. But another option would be to use identical instead of ==.

test$ID <- ifelse(is.na(test$time) | sapply(as.character(test$type), identical, "A"), NA, "1")

Or use isTRUE:

test$ID <- ifelse(is.na(test$time) | Vectorize(isTRUE)(test$type == "A"), NA, "1")

How to enable C++17 compiling in Visual Studio?

If bringing existing Visual Studio 2015 solution into Visual Studio 2017 and you want to build it with c++17 native compiler, you should first Retarget the solution/projects to v141 , THEN the dropdown will appear as described above ( Configuration Properties -> C/C++ -> Language -> Language Standard)

How to set opacity to the background color of a div?

CSS 3 introduces rgba colour, and you can combine it with graphics for a backwards compatible solution.

Looping through a Scripting.Dictionary using index/item number

Using d.Keys()(i) method is a very bad idea, because on each call it will re-create a new array (you will have significant speed reduction).

Here is an analogue of Scripting.Dictionary called "Hash Table" class from @TheTrick, that support such enumerator: http://www.cyberforum.ru/blogs/354370/blog2905.html

Dim oDict As clsTrickHashTable

Sub aaa()
    Set oDict = New clsTrickHashTable

    oDict.Add "a", "aaa"
    oDict.Add "b", "bbb"

    For i = 0 To oDict.Count - 1
        Debug.Print oDict.Keys(i) & " - " & oDict.Items(i)
    Next
End Sub

Compare objects in Angular

Bit late on this thread. angular.equals does deep check, however does anyone know that why its behave differently if one of the member contain "$" in prefix ?

You can try this Demo with following input

var obj3 = {}
obj3.a=  "b";
obj3.b={};
obj3.b.$c =true;

var obj4 = {}
obj4.a=  "b";
obj4.b={};
obj4.b.$c =true;

angular.equals(obj3,obj4);

How to clear the logs properly for a Docker container?

Use:

truncate -s 0 /var/lib/docker/containers/*/*-json.log

You may need sudo

sudo sh -c "truncate -s 0 /var/lib/docker/containers/*/*-json.log"

ref. Jeff S. How to clear the logs properly for a Docker container?

Reference: Truncating a file while it's being used (Linux)

How to create separate AngularJS controller files?

Although both answers are technically correct, I want to introduce a different syntax choice for this answer. This imho makes it easier to read what's going on with injection, differentiate between etc.

File One

// Create the module that deals with controllers
angular.module('myApp.controllers', []);

File Two

// Here we get the module we created in file one
angular.module('myApp.controllers')

// We are adding a function called Ctrl1
// to the module we got in the line above
.controller('Ctrl1', Ctrl1);

// Inject my dependencies
Ctrl1.$inject = ['$scope', '$http'];

// Now create our controller function with all necessary logic
function Ctrl1($scope, $http) {
  // Logic here
}

File Three

// Here we get the module we created in file one
angular.module('myApp.controllers')

// We are adding a function called Ctrl2
// to the module we got in the line above
.controller('Ctrl2', Ctrl2);

// Inject my dependencies
Ctrl2.$inject = ['$scope', '$http'];

// Now create our controller function with all necessary logic
function Ctrl2($scope, $http) {
  // Logic here
}

What's the difference between primitive and reference types?

The short answer is primitives are data types, while references are pointers, which do not hold their values but point to their values and are used on/with objects.

Primatives:

boolean

character

byte

short

integer

long

float

double

Lots of good references that explain these basic concepts. http://www.javaforstudents.co.uk/Types

How to fix a collation conflict in a SQL Server query?

You can resolve the issue by forcing the collation used in a query to be a particular collation, e.g. SQL_Latin1_General_CP1_CI_AS or DATABASE_DEFAULT. For example:

SELECT MyColumn
FROM FirstTable a
INNER JOIN SecondTable b
ON a.MyID COLLATE SQL_Latin1_General_CP1_CI_AS = 
b.YourID COLLATE SQL_Latin1_General_CP1_CI_AS

In the above query, a.MyID and b.YourID would be columns with a text-based data type. Using COLLATE will force the query to ignore the default collation on the database and instead use the provided collation, in this case SQL_Latin1_General_CP1_CI_AS.

Basically what's going on here is that each database has its own collation which "provides sorting rules, case, and accent sensitivity properties for your data" (from http://technet.microsoft.com/en-us/library/ms143726.aspx) and applies to columns with textual data types, e.g. VARCHAR, CHAR, NVARCHAR, etc. When two databases have differing collations, you cannot compare text columns with an operator like equals (=) without addressing the conflict between the two disparate collations.

How to verify if $_GET exists?

You are use PHP isset

Example

if (isset($_GET["id"])) {
    echo $_GET["id"];
}

Keystore type: which one to use?

There are a few more types than what's listed in the standard name list you've linked to. You can find more in the cryptographic providers documentation. The most common are certainly JKS (the default) and PKCS12 (for PKCS#12 files, often with extension .p12 or sometimes .pfx).

JKS is the most common if you stay within the Java world. PKCS#12 isn't Java-specific, it's particularly convenient to use certificates (with private keys) backed up from a browser or coming from OpenSSL-based tools (keytool wasn't able to convert a keystore and import its private keys before Java 6, so you had to use other tools).

If you already have a PKCS#12 file, it's often easier to use the PKCS12 type directly. It's possible to convert formats, but it's rarely necessary if you can choose the keystore type directly.

In Java 7, PKCS12 was mainly useful as a keystore but less for a truststore (see the difference between a keystore and a truststore), because you couldn't store certificate entries without a private key. In contrast, JKS doesn't require each entry to be a private key entry, so you can have entries that contain only certificates, which is useful for trust stores, where you store the list of certificates you trust (but you don't have the private key for them).

This has changed in Java 8, so you can now have certificate-only entries in PKCS12 stores too. (More details about these changes and further plans can be found in JEP 229: Create PKCS12 Keystores by Default.)

There are a few other keystore types, perhaps less frequently used (depending on the context), those include:

  • PKCS11, for PKCS#11 libraries, typically for accessing hardware cryptographic tokens, but the Sun provider implementation also supports NSS stores (from Mozilla) through this.
  • BKS, using the BouncyCastle provider (commonly used for Android).
  • Windows-MY/Windows-ROOT, if you want to access the Windows certificate store directly.
  • KeychainStore, if you want to use the OSX keychain directly.

Passing multiple variables to another page in url

from php.net

Warning The superglobals $_GET and $_REQUEST are already decoded. Using urldecode() on an element in $_GET or $_REQUEST could have unexpected and dangerous results.

link: http://php.net/manual/en/function.urldecode.php

be careful.

Bootstrap row class contains margin-left and margin-right which creates problems

Here is your simple and easy answer

Go to your class where you want to give a negative margin then copy and paste this inside the class.

Example for negative margin top

mt-n3

Example for negative margin bottom

mb-n2

Javascript parse float is ignoring the decimals after my comma

As @JaredPar pointed out in his answer use parseFloat with replace

var fullcost = parseFloat($("#fullcost").text().replace(',', '.'));

Just replacing the comma with a dot will fix, Unless it's a number over the thousands like 1.000.000,00 this way will give you the wrong digit. So you need to replace the comma remove the dots.

// Remove all dot's. Replace the comma.
var fullcost = parseFloat($("#fullcost").text().replace(/\./g,'').replace(',', '.'));

By using two replaces you'll be able to deal with the data without receiving wrong digits in the output.

Most efficient way to append arrays in C#?

I believe if you have 2 arrays of the same type that you want to combine into a third array, there's a very simple way to do that.

here's the code:

String[] theHTMLFiles = Directory.GetFiles(basePath, "*.html");
String[] thexmlFiles = Directory.GetFiles(basePath, "*.xml");
List<String> finalList = new List<String>(theHTMLFiles.Concat<string>(thexmlFiles));
String[] finalArray = finalList.ToArray();

How to use lodash to find and return an object from Array?

var delete_id = _(savedViews).where({ description : view }).get('0.id')

Why functional languages?

I don't think most realistic people think that functional programming will catch on (becomes the main paradigm like OO). After all, most business problems are not pretty math problems but hairy imperative rules to move data around and display them in various ways, which means it's not a good fit for pure functional programming paradigm (the learning curve of monad far exceeds OO.)

OTOH, functional programming is what makes programming fun. It makes you appreciate the inherent, timeless beauty of succinct expressions of the underlying math of the universe. People say that learning functional programming will make you a better programmer. This is of course highly subjective. I personally don't think that's completely true either.

It makes you a better sentient being.

Algorithm to calculate the number of divisors of a given number

The following is a C program to find the number of divisors of a given number.

The complexity of the above algorithm is O(sqrt(n)).

This algorithm will work correctly for the number which are perfect square as well as the numbers which are not perfect square.

Note that the upperlimit of the loop is set to the square-root of number to have the algorithm most efficient.

Note that storing the upperlimit in a separate variable also saves the time, you should not call the sqrt function in the condition section of the for loop, this also saves your computational time.

#include<stdio.h>
#include<math.h>
int main()
{
    int i,n,limit,numberOfDivisors=1;
    printf("Enter the number : ");
    scanf("%d",&n);
    limit=(int)sqrt((double)n);
    for(i=2;i<=limit;i++)
        if(n%i==0)
        {
            if(i!=n/i)
                numberOfDivisors+=2;
            else
                numberOfDivisors++;
        }
    printf("%d\n",numberOfDivisors);
    return 0;
}

Instead of the above for loop you can also use the following loop which is even more efficient as this removes the need to find the square-root of the number.

for(i=2;i*i<=n;i++)
{
    ...
}

Unresolved external symbol in object files

I had the same link errors, but from a test project which was referencing another dll. Found out that after adding _declspec(dllexport) in front of each function which was specified in the error message, the link was working well.

Jquery show/hide table rows

Change your black and white IDs to classes instead (duplicate IDs are invalid), add 2 buttons with the proper IDs, and do this:

var rows = $('table.someclass tr');

$('#showBlackButton').click(function() {
    var black = rows.filter('.black').show();
    rows.not( black ).hide();
});

$('#showWhiteButton').click(function() {
    var white = rows.filter('.white').show();
    rows.not( white ).hide();
});

$('#showAll').click(function() {
    rows.show();
});

<button id="showBlackButton">show black</button>
<button id="showWhiteButton">show white</button>
<button id="showAll">show all</button>

<table class="someclass" border="0" cellpadding="0" cellspacing="0" summary="bla bla bla">
    <caption>bla bla bla</caption>
    <thead>
          <tr class="black">
            ...
          </tr>
    </thead>
    <tbody>
        <tr class="white">
            ...
        </tr>
        <tr class="black">
           ...
        </tr>
    </tbody>
</table>

It uses the filter()[docs] method to filter the rows with the black or white class (depending on the button).

Then it uses the not()[docs] method to do the opposite filter, excluding the black or white rows that were previously found.


EDIT: You could also pass a selector to .not() instead of the previously found set. It may perform better that way:

rows.not( `.black` ).hide();

// ...

rows.not( `.white` ).hide();

...or better yet, just keep a cached set of both right from the start:

var rows = $('table.someclass tr');
var black = rows.filter('.black');
var white = rows.filter('.white');

$('#showBlackButton').click(function() {
    black.show();
    white.hide();
});

$('#showWhiteButton').click(function() {
    white.show();
    black.hide();
});

Converting Integer to String with comma for thousands

System.out.println(NumberFormat.getNumberInstance(Locale.US).format(35634646));
Output: 35,634,646

How can I search sub-folders using glob.glob module?

(The first options are of course mentioned in other answers, here the goal is to show that glob uses os.scandir internally, and provide a direct answer with this).


Using glob

As explained before, with Python 3.5+, it's easy:

import glob
for f in glob.glob('d:/temp/**/*', recursive=True):
    print(f)

#d:\temp\New folder
#d:\temp\New Text Document - Copy.txt
#d:\temp\New folder\New Text Document - Copy.txt
#d:\temp\New folder\New Text Document.txt

Using pathlib

from pathlib import Path
for f in Path('d:/temp').glob('**/*'):
    print(f)

Using os.scandir

os.scandir is what glob does internally. So here is how to do it directly, with a use of yield:

def listpath(path):
    for f in os.scandir(path):
        f2 = os.path.join(path, f)
        if os.path.isdir(f):
            yield f2
            yield from listpath(f2)
        else:
            yield f2

for f in listpath('d:\\temp'):
    print(f)

Installing Node.js (and npm) on Windows 10

The reason why you have to modify the AppData could be:

  1. Node.js couldn't handle path longer then 256 characters, windows tend to have very long PATH.
  2. If you are login from a corporate environment, your AppData might be on the server - that won't work. The npm directory must be in your local drive.

Even after doing that, the latest LTE (4.4.4) still have problem with Windows 10, it worked for a little while then whenever I try to:

$ npm install _some_package_ --global 

Node throw the "FATAL ERROR CALL_AND_RETRY_LAST Allocation failed - process out of memory" error. Still try to find a solution to that problem.

The only thing I find works is to run Vagrant or Virtual box, then run the Linux command line (must matching the path) which is quite a messy solution.

Find the item with maximum occurrences in a list

from collections import Counter
most_common,num_most_common = Counter(L).most_common(1)[0] # 4, 6 times

For older Python versions (< 2.7), you can use this recipe to create the Counter class.

Set up a scheduled job?

A more modern solution (compared to Celery) is Django Q: https://django-q.readthedocs.io/en/latest/index.html

It has great documentation and is easy to grok. Windows support is lacking, because Windows does not support process forking. But it works fine if you create your dev environment using the Windows for Linux Subsystem.

Converting unix time into date-time via excel

If you have ########, it can help you:

=((A1/1000+1*3600)/86400+25569)

+1*3600 is GTM+1

Check for special characters (/*-+_@&$#%) in a string?

While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:

  1. Add the [https://www.nuget.org/packages/Extensions.cs][1] package to your project.
  2. Add "using Extensions;" to the top of your code.
  3. "smith23@".IsAlphaNumeric() will return False whereas "smith23".IsAlphaNumeric() will return True. By default the .IsAlphaNumeric() method ignores spaces, but it can also be overridden such that "smith 23".IsAlphaNumeric(false) will return False since the space is not considered part of the alphabet.
  4. Every other check in the rest of the code is simply MyString.IsAlphaNumeric().

MongoDB/Mongoose querying at a specific date?

Have you tried:

db.posts.find({"created_on": {"$gte": new Date(2012, 7, 14), "$lt": new Date(2012, 7, 15)}})

The problem you're going to run into is that dates are stored as timestamps in Mongo. So, to match a date you're asking it to match a timestamp. In your case I think you're trying to match a day (ie. from 00:00 to 23:59 on a specific date). If your dates are stored without times then you should be okay. Otherwise, try specifying your date as a range of time on the same day (ie. start=00:00, end=23:59) if gte doesn't work.

similar question

SQL Server IIF vs CASE

IIF is a non-standard T-SQL function. It was added to SQL SERVER 2012, so that Access could migrate to SQL Server without refactoring the IIF's to CASE before hand. Once the Access db is fully migrated into SQL Server, you can refactor.

Set Matplotlib colorbar size to match graph

I appreciate all the answers above. However, like some answers and comments pointed out, the axes_grid1 module cannot address GeoAxes, whereas adjusting fraction, pad, shrink, and other similar parameters cannot necessarily give the very precise order, which really bothers me. I believe that giving the colorbar its own axes might be a better solution to address all the issues that have been mentioned.

Code

import matplotlib.pyplot as plt
import numpy as np

fig=plt.figure()
ax = plt.axes()
im = ax.imshow(np.arange(100).reshape((10,10)))

# Create an axes for colorbar. The position of the axes is calculated based on the position of ax.
# You can change 0.01 to adjust the distance between the main image and the colorbar.
# You can change 0.02 to adjust the width of the colorbar.
# This practice is universal for both subplots and GeoAxes.

cax = fig.add_axes([ax.get_position().x1+0.01,ax.get_position().y0,0.02,ax.get_position().height])
plt.colorbar(im, cax=cax) # Similar to fig.colorbar(im, cax = cax)

Result

enter image description here

Later on, I find matplotlib.pyplot.colorbar official documentation also gives ax option, which are existing axes that will provide room for the colorbar. Therefore, it is useful for multiple subplots, see following.

Code

fig, ax = plt.subplots(2,1,figsize=(12,8)) # Caution, figsize will also influence positions.
im1 = ax[0].imshow(np.arange(100).reshape((10,10)), vmin = -100, vmax =100)
im2 = ax[1].imshow(np.arange(-100,0).reshape((10,10)), vmin = -100, vmax =100)
fig.colorbar(im1, ax=ax)

Result

enter image description here

Again, you can also achieve similar effects by specifying cax, a more accurate way from my perspective.

Code

fig, ax = plt.subplots(2,1,figsize=(12,8))
im1 = ax[0].imshow(np.arange(100).reshape((10,10)), vmin = -100, vmax =100)
im2 = ax[1].imshow(np.arange(-100,0).reshape((10,10)), vmin = -100, vmax =100)
cax = fig.add_axes([ax[1].get_position().x1-0.25,ax[1].get_position().y0,0.02,ax[0].get_position().y1-ax[1].get_position().y0])
fig.colorbar(im1, cax=cax)

Result

enter image description here

Recursive Fibonacci

When x==2 you call fib(1) and fib(0):

return fib(2-1)+fib(2-2);

Consider what will happen when fib(0) is evaluated...

Why em instead of px?

It is wrong to say that one is a better choice than the other (or both wouldn't have been given their own purpose in the spec). It may even be worth noting that StackOverflow makes extensive use of px units. It is not the poor choice Spoike was told it was.

Definition of units

  • px is an absolute unit of measurement (like in, pt, or cm) that also happens to be 1/96 of an in unit (more on why later). Because it is an absolute measurement, it may be used any time you want to define something to be a particular size, rather than being proportional to something else like the size of the browser window or the font size.

    Like all the other absolute units, px units don't scale according to the width of the browser window. Thus, if your entire page design uses absolute units such as px rather than %, it won't adapt to the width of the browser. This is not inherently good or bad, just a choice that the designer needs to make between adhering to an exact size and being inflexible versus stretching but in the process not adhering to an exact size. It would be typical for a site to have a mix of fixed-size and flexible-sized objects.

    Fixed size elements often need to be incorporated into the page - such as advertising banners, logos or icons. This ensures you almost always need at least some px-based measurements in a design. Images, for example, will (by default) be scaled such that each pixel is 1*px* in size, so if you are designing around an image you'll need px units. It is also very useful for precise font sizing, and for border widths, where due to rounding it makes the most sense to use px units for the majority of screens.

    All absolute measurements are rigidly related to each other; that is, 1in is always 96px, just as 1in is always 72pt. (Note that 1in is almost never actually a physical inch when talking about screen-based media). All absolute measurements assume a nominal screen resolution of 96ppi and a nominal viewing distance of a desktop monitor, and on such a screen one px will be equal to one physical pixel on the screen and one in will be equal to 96 physical pixels. On screens that differ significantly in either pixel density or viewing distance, or if the user has zoomed the page using the browser's zoom function, px will no longer necessarily relate to physical pixels.

  • em is not an absolute unit - it is a unit that is relative to the currently chosen font size. Unless you have overridden font style by setting your font size with an absolute unit (such as px or pt), this will be affected by the choice of fonts in the user's browser or OS if they have made one, so it does not make sense to use em as a general unit of length except where you specifically want it to scale as the font size scales.

    Use em when you specifically want the size of something to depend on the current font size.

  • % is also a relative unit, in this case, relative to either the height or width of a parent element. They are a good alternative to px units for things like the total width of a design if your design does not rely on specific pixel sizes to set its size.

    Using % units in your design allows your design to adapt to the width of the screen/device, whereas using an absolute unit such as px does not.

How to read integer values from text file

You might want to do something like this (if you're using java 5 and more)

Scanner scanner = new Scanner(new File("tall.txt"));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt())
{
     tall[i++] = scanner.nextInt();
}

Via Julian Grenier from Reading Integers From A File In An Array

Targeting both 32bit and 64bit with Visual Studio in same solution/project

If you use Custom Actions written in .NET as part of your MSI installer then you have another problem.

The 'shim' that runs these custom actions is always 32bit then your custom action will run 32bit as well, despite what target you specify.

More info & some ninja moves to get around (basically change the MSI to use the 64 bit version of this shim)

Building an MSI in Visual Studio 2005/2008 to work on a SharePoint 64

64-bit Managed Custom Actions with Visual Studio

iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari?

Only tested on Android 4.1.1:

blur event is not a reliable event to test keyboard up and down because the user as the option to explicitly hide the keyboard which does not trigger a blur event on the field that caused the keyboard to show.

resize event however works like a charm if the keyboard comes up or down for any reason.

coffee:

$(window).bind "resize", (event) ->  alert "resize"

fires on anytime the keyboard is shown or hidden for any reason.

Note however on in the case of an android browser (rather than app) there is a retractable url bar which does not fire resize when it is retracted yet does change the available window size.

HTML-5 date field shows as "mm/dd/yyyy" in Chrome, even when valid date is set

I was having the same problem, with a value like 2016-08-8, then I solved adding a zero to have two digits days, and it works. Tested in chrome, firefox, and Edge

today:function(){
   var today = new Date();
   var d = (today.getDate() < 10 ? '0' : '' )+ today.getDate();
   var m = ((today.getMonth() + 1) < 10 ? '0' :'') + (today.getMonth() + 1);
   var y = today.getFullYear();
   var x = String(y+"-"+m+"-"+d); 
   return x;
}

Store boolean value in SQLite

But,if you want to store a bunch of them you could bit-shift them and store them all as one int, a little like unix file permissions/modes.

For mode 755 for instance, each digit refers to a different class of users: owner, group, public. Within each digit 4 is read, 2 is write, 1 is execute so 7 is all of them like binary 111. 5 is read and execute so 101. Make up your own encoding scheme.

I'm just writing something for storing TV schedule data from Schedules Direct and I have the binary or yes/no fields: stereo, hdtv, new, ei, close captioned, dolby, sap in Spanish, season premiere. So 7 bits, or an integer with a maximum of 127. One character really.

A C example from what I'm working on now. has() is a function that returns 1 if the 2nd string is in the first one. inp is the input string to this function. misc is an unsigned char initialized to 0.

if (has(inp,"sap='Spanish'") > 0)
  misc += 1;
if (has(inp,"stereo='true'") > 0)
  misc +=2;
if (has(inp,"ei='true'") > 0)
  misc +=4;
if (has(inp,"closeCaptioned='true'") > 0)
  misc += 8;
if (has(inp,"dolby=") > 0)
  misc += 16;
if (has(inp,"new='true'") > 0)
  misc += 32;
if (has(inp,"premier_finale='") > 0)
  misc += 64;
if (has(inp,"hdtv='true'") > 0)
  misc += 128;

So I'm storing 7 booleans in one integer with room for more.

Best way to get identity of inserted row?

One other way to guarantee the identity of the rows you insert is to specify the identity values and use the SET IDENTITY_INSERT ON and then OFF. This guarantees you know exactly what the identity values are! As long as the values are not in use then you can insert these values into the identity column.

CREATE TABLE #foo 
  ( 
     fooid   INT IDENTITY NOT NULL, 
     fooname VARCHAR(20) 
  ) 

SELECT @@Identity            AS [@@Identity], 
       Scope_identity()      AS [SCOPE_IDENTITY()], 
       Ident_current('#Foo') AS [IDENT_CURRENT] 

SET IDENTITY_INSERT #foo ON 

INSERT INTO #foo 
            (fooid, 
             fooname) 
VALUES      (1, 
             'one'), 
            (2, 
             'Two') 

SET IDENTITY_INSERT #foo OFF 

SELECT @@Identity            AS [@@Identity], 
       Scope_identity()      AS [SCOPE_IDENTITY()], 
       Ident_current('#Foo') AS [IDENT_CURRENT] 

INSERT INTO #foo 
            (fooname) 
VALUES      ('Three') 

SELECT @@Identity            AS [@@Identity], 
       Scope_identity()      AS [SCOPE_IDENTITY()], 
       Ident_current('#Foo') AS [IDENT_CURRENT] 

-- YOU CAN INSERT  
SET IDENTITY_INSERT #foo ON 

INSERT INTO #foo 
            (fooid, 
             fooname) 
VALUES      (10, 
             'Ten'), 
            (11, 
             'Eleven') 

SET IDENTITY_INSERT #foo OFF 

SELECT @@Identity            AS [@@Identity], 
       Scope_identity()      AS [SCOPE_IDENTITY()], 
       Ident_current('#Foo') AS [IDENT_CURRENT] 

SELECT * 
FROM   #foo 

This can be a very useful technique if you are loading data from another source or merging data from two databases etc.

how to console.log result of this ajax call?

Why not handle the error within the call?

i.e.

$.ajax({
    type: 'POST',
    url: 'loginCheck',
    data: $(formLogin).serialize(),
    dataType: 'json',
    error: function(req, err){ console.log('my message' + err); }
});

Get and Set a Single Cookie with Node.js HTTP Server

As an enhancement to @Corey Hart's answer, I've rewritten the parseCookies() using:

Here's the working example:

let http = require('http');

function parseCookies(str) {
  let rx = /([^;=\s]*)=([^;]*)/g;
  let obj = { };
  for ( let m ; m = rx.exec(str) ; )
    obj[ m[1] ] = decodeURIComponent( m[2] );
  return obj;
}

function stringifyCookies(cookies) {
  return Object.entries( cookies )
    .map( ([k,v]) => k + '=' + encodeURIComponent(v) )
    .join( '; ');
}

http.createServer(function ( request, response ) {
  let cookies = parseCookies( request.headers.cookie );
  console.log( 'Input cookies: ', cookies );
  cookies.search = 'google';
  if ( cookies.counter )
    cookies.counter++;
  else
    cookies.counter = 1;
  console.log( 'Output cookies: ', cookies );
  response.writeHead( 200, {
    'Set-Cookie': stringifyCookies(cookies),
    'Content-Type': 'text/plain'
  } );
  response.end('Hello World\n');
} ).listen(1234);

I also note that the OP uses the http module. If the OP was using restify, he can make use of restify-cookies:

var CookieParser = require('restify-cookies');
var Restify = require('restify');
var server = Restify.createServer();
server.use(CookieParser.parse);
server.get('/', function(req, res, next){
  var cookies = req.cookies; // Gets read-only cookies from the request
  res.setCookie('my-new-cookie', 'Hi There'); // Adds a new cookie to the response
  res.send(JSON.stringify(cookies));
});
server.listen(8080);

npm check and update package if needed

  • To update a single local package:

    1. First find out your outdated packages:

      npm outdated

    2. Then update the package or packages that you want manually as:

      npm update --save package_name

This way it is not necessary to update your local package.json file.

Note that this will update your package to the latest version.

  • If you write some version in your package.json file and do:

    npm update package_name

    In this case you will get just the next stable version (wanted) regarding the version that you wrote in your package.json file.

And with npm list (package_name) you can find out the current version of your local packages.

Android Intent Cannot resolve constructor

You Can not Use the Intent's Context for Creating Intent. So You need to use your Fragment's Parent Activity Context

Intent intent = new Intent(getActivity(),MyClass.class);

How to force reloading php.ini file?

TL;DR; If you're still having trouble after restarting apache or nginx, also try restarting the php-fpm service.

The answers here don't always satisfy the requirement to force a reload of the php.ini file. On numerous occasions I've taken these steps to be rewarded with no update, only to find the solution I need after also restarting the php-fpm service. So if restarting apache or nginx doesn't trigger a php.ini update although you know the files are updated, try restarting php-fpm as well.

To restart the service:

Note: prepend sudo if not root

Using SysV Init scripts directly:

/etc/init.d/php-fpm restart        # typical
/etc/init.d/php5-fpm restart       # debian-style
/etc/init.d/php7.0-fpm restart     # debian-style PHP 7

Using service wrapper script

service php-fpm restart        # typical
service php5-fpm restart       # debian-style
service php7.0-fpm restart.    # debian-style PHP 7

Using Upstart (e.g. ubuntu):

restart php7.0-fpm         # typical (ubuntu is debian-based) PHP 7
restart php5-fpm           # typical (ubuntu is debian-based)
restart php-fpm            # uncommon

Using systemd (newer servers):

systemctl restart php-fpm.service        # typical
systemctl restart php5-fpm.service       # uncommon
systemctl restart php7.0-fpm.service     # uncommon PHP 7

Or whatever the equivalent is on your system.

The above commands taken directly from this server fault answer

tqdm in Jupyter Notebook prints new progress bars repeatedly

If the other tips here don't work and - just like me - you're using the pandas integration through progress_apply, you can let tqdm handle it:

from tqdm.autonotebook import tqdm
tqdm.pandas()

df.progress_apply(row_function, axis=1)

The main point here lies in the tqdm.autonotebook module. As stated in their instructions for use in IPython Notebooks, this makes tqdm choose between progress bar formats used in Jupyter notebooks and Jupyter consoles - for a reason still lacking further investigations on my side, the specific format chosen by tqdm.autonotebook works smoothly in pandas, while all others didn't, for progress_apply specifically.

Getting all selected checkboxes in an array

This should do the trick:

$('input:checked');

I don't think you've got other elements that can be checked, but if you do, you'd have to make it more specific:

$('input:checkbox:checked');

$('input:checkbox').filter(':checked');

Copy file or directories recursively in Python

Unix cp doesn't 'support both directories and files':

betelgeuse:tmp james$ cp source/ dest/
cp: source/ is a directory (not copied).

To make cp copy a directory, you have to manually tell cp that it's a directory, by using the '-r' flag.

There is some disconnect here though - cp -r when passed a filename as the source will happily copy just the single file; copytree won't.

Why is processing a sorted array faster than processing an unsorted array?

The assumption by other answers that one needs to sort the data is not correct.

The following code does not sort the entire array, but only 200-element segments of it, and thereby runs the fastest.

Sorting only k-element sections completes the pre-processing in linear time, O(n), rather than the O(n.log(n)) time needed to sort the entire array.

#include <algorithm>
#include <ctime>
#include <iostream>

int main() {
    int data[32768]; const int l = sizeof data / sizeof data[0];

    for (unsigned c = 0; c < l; ++c)
        data[c] = std::rand() % 256;

    // sort 200-element segments, not the whole array
    for (unsigned c = 0; c + 200 <= l; c += 200)
        std::sort(&data[c], &data[c + 200]);

    clock_t start = clock();
    long long sum = 0;

    for (unsigned i = 0; i < 100000; ++i) {
        for (unsigned c = 0; c < sizeof data / sizeof(int); ++c) {
            if (data[c] >= 128)
                sum += data[c];
        }
    }

    std::cout << static_cast<double>(clock() - start) / CLOCKS_PER_SEC << std::endl;
    std::cout << "sum = " << sum << std::endl;
}

This also "proves" that it has nothing to do with any algorithmic issue such as sort order, and it is indeed branch prediction.

PHP - add 1 day to date format mm-dd-yyyy

Actually I wanted same alike thing, To get one year backward date, for a given date! :-)

With the hint of above answer from @mohammad mohsenipur I got to the following link, via his given link!

Luckily, there is a method same as date_add method, named date_sub method! :-) I do the following to get done what I wanted!

$date = date_create('2000-01-01');
date_sub($date, date_interval_create_from_date_string('1 years'));
echo date_format($date, 'Y-m-d');

Hopes this answer will help somebody too! :-)

Good luck guys!

Breaking/exit nested for in vb.net

If I want to exit a for-to loop, I just set the index beyond the limit:

    For i = 1 To max
        some code
        if this(i) = 25 Then i = max + 1
        some more code...
    Next`

Poppa.

Getting windbg without the whole WDK?

If you run winsdk_web.exe from the following link, you can selectively install windbg or extract windbg installer msi.

Microsoft Windows SDK for Windows 7 and .NET Framework 4 http://go.microsoft.com/fwlink/?LinkID=191420

Debugging tools for Windows

Powershell Log Off Remote Session

here is what i came up with. combining multiple answers

#computer list below
$computers = (
'computer1.domain.local',
'computer2.domain.local'

)
 
foreach ($Computer in $computers) {

 Invoke-Command -ComputerName $Computer -ScriptBlock { 
  Write-Host '______  '$Env:Computername
  $usertocheck = 'SomeUserName'
$sessionID = ((quser | Where-Object { $_ -match $usertocheck }) -split ' +')[2]
 

If([string]::IsNullOrEmpty($sessionID)){            
    Write-Host -ForegroundColor Yellow  "User Not Found."           
} else {            
    write-host -ForegroundColor Green  'Logging off ' $usertocheck 'Session ID' $sessionID
    logoff $sessionID    
}

 }
 }

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

I solved the error by modifying the following property in hibernate.cfg.xml

<property name="hibernate.hbm2ddl.auto">validate</property>

Earlier, the table was getting deleted each time I ran the program and now it doesnt, as hibernate only validates the schema and does not affect changes to it.

As far as I know you can also change from validate to update e.g.:

<property name="hibernate.hbm2ddl.auto">update</property>

When should iteritems() be used instead of items()?

As the dictionary documentation for python 2 and python 3 would tell you, in python 2 items returns a list, while iteritems returns a iterator.

In python 3, items returns a view, which is pretty much the same as an iterator.

If you are using python 2, you may want to user iteritems if you are dealing with large dictionaries and all you want to do is iterate over the items (not necessarily copy them to a list)

What is the OAuth 2.0 Bearer Token exactly?

As I read your question, I have tried without success to search on the Internet how Bearer tokens are encrypted or signed. I guess bearer tokens are not hashed (maybe partially, but not completely) because in that case, it will not be possible to decrypt it and retrieve users properties from it.

But your question seems to be trying to find answers on Bearer token functionality:

Suppose I am implementing an authorization provider, can I supply any kind of string for the bearer token? Can it be a random string? Does it has to be a base64 encoding of some attributes? Should it be hashed?

So, I'll try to explain how Bearer tokens and Refresh tokens work:

When user requests to the server for a token sending user and password through SSL, the server returns two things: an Access token and a Refresh token.

An Access token is a Bearer token that you will have to add in all request headers to be authenticated as a concrete user.

Authorization: Bearer <access_token>

An Access token is an encrypted string with all User properties, Claims and Roles that you wish. (You can check that the size of a token increases if you add more roles or claims). Once the Resource Server receives an access token, it will be able to decrypt it and read these user properties. This way, the user will be validated and granted along with all the application.

Access tokens have a short expiration (ie. 30 minutes). If access tokens had a long expiration it would be a problem, because theoretically there is no possibility to revoke it. So imagine a user with a role="Admin" that changes to "User". If a user keeps the old token with role="Admin" he will be able to access till the token expiration with Admin rights. That's why access tokens have a short expiration.

But, one issue comes in mind. If an access token has short expiration, we have to send every short period the user and password. Is this secure? No, it isn't. We should avoid it. That's when Refresh tokens appear to solve this problem.

Refresh tokens are stored in DB and will have long expiration (example: 1 month).

A user can get a new Access token (when it expires, every 30 minutes for example) using a refresh token, that the user had received in the first request for a token. When an access token expires, the client must send a refresh token. If this refresh token exists in DB, the server will return to the client a new access token and another refresh token (and will replace the old refresh token by the new one).

In case a user Access token has been compromised, the refresh token of that user must be deleted from DB. This way the token will be valid only till the access token expires because when the hacker tries to get a new access token sending the refresh token, this action will be denied.

Java Class that implements Map and keeps insertion order?

Whenever i need to maintain the natural order of things that are known ahead of time, i use a EnumMap

the keys will be enums and you can insert in any order you want but when you iterate it will iterate in the enum order (the natural order).

Also when using EnumMap there should be no collisions which can be more efficient.

I really find that using enumMap makes for clean readable code. Here is an example

Regex - Does not contain certain Characters

^[^<>]+$

The caret in the character class ([^) means match anything but, so this means, beginning of string, then one or more of anything except < and >, then the end of the string.

JavaScript Infinitely Looping slideshow with delays?

You can infinitely loop easily enough via recursion.

function it_keeps_going_and_going_and_going() {
  it_keeps_going_and_going_and_going();
}

it_keeps_going_and_going_and_going()

Convert NSDate to String in iOS Swift

Your updated code.update it.

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date as Date)
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
print(yourDate!)

Change image size via parent div

I am doing this way:

<div class="card-logo">
    <img height="100%" width="100%" src="http://someimage.jpg">
</div>

and CSS:

.card-logo {
    width: 20%;
}

I prefer this way, as if I need to upscale - I can use 150% as well

Is there a "previous sibling" selector?

I needed a solution to select the previous sibling tr. I came up with this solution using React and Styled-components. This is not my exact solution (This is from memory, hours later). I know there is a flaw in the setHighlighterRow function.

OnMouseOver a row will set the row index to state, and rerender the previous row with a new background color

class ReactClass extends Component {
  constructor() {
    this.state = {
       highlightRowIndex: null
    }
  }

  setHighlightedRow = (index) => {
    const highlightRowIndex = index === null ? null : index - 1;
    this.setState({highlightRowIndex});
  }

  render() {
    return (
       <Table>
        <Tbody>
           {arr.map((row, index) => {
                const isHighlighted = index === this.state.highlightRowIndex
                return {
                    <Trow 
                        isHighlighted={isHighlighted}
                        onMouseOver={() => this.setHighlightedRow(index)}
                        onMouseOut={() => this.setHighlightedRow(null)}
                        >
                        ...
                    </Trow>
                }
           })}  
        </Tbody>   
       </Table>
    )
  }
}

const Trow = styled.tr`
    & td {
        background-color: ${p => p.isHighlighted ? 'red' : 'white'};
    }

    &:hover {
        background-color: red;
    }
`;

mysql: get record count between two date-time

select * from yourtable where created < now() and created > '2011-04-25 04:00:00'

TypeError: 'DataFrame' object is not callable

It seems you need DataFrame.var:

Normalized by N-1 by default. This can be changed using the ddof argument

var1 = credit_card.var()

Sample:

#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
   A  B  C  D  E
0  8  8  3  7  7
1  0  4  2  5  2
2  2  2  1  0  8
3  4  0  9  6  2
4  4  1  5  3  4

var1 = credit_card.var()
print (var1)
A     8.8
B    10.0
C    10.0
D     7.7
E     7.8
dtype: float64

var2 = credit_card.var(axis=1)
print (var2)
0     4.3
1     3.8
2     9.8
3    12.2
4     2.3
dtype: float64

If need numpy solutions with numpy.var:

print (np.var(credit_card.values, axis=0))
[ 7.04  8.    8.    6.16  6.24]

print (np.var(credit_card.values, axis=1))
[ 3.44  3.04  7.84  9.76  1.84]

Differences are because by default ddof=1 in pandas, but you can change it to 0:

var1 = credit_card.var(ddof=0)
print (var1)
A    7.04
B    8.00
C    8.00
D    6.16
E    6.24
dtype: float64

var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0    3.44
1    3.04
2    7.84
3    9.76
4    1.84
dtype: float64

How do you find the row count for all your tables in Postgres

If you're in the psql shell, using \gexec allows you to execute the syntax described in syed's answer and Aur's answer without manual edits in an external text editor.

with x (y) as (
    select
        'select count(*), '''||
        tablename||
        ''' as "tablename" from '||
        tablename||' '
    from pg_tables
    where schemaname='public'
)
select
    string_agg(y,' union all '||chr(10)) || ' order by tablename'
from x \gexec

Note, string_agg() is used both to delimit union all between statements and to smush the separated datarows into a single unit to be passed into the buffer.

\gexec

Sends the current query buffer to the server, then treats each column of each row of the query's output (if any) as a SQL statement to be executed.

private final static attribute vs private final attribute

Reading the answers I found no real test really getting to the point. Here are my 2 cents :

public class ConstTest
{

    private final int         value             = 10;
    private static final int  valueStatic       = 20;
    private final File        valueObject       = new File("");
    private static final File valueObjectStatic = new File("");

    public void printAddresses() {


        System.out.println("final int address " +
                ObjectUtils.identityToString(value));
        System.out.println("final static int address " +
                ObjectUtils.identityToString(valueStatic));
        System.out.println("final file address " + 
                ObjectUtils.identityToString(valueObject));
        System.out.println("final static file address " + 
                ObjectUtils.identityToString(valueObjectStatic));
    }


    public static void main(final String args[]) {


        final ConstTest firstObj = new ConstTest();
        final ConstTest sndObj = new ConstTest();

        firstObj.printAdresses();
        sndObj.printAdresses();
    }

}

Results for first object :

final int address java.lang.Integer@6d9efb05
final static int address java.lang.Integer@60723d7c
final file address java.io.File@6c22c95b
final static file address java.io.File@5fd1acd3

Results for 2nd object :

final int address java.lang.Integer@6d9efb05
final static int address java.lang.Integer@60723d7c
final file address java.io.File@3ea981ca
final static file address java.io.File@5fd1acd3

Conclusion :

As I thought java makes a difference between primitive and other types. Primitive types in Java are always "cached", same for strings literals (not new String objects), so no difference between static and non-static members.

However there is a memory duplication for non-static members if they are not instance of a primitive type.

Changing value of valueStatic to 10 will even go further as Java will give the same addresses to the two int variables.

In oracle, how do I change my session to display UTF8?

The character set is part of the locale, which is determined by the value of NLS_LANG. As the documentation makes clear this is an operating system variable:

NLS_LANG is set as an environment variable on UNIX platforms. NLS_LANG is set in the registry on Windows platforms.

Now we can use ALTER SESSION to change the values for a couple of locale elements, NLS_LANGUAGE and NLS_TERRITORY. But not, alas, the character set. The reason for this discrepancy is - I think - that the language and territory simply effect how Oracle interprets the stored data, e.g. whether to display a comma or a period when displaying a large number. Wheareas the character set is concerned with how the client application renders the displayed data. This information is picked up by the client application at startup time, and cannot be changed from within.

How to get height and width of device display in angular2 using typescript?

You may use the typescript getter method for this scenario. Like this

public get height() {
  return window.innerHeight;
}

public get width() {
  return window.innerWidth;
}

And use that in template like this:

<section [ngClass]="{ 'desktop-view': width >= 768, 'mobile-view': width < 768 
}"></section>

Print the value

console.log(this.height, this.width);

You won't need any event handler to check for resizing of window, this method will check for size every time automatically.

disable editing default value of text input

I don't think all the other answerers understood the question correctly. The question requires disabling editing part of the text. One solution I can think of is simulating a textbox with a fixed prefix which is not part of the textarea or input.

An example of this approach is:

<div style="border:1px solid gray; color:#999999; font-family:arial; font-size:10pt; width:200px; white-space:nowrap;">Default Notes<br/>
<textarea style="border:0px solid black;" cols="39" rows="5"></textarea></div>

The other approach, which I end up using is using JS and JQuery to simulate "Disable" feature. Example with pseudo-code (cannot be specific cause of legal issue):

  // disable existing notes by preventing keystroke
  document.getElementById("txtNotes").addEventListener('keydown', function (e) {
    if (cursorLocation < defaultNoteLength ) {
            e.preventDefault();
  });

    // disable existing notes by preventing right click
    document.addEventListener('contextmenu', function (e) {
        if (cursorLocation < defaultNoteLength )
            e.preventDefault();
    });

Thanks, Carsten, for mentioning that this question is old, but I found that the solution might help other people in the future.

Reading and displaying data from a .txt file

If you want to take some shortcuts you can use Apache Commons IO:

import org.apache.commons.io.FileUtils;

String data = FileUtils.readFileToString(new File("..."), "UTF-8");
System.out.println(data);

:-)

How do you replace all the occurrences of a certain character in a string?

You really should have multiple input, e.g. one for firstname, middle names, lastname and another one for age. If you want to have some fun though you could try:

>>> input_given="join smith 25"
>>> chars="".join([i for i in input_given if not i.isdigit()])
>>> age=input_given.translate(None,chars)
>>> age
'25'
>>> name=input_given.replace(age,"").strip()
>>> name
'join smith'

This would of course fail if there is multiple numbers in the input. a quick check would be:

assert(age in input_given)

and also:

assert(len(name)<len(input_given))

C#: How to access an Excel cell?

If you are trying to automate Excel, you probably shouldn't be opening a Word document and using the Word automation ;)

Check this out, it should get you started,

http://www.codeproject.com/KB/office/package.aspx

And here is some code. It is taken from some of my code and has a lot of stuff deleted, so it doesn't do anything and may not compile or work exactly, but it should get you going. It is oriented toward reading, but should point you in the right direction.

Microsoft.Office.Interop.Excel.Worksheet sheet = newWorkbook.ActiveSheet;

if ( sheet != null )
{
    Microsoft.Office.Interop.Excel.Range range = sheet.UsedRange;
    if ( range != null )
    {
        int nRows = usedRange.Rows.Count;
        int nCols = usedRange.Columns.Count;
        foreach ( Microsoft.Office.Interop.Excel.Range row in usedRange.Rows )
        {
            string value = row.Cells[0].FormattedValue as string;
        }
    }
 }

You can also do

Microsoft.Office.Interop.Excel.Sheets sheets = newWorkbook.ExcelSheets;

if ( sheets != null )
{
     foreach ( Microsoft.Office.Interop.Excel.Worksheet sheet in sheets )
     {
          // Do Stuff
     }
}

And if you need to insert rows/columns

// Inserts a new row at the beginning of the sheet
Microsoft.Office.Interop.Excel.Range a1 = sheet.get_Range( "A1", Type.Missing );
a1.EntireRow.Insert( Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, Type.Missing );

Finding the 'type' of an input element

Check the type property. Would that suffice?

document.getelementbyId will return null if element is not defined?

Yes it will return null if it's not present you can try this below in the demo. Both will return true. The first elements exists the second doesn't.

Demo

Html

<div id="xx"></div>

Javascript:

   if (document.getElementById('xx') !=null) 
     console.log('it exists!');

   if (document.getElementById('xxThisisNotAnElementOnThePage') ==null) 
     console.log('does not exist!');

When to use malloc for char pointers

Everytime the size of the string is undetermined at compile time you have to allocate memory with malloc (or some equiviallent method). In your case you know the size of your strings at compile time (sizeof("something") and sizeof("something else")).

Python: Split a list into sub-lists based on index ranges

In python, it's called slicing. Here is an example of python's slice notation:

>>> list1 = ['a','b','c','d','e','f','g','h', 'i', 'j', 'k', 'l']
>>> print list1[:5]
['a', 'b', 'c', 'd', 'e']
>>> print list1[-7:]
['f', 'g', 'h', 'i', 'j', 'k', 'l']

Note how you can slice either positively or negatively. When you use a negative number, it means we slice from right to left.

Comparing two java.util.Dates to see if they are in the same day

private boolean isSameDay(Date date1, Date date2) {
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(date1);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(date2);
        boolean sameYear = calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR);
        boolean sameMonth = calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH);
        boolean sameDay = calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
        return (sameDay && sameMonth && sameYear);
    }

How to use Python's "easy_install" on Windows ... it's not so easy

For one thing, it says you already have that module installed. If you need to upgrade it, you should do something like this:

easy_install -U packageName

Of course, easy_install doesn't work very well if the package has some C headers that need to be compiled and you don't have the right version of Visual Studio installed. You might try using pip or distribute instead of easy_install and see if they work better.

What is a stack trace, and how can I use it to debug my application errors?

Just to add to the other examples, there are inner(nested) classes that appear with the $ sign. For example:

public class Test {

    private static void privateMethod() {
        throw new RuntimeException();
    }

    public static void main(String[] args) throws Exception {
        Runnable runnable = new Runnable() {
            @Override public void run() {
                privateMethod();
            }
        };
        runnable.run();
    }
}

Will result in this stack trace:

Exception in thread "main" java.lang.RuntimeException
        at Test.privateMethod(Test.java:4)
        at Test.access$000(Test.java:1)
        at Test$1.run(Test.java:10)
        at Test.main(Test.java:13)

echo key and value of an array without and with loop

You can try following code:

foreach ($arry as $key => $value) 
{
      echo $key;
      foreach ($value as  $val) 
      {
         echo $val; 
      }
}

How can I get the domain name of my site within a Django template?

I think what you want is to have access to the request context, see RequestContext.

How to convert int to Integer

As mentioned, one way is to use

new Integer(my_int_value)

But you should not call the constructor for wrapper classes directly

So, modify the code accordingly:

mBitmapCache.put(Integer.valueOf(R.drawable.bg1),object);

Wait for shell command to complete

Save the bat file on "C:\WINDOWS\system32" and use below code it is working

   Dim wsh As Object
   Set wsh = VBA.CreateObject("WScript.Shell")
   Dim waitOnReturn As Boolean: waitOnReturn = True
   Dim windowStyle As Integer: windowStyle = 1
   Dim errorCode As Integer

   errorCode = wsh.Run("runbat.bat", windowStyle, waitOnReturn)

If errorCode = 0 Then
    'Insert your code here
Else
    MsgBox "Program exited with error code " & errorCode & "."
End If   

How to recursively delete an entire directory with PowerShell 2.0?

I took another approach inspired by @john-rees above - especially when his approach started to fail for me at some point. Basically recurse the subtree and sort files by their path-length - delete from longest to the shortest

Get-ChildItem $tfsLocalPath -Recurse |  #Find all children
    Select-Object FullName,@{Name='PathLength';Expression={($_.FullName.Length)}} |  #Calculate the length of their path
    Sort-Object PathLength -Descending | #sort by path length descending
    %{ Get-Item -LiteralPath $_.FullName } | 
    Remove-Item -Force

Regarding the -LiteralPath magic, here's another gotchya that may be hitting you: https://superuser.com/q/212808

SQL query to group by day

For SQL Server:

GROUP BY datepart(year,datefield), 
    datepart(month,datefield), 
    datepart(day,datefield)

or faster (from Q8-Coder):

GROUP BY dateadd(DAY,0, datediff(day,0, created))

For MySQL:

GROUP BY year(datefield), month(datefield), day(datefield)

or better (from Jon Bright):

GROUP BY date(datefield)

For Oracle:

GROUP BY to_char(datefield, 'yyyy-mm-dd')

or faster (from IronGoofy):

GROUP BY trunc(created);

For Informix (by Jonathan Leffler):

GROUP BY date_column
GROUP BY EXTEND(datetime_column, YEAR TO DAY)

How can I get the source code of a Python function?

If you are using IPython, then you need to type "foo??"

In [19]: foo??
Signature: foo(arg1, arg2)
Source:
def foo(arg1,arg2):
    #do something with args
    a = arg1 + arg2
    return a

File:      ~/Desktop/<ipython-input-18-3174e3126506>
Type:      function

Multiple file upload in php

This is what worked for me. I had to upload files, store filenames and I had additional inof from input fields to store as well and one record per multiple file names. I used serialize() then added that to the main sql query.

  class addReminder extends dbconn {
    public function addNewReminder(){

           $this->exdate = $_POST['exdate'];
           $this->name = $_POST['name'];
           $this->category = $_POST['category'];
           $this->location = $_POST['location'];
           $this->notes = $_POST['notes'];



           try {

                     if(isset($_POST['submit'])){
                       $total = count($_FILES['fileUpload']['tmp_name']);
                       for($i=0;$i<$total;$i++){
                         $fileName = $_FILES['fileUpload']['name'][$i];
                         $ext = pathinfo($fileName, PATHINFO_EXTENSION);
                         $newFileName = md5(uniqid());
                         $fileDest = 'filesUploaded/'.$newFileName.'.'.$ext;
                         $justFileName = $newFileName.'.'.$ext;
                         if($ext === 'pdf' || 'jpeg' || 'JPG'){
                             move_uploaded_file($_FILES['fileUpload']['tmp_name'][$i], $fileDest);
                             $this->fileName = array($justFileName);
                             $this->encodedFileNames = serialize($this->fileName);
                             var_dump($this->encodedFileNames);
                         }else{
                           echo $fileName . ' Could not be uploaded. Pdfs and jpegs only please';
                         }
                       }

                    $sql = "INSERT INTO reminders (exdate, name, category, location, fileUpload, notes) VALUES (:exdate,:name,:category,:location,:fileName,:notes)";
                    $stmt = $this->connect()->prepare($sql);
                    $stmt->bindParam(':exdate', $this->exdate);
                    $stmt->bindParam(':name', $this->name);
                    $stmt->bindParam(':category', $this->category);
                    $stmt->bindParam(':location', $this->location);
                    $stmt->bindParam(':fileName', $this->encodedFileNames);
                    $stmt->bindParam(':notes', $this->notes);
                    $stmt->execute();
                  }

           }catch(PDOException $e){
             echo $e->getMessage();
           }
      }
    }

how to clear the screen in python

If you mean the screen where you have that interpreter prompt >>> you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do

import os
os.system('cls')  # on windows

or

os.system('clear')  # on linux / os x

How do I mount a remote Linux folder in Windows through SSH?

Apparently the free NetDrive software from Novell can access SFTP file servers.

How can I display a modal dialog in Redux that performs asynchronous actions?

The approach I suggest is a bit verbose but I found it to scale pretty well into complex apps. When you want to show a modal, fire an action describing which modal you'd like to see:

Dispatching an Action to Show the Modal

this.props.dispatch({
  type: 'SHOW_MODAL',
  modalType: 'DELETE_POST',
  modalProps: {
    postId: 42
  }
})

(Strings can be constants of course; I’m using inline strings for simplicity.)

Writing a Reducer to Manage Modal State

Then make sure you have a reducer that just accepts these values:

const initialState = {
  modalType: null,
  modalProps: {}
}

function modal(state = initialState, action) {
  switch (action.type) {
    case 'SHOW_MODAL':
      return {
        modalType: action.modalType,
        modalProps: action.modalProps
      }
    case 'HIDE_MODAL':
      return initialState
    default:
      return state
  }
}

/* .... */

const rootReducer = combineReducers({
  modal,
  /* other reducers */
})

Great! Now, when you dispatch an action, state.modal will update to include the information about the currently visible modal window.

Writing the Root Modal Component

At the root of your component hierarchy, add a <ModalRoot> component that is connected to the Redux store. It will listen to state.modal and display an appropriate modal component, forwarding the props from the state.modal.modalProps.

// These are regular React components we will write soon
import DeletePostModal from './DeletePostModal'
import ConfirmLogoutModal from './ConfirmLogoutModal'

const MODAL_COMPONENTS = {
  'DELETE_POST': DeletePostModal,
  'CONFIRM_LOGOUT': ConfirmLogoutModal,
  /* other modals */
}

const ModalRoot = ({ modalType, modalProps }) => {
  if (!modalType) {
    return <span /> // after React v15 you can return null here
  }

  const SpecificModal = MODAL_COMPONENTS[modalType]
  return <SpecificModal {...modalProps} />
}

export default connect(
  state => state.modal
)(ModalRoot)

What have we done here? ModalRoot reads the current modalType and modalProps from state.modal to which it is connected, and renders a corresponding component such as DeletePostModal or ConfirmLogoutModal. Every modal is a component!

Writing Specific Modal Components

There are no general rules here. They are just React components that can dispatch actions, read something from the store state, and just happen to be modals.

For example, DeletePostModal might look like:

import { deletePost, hideModal } from '../actions'

const DeletePostModal = ({ post, dispatch }) => (
  <div>
    <p>Delete post {post.name}?</p>
    <button onClick={() => {
      dispatch(deletePost(post.id)).then(() => {
        dispatch(hideModal())
      })
    }}>
      Yes
    </button>
    <button onClick={() => dispatch(hideModal())}>
      Nope
    </button>
  </div>
)

export default connect(
  (state, ownProps) => ({
    post: state.postsById[ownProps.postId]
  })
)(DeletePostModal)

The DeletePostModal is connected to the store so it can display the post title and works like any connected component: it can dispatch actions, including hideModal when it is necessary to hide itself.

Extracting a Presentational Component

It would be awkward to copy-paste the same layout logic for every “specific” modal. But you have components, right? So you can extract a presentational <Modal> component that doesn’t know what particular modals do, but handles how they look.

Then, specific modals such as DeletePostModal can use it for rendering:

import { deletePost, hideModal } from '../actions'
import Modal from './Modal'

const DeletePostModal = ({ post, dispatch }) => (
  <Modal
    dangerText={`Delete post ${post.name}?`}
    onDangerClick={() =>
      dispatch(deletePost(post.id)).then(() => {
        dispatch(hideModal())
      })
    })
  />
)

export default connect(
  (state, ownProps) => ({
    post: state.postsById[ownProps.postId]
  })
)(DeletePostModal)

It is up to you to come up with a set of props that <Modal> can accept in your application but I would imagine that you might have several kinds of modals (e.g. info modal, confirmation modal, etc), and several styles for them.

Accessibility and Hiding on Click Outside or Escape Key

The last important part about modals is that generally we want to hide them when the user clicks outside or presses Escape.

Instead of giving you advice on implementing this, I suggest that you just don’t implement it yourself. It is hard to get right considering accessibility.

Instead, I would suggest you to use an accessible off-the-shelf modal component such as react-modal. It is completely customizable, you can put anything you want inside of it, but it handles accessibility correctly so that blind people can still use your modal.

You can even wrap react-modal in your own <Modal> that accepts props specific to your applications and generates child buttons or other content. It’s all just components!

Other Approaches

There is more than one way to do it.

Some people don’t like the verbosity of this approach and prefer to have a <Modal> component that they can render right inside their components with a technique called “portals”. Portals let you render a component inside yours while actually it will render at a predetermined place in the DOM, which is very convenient for modals.

In fact react-modal I linked to earlier already does that internally so technically you don’t even need to render it from the top. I still find it nice to decouple the modal I want to show from the component showing it, but you can also use react-modal directly from your components, and skip most of what I wrote above.

I encourage you to consider both approaches, experiment with them, and pick what you find works best for your app and for your team.

AttributeError: 'tuple' object has no attribute

Variables names are only locally meaningful.

Once you hit

return s1,s2,s3,s4

at the end of the method, Python constructs a tuple with the values of s1, s2, s3 and s4 as its four members at index 0, 1, 2 and 3 - NOT a dictionary of variable names to values, NOT an object with variable names and their values, etc.

If you want the variable names to be meaningful after you hit return in the method, you must create an object or dictionary.

How to determine the last Row used in VBA including blank spaces in between

Well apart from all mentioned ones, there are several other ways to find the last row or column in a worksheet or specified range.

Function FindingLastRow(col As String) As Long

  'PURPOSE: Various ways to find the last row in a column or a range
  'ASSUMPTION: col is passed as column header name in string data type i.e. "B", "AZ" etc.

   Dim wks As Worksheet
   Dim lstRow As Long

   Set wks = ThisWorkbook.Worksheets("Sheet1") 'Please change the sheet name
   'Set wks = ActiveSheet   'or for your problem uncomment this line

   'Method #1: By Finding Last used cell in the worksheet
   lstRow = wks.Range("A1").SpecialCells(xlCellTypeLastCell).Row

   'Method #2: Using Table Range
   lstRow = wks.ListObjects("Table1").Range.Rows.Count

   'Method #3 : Manual way of selecting last Row : Ctrl + Shift + End
   lstRow = wks.Cells(wks.Rows.Count, col).End(xlUp).Row

   'Method #4: By using UsedRange
   wks.UsedRange 'Refresh UsedRange
   lstRow = wks.UsedRange.Rows(wks.UsedRange.Rows.Count).Row

   'Method #5: Using Named Range
   lstRow = wks.Range("MyNamedRange").Rows.Count

   'Method #6: Ctrl + Shift + Down (Range should be the first cell in data set)
   lstRow = wks.Range("A1").CurrentRegion.Rows.Count

   'Method #7: Using Range.Find method
   lstRow = wks.Column(col).Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row

   FindingLastRow = lstRow

End Function

Note: Please use only one of the above method as it justifies your problem statement.

Please pay attention to the fact that Find method does not see cell formatting but only data, hence look for xlCellTypeLastCell if only data is important and not formatting. Also, merged cells (which must be avoided) might give you unexpected results as it will give you the row number of the first cell and not the last cell in the merged cells.

How to sort by Date with DataTables jquery plugin?

Create a hidden column "dateOrder" (for example) with the date as string with the format "yyyyMMddHHmmss" and use the property "orderData" to point to that column.

var myTable = $("#myTable").dataTable({
 columns: [
      { data: "id" },
      { data: "date", "orderData": 4 },
      { data: "name" },
      { data: "total" },
      { data: "dateOrder", visible: false }
 ] });

Mapping many-to-many association table with extra column(s)

Since the SERVICE_USER table is not a pure join table, but has additional functional fields (blocked), you must map it as an entity, and decompose the many to many association between User and Service into two OneToMany associations : One User has many UserServices, and one Service has many UserServices.

You haven't shown us the most important part : the mapping and initialization of the relationships between your entities (i.e. the part you have problems with). So I'll show you how it should look like.

If you make the relationships bidirectional, you should thus have

class User {
    @OneToMany(mappedBy = "user")
    private Set<UserService> userServices = new HashSet<UserService>();
}

class UserService {
    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne
    @JoinColumn(name = "service_code")
    private Service service;

    @Column(name = "blocked")
    private boolean blocked;
}

class Service {
    @OneToMany(mappedBy = "service")
    private Set<UserService> userServices = new HashSet<UserService>();
}

If you don't put any cascade on your relationships, then you must persist/save all the entities. Although only the owning side of the relationship (here, the UserService side) must be initialized, it's also a good practice to make sure both sides are in coherence.

User user = new User();
Service service = new Service();
UserService userService = new UserService();

user.addUserService(userService);
userService.setUser(user);

service.addUserService(userService);
userService.setService(service);

session.save(user);
session.save(service);
session.save(userService);

npm not working - "read ECONNRESET"

I've tried almost all methods posted here and in other pages but didn't work. Here are the commands I've executed in order, which I encourage you to try because it worked for many people (but not me):

  • npm config rm proxy
  • npm config rm https-proxy
  • npm config set https-proxy https://username:[email protected]:6050
  • npm config set proxy http://username:[email protected]:6050
  • npm config set registry http://registry.npmjs.org/

And then trying to install the package npm install -g express, but it failed.

However, when I tried to run npm install npm@latest -g it miraculously executed and installed fine!
Then running npm install -g express again worked perfectly fine too.

TL;DR: updating npm to the latest version solved the issue (currently 6.0.1)

Should I use != or <> for not equal in T-SQL?

I understand that the C syntax != is in SQL Server due to its Unix heritage (back in the Sybase SQL Server days, pre Microsoft SQL Server 6.5).

Remove decimal values using SQL query

Here column name must be decimal.

select CAST(columnname AS decimal(38,0)) from table

Getting values from query string in an url using AngularJS $location

$location.search() returns an object, consisting of the keys as variables and the values as its value. So: if you write your query string like this:

?user=test_user_bLzgB

You could easily get the text like so:

$location.search().user

If you wish not to use a key, value like ?foo=bar, I suggest using a hash #test_user_bLzgB ,

and calling

$location.hash()

would return 'test_user_bLzgB' which is the data you wish to retrieve.

Additional info:

If you used the query string method and you are getting an empty object with $location.search(), it is probably because Angular is using the hashbang strategy instead of the html5 one... To get it working, add this config to your module

yourModule.config(['$locationProvider', function($locationProvider){
    $locationProvider.html5Mode(true);    
}]);

Ansible: create a user with sudo privileges

Sometimes it's knowing what to ask. I didn't know as I am a developer who has taken on some DevOps work.

Apparently 'passwordless' or NOPASSWD login is a thing which you need to put in the /etc/sudoers file.

The answer to my question is at Ansible: best practice for maintaining list of sudoers.

The Ansible playbook code fragment looks like this from my problem:

- name: Make sure we have a 'wheel' group
  group:
    name: wheel
    state: present

- name: Allow 'wheel' group to have passwordless sudo
  lineinfile:
    dest: /etc/sudoers
    state: present
    regexp: '^%wheel'
    line: '%wheel ALL=(ALL) NOPASSWD: ALL'
    validate: 'visudo -cf %s'

- name: Add sudoers users to wheel group
  user:
    name=deployer
    groups=wheel
    append=yes
    state=present
    createhome=yes

- name: Set up authorized keys for the deployer user
  authorized_key: user=deployer key="{{item}}"
  with_file:
    - /home/railsdev/.ssh/id_rsa.pub

And the best part is that the solution is idempotent. It doesn't add the line

%wheel ALL=(ALL) NOPASSWD: ALL

to /etc/sudoers when the playbook is run a subsequent time. And yes...I was able to ssh into the server as "deployer" and run sudo commands without having to give a password.

Easiest way to toggle 2 classes in jQuery

If your element exposes class A from the start, you can write:

$(element).toggleClass("A B");

This will remove class A and add class B. If you do that again, it will remove class B and reinstate class A.

If you want to match the elements that expose either class, you can use a multiple class selector and write:

$(".A, .B").toggleClass("A B");

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

I had the same error, but for me, the issue was that I was doing the request with a wrong GUID. I missed the last 2 characters.

360476f3-a4c8-4e1c-96d7-3c451c6c86
360476f3-a4c8-4e1c-96d7-3c451c6c865e

Angular2 - Focusing a textbox on component load

Also, it can be done dynamically like so...

<input [id]="input.id" [type]="input.type" [autofocus]="input.autofocus" />

Where input is

const input = {
  id: "my-input",
  type: "text",
  autofocus: true
};

Specifying ssh key in ansible playbook file

If you run your playbook with ansible-playbook -vvv you'll see the actual command being run, so you can check whether the key is actually being included in the ssh command (and you might discover that the problem was the wrong username rather than the missing key).

I agree with Brian's comment above (and zigam's edit) that the vars section is too late. I also tested including the key in the on-the-fly definition of the host like this

# fails
- name: Add all instance public IPs to host group
  add_host: hostname={{ item.public_ip }} groups=ec2hosts ansible_ssh_private_key_file=~/.aws/dev_staging.pem
  loop: "{{ ec2.instances }}"

but that fails too.

So this is not an answer. Just some debugging help and things not to try.

Unknown URL content://downloads/my_downloads

I have encountered the exception java.lang.IllegalArgumentException: Unknown URI: content://downloads/public_downloads/7505 in getting the doucument from the downloads. This solution worked for me.

else if (isDownloadsDocument(uri)) {
            String fileName = getFilePath(context, uri);
            if (fileName != null) {
                return Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
            }

            String id = DocumentsContract.getDocumentId(uri);
            if (id.startsWith("raw:")) {
                id = id.replaceFirst("raw:", "");
                File file = new File(id);
                if (file.exists())
                    return id;
            }

            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
            return getDataColumn(context, contentUri, null, null);
        }

This the method used to get the filepath

   public static String getFilePath(Context context, Uri uri) {

    Cursor cursor = null;
    final String[] projection = {
            MediaStore.MediaColumns.DISPLAY_NAME
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, null, null,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

This is a common problem. You're almost certainly running into permissions issues. To solve it, make sure that the apache user has read/write access to your entire repository. To do that, chown -R apache:apache *, chmod -R 664 * for everything under your svn repository.

Also, see here and here if you're still stuck.


Update to answer OP's additional question in comments:

The "664" string is an octal (base 8) representation of the permissions. There are three digits here, representing permissions for the owner, group, and everyone else (sometimes called "world"), respectively, for that file or directory.

Notice that each base 8 digit can be represented with 3 bits (000 for '0' through 111 for '7'). Each bit means something:

  • first bit: read permissions
  • second bit: write permissions
  • third bit: execute permissions

For example, 764 on a file would mean that:

  • the owner (first digit) has read/write/execute (7) permission
  • the group (second digit) has read/write (6) permission
  • everyone else (third digit) has read (4) permission

Hope that clears things up!

Check if table exists and if it doesn't exist, create it in SQL Server 2008

Declare @Username varchar(20)
Set @Username = 'Mike'

if not exists 
(Select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'tblEmp')

Begin
    Create table tblEmp (ID int primary key, Name varchar(50))
    Print (@Username + ' Table created successfully')
End

Else

Begin
    Print (@Username + ' : this Table Already exists in the database')
End

error: could not create '/usr/local/lib/python2.7/dist-packages/virtualenv_support': Permission denied

It's because the virtual environment viarable has not been installed.

Try this:

sudo pip install virtualenv
virtualenv --python python3 env
source env/bin/activate
pip install <Package>

or

sudo pip3 install virtualenv
virtualenv --python python3 env
source env/bin/activate
pip3 install <Package>

How many socket connections possible?

Which operating system?

For windows machines, if you're writing a server to scale well, and therefore using I/O Completion Ports and async I/O, then the main limitation is the amount of non-paged pool that you're using for each active connection. This translates directly into a limit based on the amount of memory that your machine has installed (non-paged pool is a finite, fixed size amount that is based on the total memory installed).

For connections that don't see much traffic you can reduce make them more efficient by posting 'zero byte reads' which don't use non-paged pool and don't affect the locked pages limit (another potentially limited resource that may prevent you having lots of socket connections open).

Apart from that, well, you will need to profile but I've managed to get more than 70,000 concurrent connections on a modestly specified (760MB memory) server; see here http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html for more details.

Obviously if you're using a less efficient architecture such as 'thread per connection' or 'select' then you should expect to achieve less impressive figures; but, IMHO, there's simply no reason to select such architectures for windows socket servers.

Edit: see here http://blogs.technet.com/markrussinovich/archive/2009/03/26/3211216.aspx; the way that the amount of non-paged pool is calculated has changed in Vista and Server 2008 and there's now much more available.

How to create a CPU spike with a bash command

#!/bin/bash
duration=120    # seconds
instances=4     # cpus
endtime=$(($(date +%s) + $duration))
for ((i=0; i<instances; i++))
do
    while (($(date +%s) < $endtime)); do :; done &
done

How to remove application from app listings on Android Developer Console

No, you cannot delete the application once you have published it in Google Play. Google will keep all the apk files. But you can unpublish the version, if you dont want that version to be availaible to user.

Responsive design with media query : screen size?

Take a look at this... http://getbootstrap.com/

For big websites I use Bootstrap and sometimes (for simple websites) I create all the style with some @mediaqueries. It's very simple, just think all the code in percentage.

.container {
max-width: 1200px;
width: 100%;
margin: 0 auto;
}

Inside the container, your structure must have widths in percentage like this...

.col-1 {
width: 40%;
float: left;
}

.col-2 {
width: 60%;
float: left;
}

@media screen and (max-width: 320px) {
.col-1, .col-2 { width: 100%; }
}

In some simple interfaces, if you start to develop the project in this way, you will have great chances to have a fully responsive site using break points only to adjust the flow of objects.

Return only string message from Spring MVC 3 Controller

This is just a note for those who might find this question later, but you don't have to pull in the response to change the content type. Here's an example below to do just that:

@RequestMapping(method = RequestMethod.GET, value="/controller")
public ResponseEntity<byte[]> displayUploadedFile()
{
  HttpHeaders headers = new HttpHeaders();
  String disposition = INLINE;
  String fileName = "";
  headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

  //Load your attachment here

  if (Arrays.equals(Constants.HEADER_BYTES_PDF, contentBytes)) {
    headers.setContentType(MediaType.valueOf("application/pdf"));
    fileName += ".pdf";
  }

  if (Arrays.equals(Constants.HEADER_BYTES_TIFF_BIG_ENDIAN, contentBytes)
      || Arrays.equals(Constantsr.HEADER_BYTES_TIFF_LITTLE_ENDIAN, contentBytes)) {
    headers.setContentType(MediaType.valueOf("image/tiff"));
    fileName += ".tif";
  }

  if (Arrays.equals(Constants.HEADER_BYTES_JPEG, contentBytes)) {
    headers.setContentType(MediaType.IMAGE_JPEG);
    fileName += ".jpg";
  }

  //Handle other types if necessary

  headers.add("Content-Disposition", , disposition + ";filename=" + fileName);
  return new ResponseEntity<byte[]>(uploadedBytes, headers, HttpStatus.OK);
}

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

form_for but to post to a different action

new syntax

<%= form_for :user, url: custom_user_path, method: :post do |f|%>
<%end%>

Forward X11 failed: Network error: Connection refused

PuTTY can't find where your X server is, because you didn't tell it. (ssh on Linux doesn't have this problem because it runs under X so it just uses that one.) Fill in the blank box after "X display location" with your Xming server's address.

Alternatively, try MobaXterm. It has an X server builtin.

<img>: Unsafe value used in a resource URL context

I usually add separate safe pipe reusable component as following

# Add Safe Pipe

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({name: 'mySafe'})
export class SafePipe implements PipeTransform {
    constructor(private sanitizer: DomSanitizer) {
    }

    public transform(url) {
        return this.sanitizer.bypassSecurityTrustResourceUrl(url);
    }
}
# then create shared pipe module as following 

import { NgModule } from '@angular/core'; 
import { SafePipe } from './safe.pipe';
@NgModule({
    declarations: [
        SafePipe
    ],
    exports: [
        SafePipe
    ]
})
export class SharedPipesModule {
}
# import shared pipe module in your native module

@NgModule({
    declarations: [],
    imports: [
        SharedPipesModule,
    ],
})
export class SupportModule {
}
<!-------------------
call your url (`trustedUrl` for me) and add `mySafe` as defined in Safe Pipe
---------------->
<div class="container-fluid" *ngIf="trustedUrl">
    <iframe [src]="trustedUrl | mySafe" align="middle" width="100%" height="800" frameborder="0"></iframe>
</div>

Converting BigDecimal to Integer

You would call myBigDecimal.intValueExact() (or just intValue()) and it will even throw an exception if you would lose information. That returns an int but autoboxing takes care of that.

Download File Using Javascript/jQuery

I know I'm late for the party, but I'd like to share my solution which is variation of Imagine Breaker's solution above. I tried to use his solution, because his solution seems most simple and easy to me. But like other said, it didn't work for some browsers, so I put some variation on it by using jquery.

Hope this could help someone out there.

function download(url) {
  var link = document.createElement("a");
  $(link).click(function(e) {
    e.preventDefault();
    window.location.href = url;
  });
  $(link).click();
}

Track a new remote branch created on GitHub

When the branch is no remote branch you can push your local branch direct to the remote.

git checkout master
git push origin master

or when you have a dev branch

git checkout dev
git push origin dev

or when the remote branch exists

git branch dev -t origin/dev

There are some other posibilites to push a remote branch.

How to echo (or print) to the js console with php

<?php
   echo '<script>console.log("Your stuff here")</script>';
?>

Disabling radio buttons with jQuery

Remove your "each" and just use:

$('input[name=ticketID]').attr("disabled",true);

That simple. It works

How to make a gui in python

Consider wxPython (which is cross-platform). Here is a tutorial.

Is there any difference between GROUP BY and DISTINCT

I know it's an old post. But it happens that I had a query that used group by just to return distinct values when using that query in toad and oracle reports everything worked fine, I mean a good response time. When we migrated from Oracle 9i to 11g the response time in Toad was excellent but in the reporte it took about 35 minutes to finish the report when using previous version it took about 5 minutes.

The solution was to change the group by and use DISTINCT and now the report runs in about 30 secs.

I hope this is useful for someone with the same situation.

"Strict Standards: Only variables should be passed by reference" error

This should be OK

   $value = explode(".", $value);
   $extension = strtolower(array_pop($value));   //Line 32
   // the file name is before the last "."
   $fileName = array_shift($value);  //Line 34

What does DIM stand for in Visual Basic and BASIC?

Short for Dimension. It's a type of variable. You declare (or "tell" Visual Basic) that you are setting up a variable with this word.

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

SQL multiple columns in IN clause

Ensure you have an index on your firstname and lastname columns and go with 1. This really won't have much of a performance impact at all.

EDIT: After @Dems comment regarding spamming the plan cache ,a better solution might be to create a computed column on the existing table (or a separate view) which contained a concatenated Firstname + Lastname value, thus allowing you to execute a query such as

SELECT City 
FROM User 
WHERE Fullname in (@fullnames)

where @fullnames looks a bit like "'JonDoe', 'JaneDoe'" etc

How to use wget in php?

Shellwrap is great tool for using the command-line in PHP!

Your example can be done quite easy and readable:

use MrRio\ShellWrap as sh;

$xml = (string)sh::curl(['u' => 'user:pass'], 'http://example.com/file.xml');

How to get the path of current worksheet in VBA?

The quickest way

path = ThisWorkbook.Path & "\"

ContractFilter mismatch at the EndpointDispatcher exception

The error says that there is a mismatch, assuming that you have a common contract based on the same WSDL, then the mismatch is in the configuration.

For example that the client is using nettcpip and the server is set up to use basic http.

Android Studio-No Module

I was able to resolve this issue by performing a Gradle sync

To do this:

  1. In project view, right click the root (in my example below, "JamsMusicPlayer"

  2. Click "Synchronize {ProjectName}"

  3. Once this completes, you should see a module in your "Run" dialog

Gradle sync

How to delete a module in Android Studio

To delete a module in Android Studio 2.3.3,

  • Open File -> Project Structure
  • On Project Structure window, list of modules of the current project gets displayed on left panel. Select the module which needs to be deleted.
  • Then click - button on top left, that means just above left panel.

How to generate a create table script for an existing table in phpmyadmin?

Run query is sql tab

SHOW CREATE TABLE tableName

Click on

+Options -> Choose Full texts -> Click on Go

Copy Create Table query and paste where you want to create new table.

Looping from 1 to infinity in Python

Simplest and best:

i = 0
while not there_is_reason_to_break(i):
    # some code here
    i += 1

It may be tempting to choose the closest analogy to the C code possible in Python:

from itertools import count

for i in count():
    if thereIsAReasonToBreak(i):
        break

But beware, modifying i will not affect the flow of the loop as it would in C. Therefore, using a while loop is actually a more appropriate choice for porting that C code to Python.

Using JAXB to unmarshal/marshal a List<String>

@GET
@Path("/test2")
public Response test2(){
   List<String> list=new Vector<String>();
   list.add("a");
   list.add("b");

   final GenericEntity<List<String>> entity = new GenericEntity<List<String>>(list) { };
   return Response.ok().entity(entity).build();
}

Set port for php artisan.php serve

You can use many ports together for each project,

  php artisan serve --port=8000

  php artisan serve --port=8001   

  php artisan serve --port=8002

  php artisan serve --port=8003

Adding a public key to ~/.ssh/authorized_keys does not log me in automatically

Beware that SELinux can trigger this error as well, even if all permissions seem to be OK. Disabling it did the trick for me (insert usual disclaimers about disabling it).