Programs & Examples On #Jboss weld

Weld is the reference implementation (RI) for JSR-299: Java Contexts and Dependency Injection for the Java EE platform (CDI)

How to add line break for UILabel?

In Swift 2.2, > iOS 8

I've set Lines = 0 on Storyboard, under Attribute Inspector and linked a referencing outlet to the label. Then use in controller like this:

 @IBOutlet weak var listLabel: UILabel!

 override func viewDidLoad() {
      ...
      listLabel.text = "Line 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7\nLine 8"
 }

Zip folder in C#

In .NET 4.5 the ZipFile.CreateFromDirectory(startPath, zipPath); method does not cover a scenario where you wish to zip a number of files and sub-folders without having to put them within a folder. This is valid when you wish the unzip to put the files directly within the current folder.

This code worked for me:

public static class FileExtensions
{
    public static IEnumerable<FileSystemInfo> AllFilesAndFolders(this DirectoryInfo dir)
    {
        foreach (var f in dir.GetFiles())
            yield return f;
        foreach (var d in dir.GetDirectories())
        {
            yield return d;
            foreach (var o in AllFilesAndFolders(d))
                yield return o;
        }
    }
}

void Test()
{
    DirectoryInfo from = new DirectoryInfo(@"C:\Test");
    using (FileStream zipToOpen = new FileStream(@"Test.zip", FileMode.Create))
    {
        using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
        {
            foreach (FileInfo file in from.AllFilesAndFolders().Where(o => o is FileInfo).Cast<FileInfo>())
            {
                var relPath = file.FullName.Substring(from.FullName.Length+1);
                ZipArchiveEntry readmeEntry = archive.CreateEntryFromFile(file.FullName, relPath);
            }
        }
    }
}

Folders don't need to be "created" in the zip-archive. The second parameter "entryName" in CreateEntryFromFile should be a relative path, and when unpacking the zip-file the directories of the relative paths will be detected and created.

C - gettimeofday for computing time?

To subtract timevals:

gettimeofday(&t0, 0);
/* ... */
gettimeofday(&t1, 0);
long elapsed = (t1.tv_sec-t0.tv_sec)*1000000 + t1.tv_usec-t0.tv_usec;

This is assuming you'll be working with intervals shorter than ~2000 seconds, at which point the arithmetic may overflow depending on the types used. If you need to work with longer intervals just change the last line to:

long long elapsed = (t1.tv_sec-t0.tv_sec)*1000000LL + t1.tv_usec-t0.tv_usec;

How to clear the text of all textBoxes in the form?

Your textboxes are probably inside of panels or other containers, and not directly inside the form.

You need to recursively traverse the Controls collection of every child control.

Simulate low network connectivity for Android

I found netlimiter4 to be the best solution for throttling data to emulators. It provides for granular control through a decent gui and gives you graphical feedback on the data throughput to each process. Currently in a free beta. screenshot

http://www.netlimiter.com/products/nl4

There are apps available on the play store to throttle to actual devices but they require root(I cant provide any advice as to how well they work, if at at all - YMMV.)

search for bradybound on the play store, I can't post more than one link..

What size do you use for varchar(MAX) in your parameter declaration?

You do not need to pass the size parameter, just declare Varchar already understands that it is MAX like:

cmd.Parameters.Add("@blah",SqlDbType.VarChar).Value = "some large text";

How are "mvn clean package" and "mvn clean install" different?

Well, both will clean. That means they'll remove the target folder. The real question is what's the difference between package and install?

package will compile your code and also package it. For example, if your pom says the project is a jar, it will create a jar for you when you package it and put it somewhere in the target directory (by default).

install will compile and package, but it will also put the package in your local repository. This will make it so other projects can refer to it and grab it from your local repository.

Documentation

SQL Switch/Case in 'where' clause

Try this query. Its very easy to understand:

CREATE TABLE PersonsDetail(FirstName nvarchar(20), LastName nvarchar(20), GenderID int);
GO

INSERT INTO PersonsDetail VALUES(N'Gourav', N'Bhatia', 2),
              (N'Ramesh', N'Kumar', 1),
              (N'Ram', N'Lal', 2),
              (N'Sunil', N'Kumar', 3),
              (N'Sunny', N'Sehgal', 1),
              (N'Malkeet', N'Shaoul', 3),
              (N'Jassy', N'Sohal', 2);
GO

SELECT FirstName, LastName, Gender =
    CASE GenderID
    WHEN 1 THEN 'Male'
    WHEN 2 THEN 'Female'
    ELSE 'Unknown'
    END
FROM PersonsDetail

HTML: How to limit file upload to be only images?

Edited

If things were as they SHOULD be, you could do this via the "Accept" attribute.

http://www.webmasterworld.com/forum21/6310.htm

However, browsers pretty much ignore this, so this is irrelavant. The short answer is, i don't think there is a way to do it in HTML. You'd have to check it server-side instead.

The following older post has some information that could help you with alternatives.

File input 'accept' attribute - is it useful?

Android: I am unable to have ViewPager WRAP_CONTENT

I have an version of WrapContentHeightViewPager that was working correctly before API 23 that will resize the parent view's height base on the current child view selected.

After upgrading to API 23, it stopped working. It turns out the old solution was using getChildAt(getCurrentItem()) to get the current child view to measure which is not working. See solution here: https://stackoverflow.com/a/16512217/1265583

Below works with API 23:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int height = 0;
    ViewPagerAdapter adapter = (ViewPagerAdapter)getAdapter();
    View child = adapter.getItem(getCurrentItem()).getView();
    if(child != null) {
        child.measure(widthMeasureSpec,  MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        height = child.getMeasuredHeight();
    }
    heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

Getting the name / key of a JToken with JSON.net

JObject obj = JObject.Parse(json);
var attributes = obj["parent"]["child"]...["your desired element"].ToList<JToken>(); 

foreach (JToken attribute in attributes)
{   
    JProperty jProperty = attribute.ToObject<JProperty>();
    string propertyName = jProperty.Name;
}

invalid use of incomplete type

You need to use a pointer or a reference as the proper type is not known at this time the compiler can not instantiate it.

Instead try:

void action(const typename Subclass::mytype &var) {
            (static_cast<Subclass*>(this))->do_action();
    }

Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

This explains better: Postman docs

Request body

While constructing requests, you would be dealing with the request body editor a lot. Postman lets you send almost any kind of HTTP request (If you can't send something, let us know!). The body editor is divided into 4 areas and has different controls depending on the body type.

form-data

multipart/form-data is the default encoding a web form uses to transfer data. This simulates filling a form on a website, and submitting it. The form-data editor lets you set key/value pairs (using the key-value editor) for your data. You can attach files to a key as well. Do note that due to restrictions of the HTML5 spec, files are not stored in history or collections. You would have to select the file again at the time of sending a request.

urlencoded

This encoding is the same as the one used in URL parameters. You just need to enter key/value pairs and Postman will encode the keys and values properly. Note that you can not upload files through this encoding mode. There might be some confusion between form-data and urlencoded so make sure to check with your API first.

raw

A raw request can contain anything. Postman doesn't touch the string entered in the raw editor except replacing environment variables. Whatever you put in the text area gets sent with the request. The raw editor lets you set the formatting type along with the correct header that you should send with the raw body. You can set the Content-Type header manually as well. Normally, you would be sending XML or JSON data here.

binary

binary data allows you to send things which you can not enter in Postman. For example, image, audio or video files. You can send text files as well. As mentioned earlier in the form-data section, you would have to reattach a file if you are loading a request through the history or the collection.

UPDATE

As pointed out by VKK, the WHATWG spec say urlencoded is the default encoding type for forms.

The invalid value default for these attributes is the application/x-www-form-urlencoded state. The missing value default for the enctype attribute is also the application/x-www-form-urlencoded state.

java.lang.IllegalAccessError: tried to access method

I was getting similar exception but at class level

e.g. Caused by: java.lang.IllegalAccessError: tried to access class ....

I fixed this by making my class public.

What is a tracking branch?

This was how I added a tracking branch so I can pull from it into my new branch:

git branch --set-upstream-to origin/Development new-branch

Parsing JSON with Unix tools

Parsing JSON is painful in a shell script. With a more appropriate language, create a tool that extracts JSON attributes in a way consistent with shell scripting conventions. You can use your new tool to solve the immediate shell scripting problem and then add it to your kit for future situations.

For example, consider a tool jsonlookup such that if I say jsonlookup access token id it will return the attribute id defined within the attribute token defined within the attribute access from stdin, which is presumably JSON data. If the attribute doesn't exist, the tool returns nothing (exit status 1). If the parsing fails, exit status 2 and a message to stderr. If the lookup succeeds, the tool prints the attribute's value.

Having created a unix tool for the precise purpose of extracting JSON values you can easily use it in shell scripts:

access_token=$(curl <some horrible crap> | jsonlookup access token id)

Any language will do for the implementation of jsonlookup. Here is a fairly concise python version:

#!/usr/bin/python                                                               

import sys
import json

try: rep = json.loads(sys.stdin.read())
except:
    sys.stderr.write(sys.argv[0] + ": unable to parse JSON from stdin\n")
    sys.exit(2)
for key in sys.argv[1:]:
    if key not in rep:
        sys.exit(1)
    rep = rep[key]
print rep

Get a filtered list of files in a directory

use os.walk to recursively list your files

import os
root = "/home"
pattern = "145992"
alist_filter = ['jpg','bmp','png','gif'] 
path=os.path.join(root,"mydir_to_scan")
for r,d,f in os.walk(path):
    for file in f:
        if file[-3:] in alist_filter and pattern in file:
            print os.path.join(root,file)

Spring MVC - Why not able to use @RequestBody and @RequestParam together

You could also just change the @RequestParam default required status to false so that HTTP response status code 400 is not generated. This will allow you to place the Annotations in any order you feel like.

@RequestParam(required = false)String name

org.hibernate.MappingException: Could not determine type for: java.util.Set

I had similar problem I found the issue I was mixing the annotations some of them above the attributes and some of them above public methods. I just put all of them above attributes and it works.

JavaScript closure inside loops – simple practical example

Let's say you don't use es6; You can use IFFY function:

var funcs = [];
for (var i = 0; i < 13; i++) {      
funcs[i] = (function(x) {
console.log("My value: " + i)})(i);}

But it will be different.

Copy a git repo without history

You can limit the depth of the history while cloning:

--depth <depth>
Create a shallow clone with a history truncated to the specified 
number of revisions.

Use this if you want limited history, but still some.

When is it appropriate to use C# partial classes?

I find it disturbing that the word 'cohesion' does not appear anywhere in these posts (until now). And I'm also disturbed that anyone thinks enabling or encouraging huge classes and methods is somehow a good thing. If you're trying to understand and maintain a code-base 'partial' sucks.

How to calculate the 95% confidence interval for the slope in a linear regression model in R

Let's fit the model:

> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)

Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)

Residuals:
    Min      1Q  Median      3Q     Max 
-245.74 -113.99  -32.05  104.96  484.81 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 811.2267    76.9755  10.539 2.29e-13 ***
body.weight   7.0595     0.9776   7.221 7.03e-09 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 

Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433 
F-statistic: 52.15 on 1 and 42 DF,  p-value: 7.025e-09 

The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).

This can be computed using confint:

> confint(fit, 'body.weight', level=0.95)
               2.5 % 97.5 %
body.weight 5.086656 9.0324

C++ printing spaces or tabs given a user input integer

Just use std::string:

std::cout << std::string( n, ' ' );

In many cases, however, depending on what comes next, is may be simpler to just add n to the parameter to an std::setw.

SQL Query with Join, Count and Where

I have used sub-query and it worked great!

SELECT *,(SELECT count(*) FROM $this->tbl_news WHERE
$this->tbl_news.cat_id=$this->tbl_categories.cat_id) as total_news FROM
$this->tbl_categories

Filling a List with all enum values in Java

Class.getEnumConstants()

List<SOME_ENUM> enumList = Arrays.asList(SOME_ENUM.class.getEnumConstants());

How to check not in array element

you can check using php in_array() built in function

<?php
  $os = array("Mac", "NT", "Irix", "Linux");
  if (in_array("Irix", $os)) {
    echo "Got Irix";
 }
 if (in_array("mac", $os)) {
  echo "Got mac";
}
?>

and you can also check using this

<?php
  $search_array = array('first' => 1, 'second' => 4);
  if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
   }
   ?>

in_array() is fine if you're only checking but if you need to check that a value exists and return the associated key, array_search is a better option.

$data = array(
0 => 'Key1',
1 => 'Key2'
);

$key = array_search('Key2', $data);

if ($key) {
 echo 'Key is ' . $key;
} else {
 echo 'Key not found';
}

for more details http://php.net/manual/en/function.in-array.php

gradlew: Permission Denied

I got the same error trying to execute flutter run on a mac. Apparently, in your flutter project, there is a file android/gradlew that is expected to be executable (and it wasn't). So in my case,

chmod a+rx android/gradlew

i used this command and execute the project

How to empty a file using Python

Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:

open(filename, 'w').close()

Microsoft Excel ActiveX Controls Disabled?

Advice in KB and above didn't work for me. I discovered that if one Excel 2007 user (with or without the security update; not sure of exact circumstances that cause this) saves the file, the original error returns.

I discovered that the fastest way to repair the file again is to delete all the VBA code. Save. Then replace the VBA code (copy/paste). Save. Before attempting this, I delete the .EXD files first, because otherwise I get an error on open.

In my case, I cannot upgrade/update all users of my Excel file in various locations. Since the problem comes back after some users save the Excel file, I am going to have to replace the ActiveX control with something else.

Relative imports in Python 3

I had a similar problem: I needed a Linux service and cgi plugin which use common constants to cooperate. The 'natural' way to do this is to place them in the init.py of the package, but I cannot start the cgi plugin with the -m parameter.

My final solution was similar to Solution #2 above:

import sys
import pathlib as p
import importlib

pp = p.Path(sys.argv[0])
pack = pp.resolve().parent

pkg = importlib.import_module('__init__', package=str(pack))

The disadvantage is that you must prefix the constants (or common functions) with pkg:

print(pkg.Glob)

PDF Editing in PHP?

If you are taking a 'fill in the blank' approach, you can precisely position text anywhere you want on the page. So it's relatively easy (if not a bit tedious) to add the missing text to the document. For example with Zend Framework:

<?php
require_once 'Zend/Pdf.php';

$pdf = Zend_Pdf::load('blank.pdf');
$page = $pdf->pages[0];
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
$page->setFont($font, 12);
$page->drawText('Hello world!', 72, 720);
$pdf->save('zend.pdf');

If you're trying to replace inline content, such as a "[placeholder string]," it gets much more complicated. While it's technically possible to do, you're likely to mess up the layout of the page.

A PDF document is comprised of a set of primitive drawing operations: line here, image here, text chunk there, etc. It does not contain any information about the layout intent of those primitives.

How to execute Ant build in command line

Go to the Ant website and download. This way, you have a copy of Ant outside of Eclipse. I recommend to put it under the C:\ant directory. This way, it doesn't have any spaces in the directory names. In your System Control Panel, set the Environment Variable ANT_HOME to this directory, then pre-pend to the System PATHvariable, %ANT_HOME%\bin. This way, you don't have to put in the whole directory name.

Assuming you did the above, try this:

C:\> cd \Silk4J\Automation\iControlSilk4J
C:\Silk4J\Automation\iControlSilk4J> ant -d build

This will do several things:

  • It will eliminate the possibility that the problem is with Eclipe's version of Ant.
  • It is way easier to type
  • Since you're executing the build.xml in the directory where it exists, you don't end up with the possibility that your Ant build can't locate a particular directory.

The -d will print out a lot of output, so you might want to capture it, or set your terminal buffer to something like 99999, and run cls first to clear out the buffer. This way, you'll capture all of the output from the beginning in the terminal buffer.

Let's see how Ant should be executing. You didn't specify any targets to execute, so Ant should be taking the default build target. Here it is:

<target depends="build-subprojects,build-project" name="build"/>

The build target does nothing itself. However, it depends upon two other targets, so these will be called first:

The first target is build-subprojects:

<target name="build-subprojects"/>

This does nothing at all. It doesn't even have a dependency.

The next target specified is build-project does have code:

<target depends="init" name="build-project">

This target does contain tasks, and some dependent targets. Before build-project executes, it will first run the init target:

<target name="init">
    <mkdir dir="bin"/>
    <copy includeemptydirs="false" todir="bin">
        <fileset dir="src">
            <exclude name="**/*.java"/>
        </fileset>
    </copy>
</target>

This target creates a directory called bin, then copies all files under the src tree with the suffix *.java over to the bin directory. The includeemptydirs mean that directories without non-java code will not be created.

Ant uses a scheme to do minimal work. For example, if the bin directory is created, the <mkdir/> task is not executed. Also, if a file was previously copied, or there are no non-Java files in your src directory tree, the <copy/> task won't run. However, the init target will still be executed.

Next, we go back to our previous build-project target:

<target depends="init" name="build-project">
    <echo message="${ant.project.name}: ${ant.file}"/>
    <javac debug="true" debuglevel="${debuglevel}" destdir="bin" source="${source}" target="${target}">
        <src path="src"/>
        <classpath refid="iControlSilk4J.classpath"/>
    </javac>
</target>

Look at this line:

<echo message="${ant.project.name}: ${ant.file}"/>

That should have always executed. Did your output print:

[echo] iControlSilk4J: C:\Silk4J\Automation\iControlSilk4J\build.xml

Maybe you didn't realize that was from your build.

After that, it runs the <javac/> task. That is, if there's any files to actually compile. Again, Ant tries to avoid work it doesn't have to do. If all of the *.java files have previously been compiled, the <javac/> task won't execute.

And, that's the end of the build. Your build might not have done anything simply because there was nothing to do. You can try running the clean task, and then build:

C:\Silk4J\Automation\iControlSilk4J> ant -d clean build

However, Ant usually prints the target being executed. You should have seen this:

init:

build-subprojects:

build-projects:

    [echo] iControlSilk4J: C:\Silk4J\Automation\iControlSilk4J\build.xml

build:

Build Successful

Note that the targets are all printed out in order they're executed, and the tasks are printed out as they are executed. However, if there's nothing to compile, or nothing to copy, then you won't see these tasks being executed. Does this look like your output? If so, it could be there's nothing to do.

  • If the bin directory already exists, <mkdir/> isn't going to execute.
  • If there are no non-Java files in src, or they have already been copied into bin, the <copy/> task won't execute.
  • If there are no Java file in your src directory, or they have already been compiled, the <java/> task won't run.

If you look at the output from the -d debug, you'll see Ant looking at a task, then explaining why a particular task wasn't executed. Plus, the debug option will explain how Ant decides what tasks to execute.

See if that helps.

How to properly add 1 month from now to current date in moment.js

You could try

moment().add(1, 'M').subtract(1, 'day').format('DD-MM-YYYY')

Where will log4net create this log file?

If you want your log file to be place at a specified location which will be decided at run time may be your project output directory then you can configure your .config file entry in that way

<file type="log4net.Util.PatternString" value="%property{LogFileName}.txt" />

and then in the code before calling log4net configure, set the new path like below

 log4net.GlobalContext.Properties["LogFileName"] = @"E:\\file1"; //log file path
 log4net.Config.XmlConfigurator.Configure();

How simple is it? :)

How do I start/stop IIS Express Server?

You can stop any IIS Express application or you can stop all application. Right click on IIS express icon , which is located at right bottom corner of task bar. Then Select Show All Application

enter image description here

Numpy where function multiple conditions

Try:

np.intersect1d(np.where(dists >= r)[0],np.where(dists <= r + dr)[0])

ByRef argument type mismatch in Excel VBA

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

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

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

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

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

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

End sub

and the next one is working as well:

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

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

End sub

Pandas groupby month and year

You can use either resample or Grouper (which resamples under the hood).

First make sure that the datetime column is actually of datetimes (hit it with pd.to_datetime). It's easier if it's a DatetimeIndex:

In [11]: df1
Out[11]:
            abc  xyz
Date
2013-06-01  100  200
2013-06-03  -20   50
2013-08-15   40   -5
2014-01-20   25   15
2014-02-21   60   80

In [12]: g = df1.groupby(pd.Grouper(freq="M"))  # DataFrameGroupBy (grouped by Month)

In [13]: g.sum()
Out[13]:
            abc  xyz
Date
2013-06-30   80  250
2013-07-31  NaN  NaN
2013-08-31   40   -5
2013-09-30  NaN  NaN
2013-10-31  NaN  NaN
2013-11-30  NaN  NaN
2013-12-31  NaN  NaN
2014-01-31   25   15
2014-02-28   60   80

In [14]: df1.resample("M", how='sum')  # the same
Out[14]:
            abc  xyz
Date
2013-06-30   40  125
2013-07-31  NaN  NaN
2013-08-31   40   -5
2013-09-30  NaN  NaN
2013-10-31  NaN  NaN
2013-11-30  NaN  NaN
2013-12-31  NaN  NaN
2014-01-31   25   15
2014-02-28   60   80

Note: Previously pd.Grouper(freq="M") was written as pd.TimeGrouper("M"). The latter is now deprecated since 0.21.


I had thought the following would work, but it doesn't (due to as_index not being respected? I'm not sure.). I'm including this for interest's sake.

If it's a column (it has to be a datetime64 column! as I say, hit it with to_datetime), you can use the PeriodIndex:

In [21]: df
Out[21]:
        Date  abc  xyz
0 2013-06-01  100  200
1 2013-06-03  -20   50
2 2013-08-15   40   -5
3 2014-01-20   25   15
4 2014-02-21   60   80

In [22]: pd.DatetimeIndex(df.Date).to_period("M")  # old way
Out[22]:
<class 'pandas.tseries.period.PeriodIndex'>
[2013-06, ..., 2014-02]
Length: 5, Freq: M

In [23]: per = df.Date.dt.to_period("M")  # new way to get the same

In [24]: g = df.groupby(per)

In [25]: g.sum()  # dang not quite what we want (doesn't fill in the gaps)
Out[25]:
         abc  xyz
2013-06   80  250
2013-08   40   -5
2014-01   25   15
2014-02   60   80

To get the desired result we have to reindex...

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

str.split() without any arguments splits on runs of whitespace characters:

>>> s = 'I am having a very nice day.'
>>> 
>>> len(s.split())
7

From the linked documentation:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

What is "pass-through authentication" in IIS 7?

Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.

With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.

If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.

The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.

Return a 2d array from a function

Whatever changes you would make in function will persist.So there is no need to return anything.You can pass 2d array and change it whenever you will like.

  void MakeGridOfCounts(int Grid[][6])
    {
      cGrid[6][6] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }};

    }

or

void MakeGridOfCounts(int Grid[][6],int answerArray[][6])
    {
     ....//do the changes in the array as you like they will reflect in main... 
    }

Temporary table in SQL server causing ' There is already an object named' error

I usually put these lines at the beginning of my stored procedure, and then at the end.

It is an "exists" check for #temp tables.

IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
begin
        drop table #MyCoolTempTable
end

Full Example:

CREATE PROCEDURE [dbo].[uspTempTableSuperSafeExample]
AS
BEGIN
    SET NOCOUNT ON;


    IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
    BEGIN
            DROP TABLE #MyCoolTempTable
    END


    CREATE TABLE #MyCoolTempTable (
        MyCoolTempTableKey INT IDENTITY(1,1),
        MyValue VARCHAR(128)
    )  

    INSERT INTO #MyCoolTempTable (MyValue)
        SELECT LEFT(@@VERSION, 128)
        UNION ALL SELECT TOP 10 LEFT(name, 128) from sysobjects

    SELECT MyCoolTempTableKey, MyValue FROM #MyCoolTempTable


    IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
    BEGIN
            DROP TABLE #MyCoolTempTable
    END


    SET NOCOUNT OFF;
END
GO

Get the current user, within an ApiController action, without passing the userID as a parameter

You can also access the principal using the User property on ApiController.

So the following two statements are basically the same:

string id;
id = User.Identity.GetUserId();
id = RequestContext.Principal.Identity.GetUserId();

How to paste text to end of every line? Sublime 2

Here's the workflow I use all the time, using the keyboard only

  1. Ctrl/Cmd + A Select All
  2. Ctrl/Cmd + Shift + L Split into Lines
  3. ' Surround every line with quotes

Note that this doesn't work if there are blank lines in the selection.

Android Studio Run/Debug configuration error: Module not specified

This issue also may happen when you just installed new Android studio and importing some project, in the new Android studio only the latest sdk is downloaded(for example currently the latest is 30) and if your project target sdk is 29 you will not see your module in run configuring dialog.

So download the sdk that your app is targeted, then run Sync project with gradle files.

enter image description here

How can we run a test method with multiple parameters in MSTest?

There is, of course, another way to do this which has not been discussed in this thread, i.e. by way of inheritance of the class containing the TestMethod. In the following example, only one TestMethod has been defined but two test cases have been made.

In Visual Studio 2012, it creates two tests in the TestExplorer:

  1. DemoTest_B10_A5.test
  2. DemoTest_A12_B4.test

    public class Demo
    {
        int a, b;
    
        public Demo(int _a, int _b)
        {
            this.a = _a;
            this.b = _b;
        }
    
        public int Sum()
        {
            return this.a + this.b;
        }
    }
    
    public abstract class DemoTestBase
    {
        Demo objUnderTest;
        int expectedSum;
    
        public DemoTestBase(int _a, int _b, int _expectedSum)
        {
            objUnderTest = new Demo(_a, _b);
            this.expectedSum = _expectedSum;
        }
    
        [TestMethod]
        public void test()
        {
            Assert.AreEqual(this.expectedSum, this.objUnderTest.Sum());
        }
    }
    
    [TestClass]
    public class DemoTest_A12_B4 : DemoTestBase
    {
        public DemoTest_A12_B4() : base(12, 4, 16) { }
    }
    
    public abstract class DemoTest_B10_Base : DemoTestBase
    {
        public DemoTest_B10_Base(int _a) : base(_a, 10, _a + 10) { }
    }
    
    [TestClass]
    public class DemoTest_B10_A5 : DemoTest_B10_Base
    {
        public DemoTest_B10_A5() : base(5) { }
    }
    

How to move a git repository into another directory and make that directory a git repository?

It's very simple. Git doesn't care about what's the name of its directory. It only cares what's inside. So you can simply do:

# copy the directory into newrepo dir that exists already (else create it)
$ cp -r gitrepo1 newrepo

# remove .git from old repo to delete all history and anything git from it
$ rm -rf gitrepo1/.git

Note that the copy is quite expensive if the repository is large and with a long history. You can avoid it easily too:

# move the directory instead
$ mv gitrepo1 newrepo

# make a copy of the latest version
# Either:
$ mkdir gitrepo1; cp -r newrepo/* gitrepo1/  # doesn't copy .gitignore (and other hidden files)

# Or:
$ git clone --depth 1 newrepo gitrepo1; rm -rf gitrepo1/.git

# Or (look further here: http://stackoverflow.com/q/1209999/912144)
$ git archive --format=tar --remote=<repository URL> HEAD | tar xf -

Once you create newrepo, the destination to put gitrepo1 could be anywhere, even inside newrepo if you want it. It doesn't change the procedure, just the path you are writing gitrepo1 back.

Can I have multiple background images using CSS?

Yes, it is possible, and has been implemented by popular usability testing website Silverback. If you look through the source code you can see that the background is made up of several images, placed on top of each other.

Here is the article demonstrating how to do the effect can be found on Vitamin. A similar concept for wrapping these 'onion skin' layers can be found on A List Apart.

How can I measure the actual memory usage of an application or process?

While this question seems to be about examining currently running processes, I wanted to see the peak memory used by an application from start to finish. Besides Valgrind, you can use tstime, which is much simpler. It measures the "highwater" memory usage (RSS and virtual). From this answer.

Raw SQL Query without DbSet - Entity Framework Core

With Entity Framework 6 you can execute something like below

Create Modal Class as

Public class User
{
        public int Id { get; set; }
        public string fname { get; set; }
        public string lname { get; set; }
        public string username { get; set; }
}

Execute Raw DQL SQl command as below:

var userList = datacontext.Database.SqlQuery<User>(@"SELECT u.Id ,fname , lname ,username FROM dbo.Users").ToList<User>();

Binding to static property

Leanest answer (.net 4.5 and later):

    static public event EventHandler FilterStringChanged;
    static string _filterString;
    static public string FilterString
    {
        get { return _filterString; }
        set
        {
            _filterString= value;
            FilterStringChanged?.Invoke(null, EventArgs.Empty);
        }
    }

and XAML:

    <TextBox Text="{Binding Path=(local:VersionManager.FilterString)}"/>

Don't neglect the brackets

How to draw a line with matplotlib?

I was checking how ax.axvline does work, and I've written a small function that resembles part of its idea:

import matplotlib.pyplot as plt
import matplotlib.lines as mlines

def newline(p1, p2):
    ax = plt.gca()
    xmin, xmax = ax.get_xbound()

    if(p2[0] == p1[0]):
        xmin = xmax = p1[0]
        ymin, ymax = ax.get_ybound()
    else:
        ymax = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmax-p1[0])
        ymin = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmin-p1[0])

    l = mlines.Line2D([xmin,xmax], [ymin,ymax])
    ax.add_line(l)
    return l

So, if you run the following code you will realize how does it work. The line will span the full range of your plot (independently on how big it is), and the creation of the line doesn't rely on any data point within the axis, but only in two fixed points that you need to specify.

import numpy as np
x = np.linspace(0,10)
y = x**2

p1 = [1,20]
p2 = [6,70]

plt.plot(x, y)
newline(p1,p2)
plt.show()

enter image description here

What is best way to start and stop hadoop ecosystem, with command line?

From Hadoop page,

start-all.sh 

This will startup a Namenode, Datanode, Jobtracker and a Tasktracker on your machine.

start-dfs.sh

This will bring up HDFS with the Namenode running on the machine you ran the command on. On such a machine you would need start-mapred.sh to separately start the job tracker

start-all.sh/stop-all.sh has to be run on the master node

You would use start-all.sh on a single node cluster (i.e. where you would have all the services on the same node.The namenode is also the datanode and is the master node).

In multi-node setup,

You will use start-all.sh on the master node and would start what is necessary on the slaves as well.

Alternatively,

Use start-dfs.sh on the node you want the Namenode to run on. This will bring up HDFS with the Namenode running on the machine you ran the command on and Datanodes on the machines listed in the slaves file.

Use start-mapred.sh on the machine you plan to run the Jobtracker on. This will bring up the Map/Reduce cluster with Jobtracker running on the machine you ran the command on and Tasktrackers running on machines listed in the slaves file.

hadoop-daemon.sh as stated by Tariq is used on each individual node. The master node will not start the services on the slaves.In a single node setup this will act same as start-all.sh.In a multi-node setup you will have to access each node (master as well as slaves) and execute on each of them.

Have a look at this start-all.sh it call config followed by dfs and mapred

Node.js quick file server (static files over HTTP)

You can use the NPM serve package for this, if you don't need the NodeJS stuff it is a quick and easy to use tool:

1 - Install the package on your PC:

npm install -g serve

2 - Serve your static folder with serve <path> :

d:> serve d:\StaticSite

It will show you which port your static folder is being served, just navigate to the host like:

http://localhost:3000

What is the proper #include for the function 'sleep()'?

The sleep man page says it is declared in <unistd.h>.

Synopsis:

#include <unistd.h>

unsigned int sleep(unsigned int seconds);

How to convert SQL Server's timestamp column to datetime format

Using cast you can get date from a timestamp field:

SELECT CAST(timestamp_field AS DATE) FROM tbl_name

Scrolling an iframe with JavaScript?

I've also had trouble using any type of javascript "scrollTo" function in an iframe on an iPad. Finally found an "old" solution to the problem, just hash to an anchor.

In my situation after an ajax return my error messages were set to display at the top of the iframe but if the user had scrolled down in what is an admittedly long form the submission goes out and the error appears "above the fold". Additionally, assuming the user did scroll way down the top level page was scrolled away from 0,0 and was also hidden.

I added

<a name="ptop"></a>

to the top of my iframe document and

<a name="atop"></a>

to the top of my top level page

then

    $(document).ready(function(){
      $("form").bind("ajax:complete",
        function() {
          location.hash = "#";
          top.location.hash = "#";
          setTimeout('location.hash="#ptop"',150);
          setTimeout('top.location.hash="#atop"',350);
        }
      )
    });

in the iframe.

You have to hash the iframe before the top page or only the iframe will scroll and the top will remain hidden but while it's a tiny bit "jumpy" due to the timeout intervals it works. I imagine tags throughout would allow various "scrollTo" points.

Calculate median in c#

Sometime in the future. This is I think as simple as it can get.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Median
{
    class Program
    {
        static void Main(string[] args)
        {
            var mediaValue = 0.0;
            var items = new[] { 1, 2, 3, 4,5 };
            var getLengthItems = items.Length;
            Array.Sort(items);
            if (getLengthItems % 2 == 0)
            {
                var firstValue = items[(items.Length / 2) - 1];
                var secondValue = items[(items.Length / 2)];
                mediaValue = (firstValue + secondValue) / 2.0;
            }
            if (getLengthItems % 2 == 1)
            {
                mediaValue = items[(items.Length / 2)];
            }
            Console.WriteLine(mediaValue);
            Console.WriteLine("Enter to Exit!");
            Console.ReadKey();
        }
    }
}

Getting a list item by index

You can use the ElementAt extension method on the list.

For example:

// Get the first item from the list

using System.Linq;

var myList = new List<string>{ "Yes", "No", "Maybe"};
var firstItem = myList.ElementAt(0);

// Do something with firstItem

CodeIgniter activerecord, retrieve last insert id?

Last insert id means you can get inserted auto increment id by using this method in active record,

$this->db->insert_id() 
// it can be return insert id it is 
// similar to the mysql_insert_id in core PHP

You can refer this link you can find some more stuff.

Information from executing a query

Can I set an unlimited length for maxJsonLength in web.config?

For those who are having issues with in MVC3 with JSON that's automatically being deserialized for a model binder and is too large, here is a solution.

  1. Copy the code for the JsonValueProviderFactory class from the MVC3 source code into a new class.
  2. Add a line to change the maximum JSON length before the object is deserialized.
  3. Replace the JsonValueProviderFactory class with your new, modified class.

Thanks to http://blog.naver.com/techshare/100145191355 and https://gist.github.com/DalSoft/1588818 for pointing me in the right direction for how to do this. The last link on the first site contains full source code for the solution.

mysql: SOURCE error 2?

solution - 1) Make sure you're in the root folder of your app. eg app/db/schema.sql.

solution - 2) open/reveal the folder on your window and drag&&drop in the command line next to keywork source (space) filesource. eg source User/myMAC/app/db/schema.sql

How to save a git commit message from windows cmd?

You are inside vim. To save changes and quit, type:

<esc> :wq <enter>

That means:

  • Press Escape. This should make sure you are in command mode
  • type in :wq
  • Press Return

An alternative that stdcall in the comments mentions is:

  • Press Escape
  • Press shift+Z shift+Z (capital Z twice).

PHP/regex: How to get the string value of HTML tag?

$userinput = "http://www.example.vn/";
//$url = urlencode($userinput);
$input = @file_get_contents($userinput) or die("Could not access file: $userinput");
$regexp = "<tagname\s[^>]*>(.*)<\/tagname>";
//==Example:
//$regexp = "<div\s[^>]*>(.*)<\/div>";

if(preg_match_all("/$regexp/siU", $input, $matches, PREG_SET_ORDER)) {
    foreach($matches as $match) {
        // $match[2] = link address 
        // $match[3] = link text
    }
}

Can I force a page break in HTML printing?

@Chris Doggett makes perfect sense. Although, I found one funny trick on lvsys.com, and it actually works on firefox and chrome. Just put this comment anywhere you want the page-break to be inserted. You can also replace the <p> tag with any block element.

<p><!-- pagebreak --></p>

How to make the script wait/sleep in a simple way in unity

With .Net 4.x you can use Task-based Asynchronous Pattern (TAP) to achieve this:

// .NET 4.x async-await
using UnityEngine;
using System.Threading.Tasks;
public class AsyncAwaitExample : MonoBehaviour
{
     private async void Start()
     {
        Debug.Log("Wait.");
        await WaitOneSecondAsync();
        DoMoreStuff(); // Will not execute until WaitOneSecond has completed
     }
    private async Task WaitOneSecondAsync()
    {
        await Task.Delay(TimeSpan.FromSeconds(1));
        Debug.Log("Finished waiting.");
    }
}

this is a feature to use .Net 4.x with Unity please see this link for description about it

and this link for sample project and compare it with coroutine

But becareful as documentation says that This is not fully replacement with coroutine

Experimental decorators warning in TypeScript compilation

in my case I solved this issue by setting "include": [ "src/**/*"] in my tsconfig.json file and restarting vscode. I've got this solution from a github issue: https://github.com/microsoft/TypeScript/issues/9335

How do I dynamically assign properties to an object in TypeScript?

You can create new object based on the old object using the spread operator

interface MyObject {
    prop1: string;
}

const myObj: MyObject = {
    prop1: 'foo',
}

const newObj = {
    ...myObj,
    prop2: 'bar',
}

console.log(newObj.prop2); // 'bar'

TypeScript will infer all the fields of the original object and VSCode will do autocompletion, etc.

How to get the day name from a selected date?

What about if we use String.Format here

_x000D_
_x000D_
DateTime today = DateTime.Today;_x000D_
String.Format("{0:dd-MM}, {1:dddd}", today, today) //In dd-MM format_x000D_
String.Format("{0:MM-dd}, {1:dddd}", today, today) //In MM-dd format
_x000D_
_x000D_
_x000D_

How to Change color of Button in Android when Clicked?

hai the most easiest way is this:

add this code to mainactivity.java

public void start(View view) {

  stop.setBackgroundResource(R.color.red);
 start.setBackgroundResource(R.color.yellow);
}

public void stop(View view) {
stop.setBackgroundResource(R.color.yellow);
start.setBackgroundResource(R.color.red);
}

and then in your activity main

    <button android:id="@+id/start" android:layout_height="wrap_content" android:layout_width="wrap_content" android:onclick="start" android:text="Click">

</button><button android:id="@+id/stop" android:layout_height="wrap_content" android:layout_width="wrap_content" android:onclick="stop" android:text="Click">

or follow along this tutorial

Best way to serialize/unserialize objects in JavaScript?

The browser's native JSON API may not give you back your idOld function after you call JSON.stringify, however, if can stringify your JSON yourself (maybe use Crockford's json2.js instead of browser's API), then if you have a string of JSON e.g.

var person_json = "{ \"age:\" : 20, \"isOld:\": false, isOld: function() { return this.age > 60; } }";

then you can call

eval("(" + person + ")") 

, and you will get back your function in the json object.

Mysql Compare two datetime fields

Your query apparently returned all correct dates, even considering the time.

If you're still not happy with the results, give DATEDIFF a shot and look for negaive/positive results between the two dates.

Make sure your mydate column is a datetime type.

How do I turn off Oracle password expiration?

For those who are using Oracle 12.1.0 for development purposes:
I found that the above methods would have no effect on the db user: "system", because the account_status would remain in the expired-grace period.

The easiest solution was for me to use SQL Developer:
within SQL Developer, I had to go to: View / DBA / Security and then Users / System and then on the right side: Actions / Expire pw and then: Actions / Edit and I could untick the option for expired.

This cleared the account_status, it shows OPEN again, and the SQL Developer is no longer showing the ORA-28002 message.

VBA for clear value in specific range of cell and protected cell from being wash away formula

Not sure its faster with VBA - the fastest way to do it in the normal Excel programm would be:

  1. Ctrl-G
  2. A1:X50 Enter
  3. Delete

Unless you have to do this very often, entering and then triggering the VBAcode is more effort.

And in case you only want to delete formulas or values, you can insert Ctrl-G, Alt-S to select Goto Special and here select Formulas or Values.

writing to serial port from linux command line

SCREEN:

NOTE: screen is actually not able to send hex, as far as I know. To do that, use echo or printf

I was using the suggestions in this post to write to a serial port, then using the info from another post to read from the port, with mixed results. I found that using screen is an "easier" solution, since it opens a terminal session directly with that port. (I put easier in quotes, because screen has a really weird interface, IMO, and takes some further reading to figure it out.)

You can issue this command to open a screen session, then anything you type will be sent to the port, plus the return values will be printed below it:

screen /dev/ttyS0 19200,cs8

(Change the above to fit your needs for speed, parity, stop bits, etc.) I realize screen isn't the "linux command line" as the post specifically asks for, but I think it's in the same spirit. Plus, you don't have to type echo and quotes every time.

ECHO:

Follow praetorian droid's answer. HOWEVER, this didn't work for me until I also used the cat command (cat < /dev/ttyS0) while I was sending the echo command.

PRINTF:

I found that one can also use printf's '%x' command:

c="\x"$(printf '%x' 0x12)
printf $c >> $SERIAL_COMM_PORT

Again, for printf, start cat < /dev/ttyS0 before sending the command.

How to get current working directory in Java?

Who says your main class is in a file on a local harddisk? Classes are more often bundled inside JAR files, and sometimes loaded over the network or even generated on the fly.

So what is it that you actually want to do? There is probably a way to do it that does not make assumptions about where classes come from.

Toggle Class in React

For anybody reading this in 2019, after React 16.8 was released, take a look at the React Hooks. It really simplifies handling states in components. The docs are very well written with an example of exactly what you need.

SELECT INTO USING UNION QUERY

You can also try:

create table new_table as
select * from table1
union
select * from table2

Jquery in React is not defined

Just a note: if you use arrow functions you don't need the const that = this part. It might look like this:

fetch('http://jsonplaceholder.typicode.com/posts') 
  .then((response) => { return response.json(); }) 
  .then((myJson) => { 
     this.setState({data: myJson}); // for example
});

delete word after or around cursor in VIM

I'd like to delete not only the word before cursor, but the word after or around cursor as well.

In that case the solution proposed by OP (i.e. using <c-w>) can be combined with the accepted answer to give:

inoremap <c-d> <c-o>daw<c-w>

alternatively (shorter solution):

inoremap <c-d> <c-o>vawobd

Sample input:

word1 word2 word3 word4
               ^------------- Cursor location

Output:

word1 word4

MySQL limit from descending order

yes, you can swap these 2 queries

select * from table limit 5, 5

select * from table limit 0, 5

Center-align a HTML table

table
{ 
margin-left: auto;
margin-right: auto;
}

This will definitely work. Cheers

How to convert ZonedDateTime to Date?

tl;dr

java.util.Date.from(  // Transfer the moment in UTC, truncating any microseconds or nanoseconds to milliseconds.
    Instant.now() ;   // Capture current moment in UTC, with resolution as fine as nanoseconds.
)

Though there was no point in that code above. Both java.util.Date and Instant represent a moment in UTC, always in UTC. Code above has same effect as:

new java.util.Date()  // Capture current moment in UTC.

No benefit here to using ZonedDateTime. If you already have a ZonedDateTime, adjust to UTC by extracting a Instant.

java.util.Date.from(             // Truncates any micros/nanos.
    myZonedDateTime.toInstant()  // Adjust to UTC. Same moment, same point on the timeline, different wall-clock time.
)

Other Answer Correct

The Answer by ssoltanid correctly addresses your specific question, how to convert a new-school java.time object (ZonedDateTime) to an old-school java.util.Date object. Extract the Instant from the ZonedDateTime and pass to java.util.Date.from().

Data Loss

Note that you will suffer data loss, as Instant tracks nanoseconds since epoch while java.util.Date tracks milliseconds since epoch.

diagram comparing resolutions of millisecond, microsecond, and nanosecond

Your Question and comments raise other issues.

Keep Servers In UTC

Your servers should have their host OS set to UTC as a best practice generally. The JVM picks up on this host OS setting as its default time zone, in the Java implementations that I'm aware of.

Specify Time Zone

But you should never rely on the JVM’s current default time zone. Rather than pick up the host setting, a flag passed when launching a JVM can set another time zone. Even worse: Any code in any thread of any app at any moment can make a call to java.util.TimeZone::setDefault to change that default at runtime!

Cassandra Timestamp Type

Any decent database and driver should automatically handle adjusting a passed date-time to UTC for storage. I do not use Cassandra, but it does seem to have some rudimentary support for date-time. The documentation says its Timestamp type is a count of milliseconds from the same epoch (first moment of 1970 in UTC).

ISO 8601

Furthermore, Cassandra accepts string inputs in the ISO 8601 standard formats. Fortunately, java.time uses ISO 8601 formats as its defaults for parsing/generating strings. The Instant class’ toString implementation will do nicely.

Precision: Millisecond vs Nanosecord

But first we need to reduce the nanosecond precision of ZonedDateTime to milliseconds. One way is to create a fresh Instant using milliseconds. Fortunately, java.time has some handy methods for converting to and from milliseconds.

Example Code

Here is some example code in Java 8 Update 60.

ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) );
…
Instant instant = zdt.toInstant();
Instant instantTruncatedToMilliseconds = Instant.ofEpochMilli( instant.toEpochMilli() );
String fodderForCassandra = instantTruncatedToMilliseconds.toString();  // Example: 2015-08-18T06:36:40.321Z

Or according to this Cassandra Java driver doc, you can pass a java.util.Date instance (not to be confused with java.sqlDate). So you could make a j.u.Date from that instantTruncatedToMilliseconds in the code above.

java.util.Date dateForCassandra = java.util.Date.from( instantTruncatedToMilliseconds );

If doing this often, you could make a one-liner.

java.util.Date dateForCassandra = java.util.Date.from( zdt.toInstant() );

But it would be neater to create a little utility method.

static public java.util.Date toJavaUtilDateFromZonedDateTime ( ZonedDateTime zdt ) {
    Instant instant = zdt.toInstant();
    // Data-loss, going from nanosecond resolution to milliseconds.
    java.util.Date utilDate = java.util.Date.from( instant ) ;
    return utilDate;
}

Notice the difference in all this code than in the Question. The Question’s code was trying to adjust the time zone of the ZonedDateTime instance to UTC. But that is not necessary. Conceptually:

ZonedDateTime = Instant + ZoneId

We just extract the Instant part, which is already in UTC (basically in UTC, read the class doc for precise details).


Table of date-time types in Java, both modern and legacy


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Cannot edit in read-only editor VS Code

I was experiencing this issue while using the SFTP extension in VSCode. In this case, all you have to do is right-click somewhere in the file and select 'edit in local'

enter image description here

enter image description here

enter image description here

Reading local text file into a JavaScript array

Using Node.js

sync mode:

var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")

async mode:

var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
    var textByLine = text.split("\n")
});

UPDATE

As of at least Node 6, readFileSync returns a Buffer, so it must first be converted to a string in order for split to work:

var text = fs.readFileSync("./mytext.txt").toString('utf-8');

Or

var text = fs.readFileSync("./mytext.txt", "utf-8");

How to embed a PDF?

Here is the code you can use for every browser:

<embed src="pdfFiles/interfaces.pdf" width="600" height="500" alt="pdf" pluginspage="http://www.adobe.com/products/acrobat/readstep2.html">

Tested on firefox and chrome

Tooltip on image

Using javascript, you can set tooltips for all the images on the page.

_x000D_
_x000D_
<!DOCTYPE html>
<html>
    <body>
    <img src="http://sushmareddy.byethost7.com/dist/img/buffet.png" alt="Food">
    <img src="http://sushmareddy.byethost7.com/dist/img/uthappizza.png" alt="Pizza">
     <script>
     //image objects
     var imageEls = document.getElementsByTagName("img");
     //Iterating
     for(var i=0;i<imageEls.length;i++){
        imageEls[i].title=imageEls[i].alt;
        //OR
        //imageEls[i].title="Title of your choice";
     }
        </script>
    </body>
</html>
_x000D_
_x000D_
_x000D_

Using PHP Replace SPACES in URLS with %20

$result = preg_replace('/ /', '%20', 'your string here');

you may also consider using

$result = urlencode($yourstring)

to escape other special characters as well

Safest way to run BAT file from Powershell script

To run the .bat, and have access to the last exit code, run it as:

 & .\my-app\my-fle.bat

Logcat not displaying my log calls

There are a number of reasons why you might not see logs, most of which are listed below. Here are some steps to check most reasons:

  1. Make sure you don't have 'android:debuggable="false"' in your AndroidManifest.xml
  2. Make sure your logcat isn't paused and make sure you are scrolled to the bottom
  3. Your filters should either be 'no filters' or your current app
  4. You have the correct device selected in your logcat devices list
  5. If you're not getting any messages, try restarting adb. You can do that from Android Studio by clicking on the 'restart' icon, it's right after the print icon for logcat and it looks like a green curved arrow coming out of a box. If you don't see it, mouse over the '>>' that continues the icon menu when the logcat is too small.

Is there a way to rollback my last push to Git?

Since you are the only user:

git reset --hard HEAD@{1}
git push -f
git reset --hard HEAD@{1}

( basically, go back one commit, force push to the repo, then go back again - remove the last step if you don't care about the commit )

Without doing any changes to your local repo, you can also do something like:

git push -f origin <sha_of_previous_commit>:master

Generally, in published repos, it is safer to do git revert and then git push

Selecting Folder Destination in Java?

I found a good example of what you need in this link.

import javax.swing.JFileChooser;

public class Main {
  public static void main(String s[]) {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle("choosertitle");
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setAcceptAllFileFilterUsed(false);

    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
      System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
      System.out.println("getSelectedFile() : " + chooser.getSelectedFile());
    } else {
      System.out.println("No Selection ");
    }
  }
}

is of a type that is invalid for use as a key column in an index

There is a limitation in SQL Server (up till 2008 R2) that varchar(MAX) and nvarchar(MAX) (and several other types like text, ntext ) cannot be used in indices. You have 2 options:
1. Set a limited size on the key field ex. nvarchar(100)
2. Create a check constraint that compares the value with all the keys in the table. The condition is:

([dbo].[CheckKey]([key])=(1))

and [dbo].[CheckKey] is a scalar function defined as:

CREATE FUNCTION [dbo].[CheckKey]
(
    @key nvarchar(max)
)
RETURNS bit
AS
BEGIN
    declare @res bit
    if exists(select * from key_value where [key] = @key)
        set @res = 0
    else
        set @res = 1

    return @res
END

But note that a native index is more performant than a check constraint so unless you really can't specify a length, don't use the check constraint.

"query function not defined for Select2 undefined error"

This error message is too general. One of its other possible sources is that you're trying to call select2() method on already "select2ed" input.

console.writeline and System.out.println

First I am afraid your question contains a little mistake. There is not method writeline in class Console. Instead class Console provides method writer() that returns PrintWriter. This print writer has println().

Now what is the difference between

System.console().writer().println("hello from console");

and

System.out.println("hello system out");

If you run your application from command line I think there is no difference. But if console is unavailable System.console() returns null while System.out still exists. This may happen if you invoke your application and perform redirect of STDOUT to file.

Here is an example I have just implemented.

import java.io.Console;


public class TestConsole {
    public static void main(String[] args) {
        Console console = System.console();
        System.out.println("console=" + console);
        console.writer().println("hello from console");
    }
}

When I ran the application from command prompt I got the following:

$ java TestConsole
console=java.io.Console@93dcd
hello from console

but when I redirected the STDOUT to file...

$ java TestConsole >/tmp/test
Exception in thread "main" java.lang.NullPointerException
        at TestConsole.main(TestConsole.java:8)

Line 8 is console.writer().println().

Here is the content of /tmp/test

console=null

I hope my explanations help.

Why is vertical-align: middle not working on my span or div?

HTML

<div id="myparent">
  <div id="mychild">Test Content here</div>
</div>

CSS

#myparent {
  display: table;
}
#mychild {
  display: table-cell;
  vertical-align: middle;
}

We set the parent div to display as a table and the child div to display as a table-cell. We can then use vertical-align on the child div and set its value to middle. Anything inside this child div will be vertically centered.

Issue with background color and Google Chrome

It must be a WebKit issue as it is in both Safari 4 and Chrome.

how to overlap two div in css?

check this fiddle , and if you want to move the overlapped div you set its position to absolute then change it's top and left values

How to update UI from another thread running in another class

Everything that interacts with the UI must be called in the UI thread (unless it is a frozen object). To do that, you can use the dispatcher.

var disp = /* Get the UI dispatcher, each WPF object has a dispatcher which you can query*/
disp.BeginInvoke(DispatcherPriority.Normal,
        (Action)(() => /*Do your UI Stuff here*/));

I use BeginInvoke here, usually a backgroundworker doesn't need to wait that the UI updates. If you want to wait, you can use Invoke. But you should be careful not to call BeginInvoke to fast to often, this can get really nasty.

By the way, The BackgroundWorker class helps with this kind of taks. It allows Reporting changes, like a percentage and dispatches this automatically from the Background thread into the ui thread. For the most thread <> update ui tasks the BackgroundWorker is a great tool.

Identify if a string is a number

public static bool IsNumeric(this string input)
{
    int n;
    if (!string.IsNullOrEmpty(input)) //.Replace('.',null).Replace(',',null)
    {
        foreach (var i in input)
        {
            if (!int.TryParse(i.ToString(), out n))
            {
                return false;
            }

        }
        return true;
    }
    return false;
}

Should each and every table have a primary key?

Pretty much any time I've created a table without a primary key, thinking I wouldn't need one, I've ended up going back and adding one. I now create even my join tables with an auto-generated identity field that I use as the primary key.

What svn command would list all the files modified on a branch?

svn log -q -v shows paths and hides comments. All the paths are indented so you can search for lines starting with whitespace. Then pipe to cut and sort to tidy up:

svn log --stop-on-copy -q -v | grep '^[[:space:]]'| cut -c6- | sort -u

This gets all the paths mentioned on the branch since its branch point. Note it will list deleted and added, as well as modified files. I just used this to get the stuff I should worry about reviewing on a slightly messy branch from a new dev.

How to force a line break in a long word in a DIV?

CSS word-wrap:break-word;, tested in FireFox 3.6.3

How to combine 2 plots (ggplot) into one plot?

Creating a single combined plot with your current data set up would look something like this

p <- ggplot() +
      # blue plot
      geom_point(data=visual1, aes(x=ISSUE_DATE, y=COUNTED)) + 
      geom_smooth(data=visual1, aes(x=ISSUE_DATE, y=COUNTED), fill="blue",
        colour="darkblue", size=1) +
      # red plot
      geom_point(data=visual2, aes(x=ISSUE_DATE, y=COUNTED)) + 
      geom_smooth(data=visual2, aes(x=ISSUE_DATE, y=COUNTED), fill="red",
        colour="red", size=1)

however if you could combine the data sets before plotting then ggplot will automatically give you a legend, and in general the code looks a bit cleaner

visual1$group <- 1
visual2$group <- 2

visual12 <- rbind(visual1, visual2)

p <- ggplot(visual12, aes(x=ISSUE_DATE, y=COUNTED, group=group, col=group, fill=group)) +
      geom_point() +
      geom_smooth(size=1)

How to check if an option is selected?

If you want to check selected option through javascript

Simplest method is add onchange attribute in that tag and define a function in js file see example if your html file has options something like this

 <select onchange="subjects(this.value)">
               <option>Select subject</option>
               <option value="Computer science">Computer science</option>
               <option value="Information Technolgy">Information Technolgy</option>
               <option value="Electronic Engineering">Electronic Engineering</option>
               <option value="Electrical Engineering">Electrical Engineering</option>
 </select>

And now add function in js file

function subjects(str){
    console.log(`selected option is ${str}`);
}

If you want to check selected option in php file

Simply give name attribute in your tag and access it php file global variables /array ($_GET or $_POST) see example if your html file is something like this

<form action="validation.php" method="POST">
             Subject:<br>
            <select name="subject">
               <option>Select subject</option>
               <option value="Computer science">Computer science</option>
               <option value="Information Technolgy">Information Technolgy</option>
               <option value="Electronic Engineering">Electronic Engineering</option>
               <option value="Electrical Engineering">Electrical Engineering</option>
            </select><br>

         </form>

And in your php file validation.php you can access like this

$subject = $_POST['subject'];
echo "selected option is $subject";

What Ruby IDE do you prefer?

Redcar has been getting some attention lately, as well. Still early in its life, but it shows promise.

Python, how to read bytes from file and save it?

with open("input", "rb") as input:
    with open("output", "wb") as output:
        while True:
            data = input.read(1024)
            if data == "":
                break
            output.write(data)

The above will read 1 kilobyte at a time, and write it. You can support incredibly large files this way, as you won't need to read the entire file into memory.

How to get indices of a sorted array in Python

myList = [1, 2, 3, 100, 5]    
sorted(range(len(myList)),key=myList.__getitem__)

[0, 1, 2, 4, 3]

Conversion failed when converting the varchar value 'simple, ' to data type int

If you are converting a varchar to int make sure you do not have decimal places.

For example, if you are converting a varchar field with value (12345.0) to an integer then you get this conversion error. In my case I had all my fields with .0 as ending so I used the following statement to globally fix the problem.

CONVERT(int, replace(FIELD_NAME,'.0',''))

submit a form in a new tab

Add target="_blank" to the <form> tag.

Formatting ISODate from Mongodb

you can use mongo query like this yearMonthDayhms: { $dateToString: { format: "%Y-%m-%d-%H-%M-%S", date: {$subtract:["$cdt",14400000]}}}

HourMinute: { $dateToString: { format: "%H-%M-%S", date: {$subtract:["$cdt",14400000]}}}

enter image description here

LINQ: "contains" and a Lambda query

If I understand correctly, you need to convert the type (char value) that you store in Building list to the type (enum) that you store in buildingStatus list.

(For each status in the Building list//character value//, does the status exists in the buildingStatus list//enum value//)

public static IQueryable<Building> WithStatus(this IQueryable<Building> qry,  
IList<BuildingStatuses> buildingStatus) 
{ 
    return from v in qry
           where ContainsStatus(v.Status)
           select v;
} 


private bool ContainsStatus(v.Status)
{
    foreach(Enum value in Enum.GetValues(typeof(buildingStatus)))
    {
        If v.Status == value.GetCharValue();
            return true;
    }

    return false;
}

How to move all HTML element children to another parent using JavaScript?

This answer only really works if you don't need to do anything other than transferring the inner code (innerHTML) from one to the other:

// Define old parent
var oldParent = document.getElementById('old-parent');

// Define new parent
var newParent = document.getElementById('new-parent');

// Basically takes the inner code of the old, and places it into the new one
newParent.innerHTML = oldParent.innerHTML;

// Delete / Clear the innerHTML / code of the old Parent
oldParent.innerHTML = '';

Hope this helps!

Foreign Key Django Model

You create the relationships the other way around; add foreign keys to the Person type to create a Many-to-One relationship:

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()
    anniversary = models.ForeignKey(
        Anniversary, on_delete=models.CASCADE)
    address = models.ForeignKey(
        Address, on_delete=models.CASCADE)

class Address(models.Model):
    line1 = models.CharField(max_length=150)
    line2 = models.CharField(max_length=150)
    postalcode = models.CharField(max_length=10)
    city = models.CharField(max_length=150)
    country = models.CharField(max_length=150)

class Anniversary(models.Model):
    date = models.DateField()

Any one person can only be connected to one address and one anniversary, but addresses and anniversaries can be referenced from multiple Person entries.

Anniversary and Address objects will be given a reverse, backwards relationship too; by default it'll be called person_set but you can configure a different name if you need to. See Following relationships "backward" in the queries documentation.

Configure nginx with multiple locations with different root folders on subdomain

server {

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

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

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

http://nginx.org/r/root

trying to align html button at the center of the my page

There are multiple ways to fix the same. PFB two of them -

1st Way using position: fixed - position: fixed; positions relative to the viewport, which means it always stays in the same place even if the page is scrolled. Adding the left and top value to 50% will place it into the middle of the screen.

 button {
   position: fixed;
   left: 50%;
   top:50%;
 }

2nd Way using margin: auto -margin: 0 auto; for horizontal centering, but margin: auto; has refused to work for vertical centering… until now! But actually absolute centering only requires a declared height and these styles:

button {
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  height: 40px;
}

Display two fields side by side in a Bootstrap Form

How about using an input group to style it on the same line?

Here's the final HTML to use:

<div class="input-group">
    <input type="text" class="form-control" placeholder="Start"/>
    <span class="input-group-addon">-</span>
    <input type="text" class="form-control" placeholder="End"/>
</div>

Which will look like this:

screenshot

Here's a Stack Snippet Demo:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="input-group">_x000D_
    <input type="text" class="form-control" placeholder="Start"/>_x000D_
    <span class="input-group-addon">-</span>_x000D_
    <input type="text" class="form-control" placeholder="End"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

I'll leave it as an exercise to the reader to translate it into an asp:textbox element

Create a new line in Java's FileWriter

If you want to get new line characters used in current OS like \r\n for Windows, you can get them by

  • System.getProperty("line.separator");
  • since Java7 System.lineSeparator()
  • or as mentioned by Stewart generate them via String.format("%n");

You can also use PrintStream and its println method which will add OS dependent line separator at the end of your string automatically

PrintStream fileStream = new PrintStream(new File("file.txt"));
fileStream.println("your data");
//         ^^^^^^^ will add OS line separator after data 

(BTW System.out is also instance of PrintStream).

Dynamically create checkbox with JQuery from text input

Put a global variable to generate the ids.

<script>
    $(function(){
        // Variable to get ids for the checkboxes
        var idCounter=1;
        $("#btn1").click(function(){
            var val = $("#txtAdd").val();
            $("#divContainer").append ( "<label for='chk_" + idCounter + "'>" + val + "</label><input id='chk_" + idCounter + "' type='checkbox' value='" + val + "' />" );
            idCounter ++;
        });
    });
</script>
<div id='divContainer'></div>
<input type="text" id="txtAdd" /> 
<button id="btn1">Click</button>

Best way to get user GPS location in background in Android

Well Create a class extending Service ,this service will contain your Location listener class(Fused Location Provider) purpose of this service is to get location periodically , something like this

  public class LocationGetter extends Service {


    ......

    public class MyLocationListener implements GooglePlayServicesClient.ConnectionCallbacks,GooglePlayServicesClient.OnConnectionFailedListener,LocationListener, com.google.android.gms.location.LocationListener {

   //your fused Location provider code

    }

    ......

}

Then create a class extending Broadcast Receiver , such that the purpose of this broadcast Receiver is to check whether service is alive if not restart service even during phone ON/OFF ....

register receiver in ur activity , listen for broadcasts , unregeister receiver depending ur need...

OpenSSL Command to check if a server is presenting a certificate

I encountered the write:errno=104 attempting to test connecting to an SSL-enabled RabbitMQ broker port with openssl s_client.

The issue turned out to be simply that the user RabbitMQ was running as did not have read permissions on the certificate file. There was little-to-no useful logging in RabbitMQ.

NSString property: copy or retain?

Copy should be used for NSString. If it's Mutable, then it gets copied. If it's not, then it just gets retained. Exactly the semantics that you want in an app (let the type do what's best).

using jquery $.ajax to call a PHP function

You may use my library that does that automatically, I've been improving it for the past 2 years http://phery-php-ajax.net

Phery::instance()->set(array(
   'phpfunction' => function($data){
      /* Do your thing */
      return PheryResponse::factory(); // do your dom manipulation, return JSON, etc
   }
))->process();

The javascript would be simple as

phery.remote('phpfunction');

You can pass all the dynamic javascript part to the server, with a query builder like chainable interface, and you may pass any type of data back to the PHP. For example, some functions that would take too much space in the javascript side, could be called in the server using this (in this example, mcrypt, that in javascript would be almost impossible to accomplish):

function mcrypt(variable, content, key){
  phery.remote('mcrypt_encrypt', {'var': variable, 'content': content, 'key':key || false});
}

//would use it like (you may keep the key on the server, safer, unless it's encrypted for the user)
window.variable = '';
mcrypt('variable', 'This must be encoded and put inside variable', 'my key');

and in the server

Phery::instance()->set(array(
  'mcrypt_encrypt' => function($data){
     $r = new PheryResponse;

     $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
     $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
     $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $data['key'] ? : 'my key', $data['content'], MCRYPT_MODE_ECB, $iv);
     return $r->set_var($data['variable'], $encrypted);
     // or call a callback with the data, $r->call($data['callback'], $encrypted);
  }
))->process();

Now the variable will have the encrypted data.

Node.js server that accepts POST requests

The following code shows how to read values from an HTML form. As @pimvdb said you need to use the request.on('data'...) to capture the contents of the body.

const http = require('http')

const server = http.createServer(function(request, response) {
  console.dir(request.param)

  if (request.method == 'POST') {
    console.log('POST')
    var body = ''
    request.on('data', function(data) {
      body += data
      console.log('Partial body: ' + body)
    })
    request.on('end', function() {
      console.log('Body: ' + body)
      response.writeHead(200, {'Content-Type': 'text/html'})
      response.end('post received')
    })
  } else {
    console.log('GET')
    var html = `
            <html>
                <body>
                    <form method="post" action="http://localhost:3000">Name: 
                        <input type="text" name="name" />
                        <input type="submit" value="Submit" />
                    </form>
                </body>
            </html>`
    response.writeHead(200, {'Content-Type': 'text/html'})
    response.end(html)
  }
})

const port = 3000
const host = '127.0.0.1'
server.listen(port, host)
console.log(`Listening at http://${host}:${port}`)


If you use something like Express.js and Bodyparser then it would look like this since Express will handle the request.body concatenation

var express = require('express')
var fs = require('fs')
var app = express()

app.use(express.bodyParser())

app.get('/', function(request, response) {
  console.log('GET /')
  var html = `
    <html>
        <body>
            <form method="post" action="http://localhost:3000">Name: 
                <input type="text" name="name" />
                <input type="submit" value="Submit" />
            </form>
        </body>
    </html>`
  response.writeHead(200, {'Content-Type': 'text/html'})
  response.end(html)
})

app.post('/', function(request, response) {
  console.log('POST /')
  console.dir(request.body)
  response.writeHead(200, {'Content-Type': 'text/html'})
  response.end('thanks')
})

port = 3000
app.listen(port)
console.log(`Listening at http://localhost:${port}`)

In Spring MVC, how can I set the mime type header when using @ResponseBody

I don't think you can, apart from response.setContentType(..)

How to make a class property?

Here's how I would do this:

class ClassPropertyDescriptor(object):

    def __init__(self, fget, fset=None):
        self.fget = fget
        self.fset = fset

    def __get__(self, obj, klass=None):
        if klass is None:
            klass = type(obj)
        return self.fget.__get__(obj, klass)()

    def __set__(self, obj, value):
        if not self.fset:
            raise AttributeError("can't set attribute")
        type_ = type(obj)
        return self.fset.__get__(obj, type_)(value)

    def setter(self, func):
        if not isinstance(func, (classmethod, staticmethod)):
            func = classmethod(func)
        self.fset = func
        return self

def classproperty(func):
    if not isinstance(func, (classmethod, staticmethod)):
        func = classmethod(func)

    return ClassPropertyDescriptor(func)


class Bar(object):

    _bar = 1

    @classproperty
    def bar(cls):
        return cls._bar

    @bar.setter
    def bar(cls, value):
        cls._bar = value


# test instance instantiation
foo = Bar()
assert foo.bar == 1

baz = Bar()
assert baz.bar == 1

# test static variable
baz.bar = 5
assert foo.bar == 5

# test setting variable on the class
Bar.bar = 50
assert baz.bar == 50
assert foo.bar == 50

The setter didn't work at the time we call Bar.bar, because we are calling TypeOfBar.bar.__set__, which is not Bar.bar.__set__.

Adding a metaclass definition solves this:

class ClassPropertyMetaClass(type):
    def __setattr__(self, key, value):
        if key in self.__dict__:
            obj = self.__dict__.get(key)
        if obj and type(obj) is ClassPropertyDescriptor:
            return obj.__set__(self, value)

        return super(ClassPropertyMetaClass, self).__setattr__(key, value)

# and update class define:
#     class Bar(object):
#        __metaclass__ = ClassPropertyMetaClass
#        _bar = 1

# and update ClassPropertyDescriptor.__set__
#    def __set__(self, obj, value):
#       if not self.fset:
#           raise AttributeError("can't set attribute")
#       if inspect.isclass(obj):
#           type_ = obj
#           obj = None
#       else:
#           type_ = type(obj)
#       return self.fset.__get__(obj, type_)(value)

Now all will be fine.

Align DIV to bottom of the page

It's a quick fix, I hope it helps.

<div id="content">
content...
</div>
<footer>
content footer...
</footer>

css:

#content{min-height: calc(100vh - 100px);}

100vh is 100% height of device and 100px is height of footer

If the content is higher than height of device, the footer will stay on bottom. And the content is shorter than height of device, the footer will stay on bottom of screen

Python executable not finding libpython shared library

On Solaris 11

Use LD_LIBRARY_PATH_64 to resolve symlink to python libs.

In my case for python3.6 LD_LIBRARY_PATH didn't work but LD_LIBRARY_PATH_64 did.

Hope this helps.
Regards

how to add a day to a date using jquery datepicker

This answer really helped me get started (noob) - but I encountered some weird behavior when I set a start date of 12/31/2014 and added +1 to default the end date. Instead of giving me an end date of 01/01/2015 I was getting 02/01/2015 (!!!). This version parses the components of the start date to avoid these end of year oddities.


 $( "#date_start" ).datepicker({

   minDate: 0,
   dateFormat: "mm/dd/yy",

   onSelect: function(selected) {
         $("#date_end").datepicker("option","minDate", selected); //  mindate on the End datepicker cannot be less than start date already selected.
         var date = $(this).datepicker('getDate');
         var tempStartDate = new Date(date);
         var default_end = new Date(tempStartDate.getFullYear(), tempStartDate.getMonth(), tempStartDate.getDate()+1); //this parses date to overcome new year date weirdness
         $('#date_end').datepicker('setDate', default_end); // Set as default                           
   }

 });

 $( "#date_end" ).datepicker({

   minDate: 0,
   dateFormat: "mm/dd/yy",

   onSelect: function(selected) {
     $("#date_start").datepicker("option","maxDate", selected); //  maxdate on the Start datepicker cannot be more than end date selected.

  }

});

How do I make a JSON object with multiple arrays?

Another example:

[  
[  
    {  
        "@id":1,
        "deviceId":1,
        "typeOfDevice":"1",
        "state":"1",
        "assigned":true
    },
    {  
        "@id":2,
        "deviceId":3,
        "typeOfDevice":"3",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":3,
        "deviceId":4,
        "typeOfDevice":"júuna",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":4,
        "deviceId":5,
        "typeOfDevice":"nffjnff",
        "state":"Regular",
        "assigned":true
    },
    {  
        "@id":5,
        "deviceId":6,
        "typeOfDevice":"44",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":6,
        "deviceId":7,
        "typeOfDevice":"rr",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":7,
        "deviceId":8,
        "typeOfDevice":"j",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":8,
        "deviceId":9,
        "typeOfDevice":"55",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":9,
        "deviceId":10,
        "typeOfDevice":"5",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":10,
        "deviceId":11,
        "typeOfDevice":"5",
        "state":"Excelent",
        "assigned":true
    }
],
1
]

Read the array's

$.each(data[0], function(i, item) {
         data[0][i].deviceId + data[0][i].typeOfDevice  + data[0][i].state +  data[0][i].assigned 
    });

Use http://www.jsoneditoronline.org/ to understand the JSON code better

MySQL Multiple Left Joins

To display the all details for each news post title ie. "news.id" which is the primary key, you need to use GROUP BY clause for "news.id"

SELECT news.id, users.username, news.title, news.date,
       news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id

Use of contains in Java ArrayList<String>

Yes, that should work for Strings, but if you are worried about duplicates use a Set. This collection prevents duplicates without you having to do anything. A HashSet is OK to use, but it is unordered so if you want to preserve insertion order you use a LinkedHashSet.

How to get character array from a string?

It already is:

_x000D_
_x000D_
var mystring = 'foobar';_x000D_
console.log(mystring[0]); // Outputs 'f'_x000D_
console.log(mystring[3]); // Outputs 'b'
_x000D_
_x000D_
_x000D_

Or for a more older browser friendly version, use:

_x000D_
_x000D_
var mystring = 'foobar';_x000D_
console.log(mystring.charAt(3)); // Outputs 'b'
_x000D_
_x000D_
_x000D_

"Cannot GET /" with Connect on Node.js

This code should work:

var connect = require("connect");

var app = connect.createServer().use(connect.static(__dirname + '/public'));

app.listen(8180);

Also in connect 2.0 .createServer() method deprecated. Use connect() instead.

var connect = require("connect");

var app = connect().use(connect.static(__dirname + '/public'));

app.listen(8180);

How to draw circle in html page?

There are a few unicode circles you could use:

_x000D_
_x000D_
* { font-size: 50px; }
_x000D_
&#x25CB;_x000D_
&#x25CC;_x000D_
&#x25CD;_x000D_
&#x25CE;_x000D_
&#x25CF;
_x000D_
_x000D_
_x000D_

More shapes here.

You can overlay text on the circles if you want to:

_x000D_
_x000D_
#container {_x000D_
    position: relative;_x000D_
}_x000D_
#circle {_x000D_
  font-size: 50px;_x000D_
  color: #58f;_x000D_
}_x000D_
#text {_x000D_
    z-index: 1;_x000D_
    position: absolute;_x000D_
    top: 21px;_x000D_
    left: 11px;_x000D_
}
_x000D_
<div id="container">_x000D_
    <div id="circle">&#x25CF;</div>_x000D_
    <div id="text">a</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You could also use a custom font (like this one) if you want to have a higher chance of it looking the same on different systems since not all computers/browsers have the same fonts installed.

How do I import a specific version of a package using go get?

go get is the Go package manager. It works in a completely decentralized way and how package discovery still possible without a central package hosting repository.

Besides locating and downloading packages, the other big role of a package manager is handling multiple versions of the same package. Go takes the most minimal and pragmatic approach of any package manager. There is no such thing as multiple versions of a Go package.

go get always pulls from the HEAD of the default branch in the repository. Always. This has two important implications:

  1. As a package author, you must adhere to the stable HEAD philosophy. Your default branch must always be the stable, released version of your package. You must do work in feature branches and only merge when ready to release.

  2. New major versions of your package must have their own repository. Put simply, each major version of your package (following semantic versioning) would have its own repository and thus its own import path.

    e.g. github.com/jpoehls/gophermail-v1 and github.com/jpoehls/gophermail-v2.

As someone building an application in Go, the above philosophy really doesn't have a downside. Every import path is a stable API. There are no version numbers to worry about. Awesome!

For more details : http://zduck.com/2014/go-and-package-versioning/

Drop rows containing empty cells from a pandas DataFrame

Pandas will recognise a value as null if it is a np.nan object, which will print as NaN in the DataFrame. Your missing values are probably empty strings, which Pandas doesn't recognise as null. To fix this, you can convert the empty stings (or whatever is in your empty cells) to np.nan objects using replace(), and then call dropna()on your DataFrame to delete rows with null tenants.

To demonstrate, we create a DataFrame with some random values and some empty strings in a Tenants column:

>>> import pandas as pd
>>> import numpy as np
>>> 
>>> df = pd.DataFrame(np.random.randn(10, 2), columns=list('AB'))
>>> df['Tenant'] = np.random.choice(['Babar', 'Rataxes', ''], 10)
>>> print df

          A         B   Tenant
0 -0.588412 -1.179306    Babar
1 -0.008562  0.725239         
2  0.282146  0.421721  Rataxes
3  0.627611 -0.661126    Babar
4  0.805304 -0.834214         
5 -0.514568  1.890647    Babar
6 -1.188436  0.294792  Rataxes
7  1.471766 -0.267807    Babar
8 -1.730745  1.358165  Rataxes
9  0.066946  0.375640         

Now we replace any empty strings in the Tenants column with np.nan objects, like so:

>>> df['Tenant'].replace('', np.nan, inplace=True)
>>> print df

          A         B   Tenant
0 -0.588412 -1.179306    Babar
1 -0.008562  0.725239      NaN
2  0.282146  0.421721  Rataxes
3  0.627611 -0.661126    Babar
4  0.805304 -0.834214      NaN
5 -0.514568  1.890647    Babar
6 -1.188436  0.294792  Rataxes
7  1.471766 -0.267807    Babar
8 -1.730745  1.358165  Rataxes
9  0.066946  0.375640      NaN

Now we can drop the null values:

>>> df.dropna(subset=['Tenant'], inplace=True)
>>> print df

          A         B   Tenant
0 -0.588412 -1.179306    Babar
2  0.282146  0.421721  Rataxes
3  0.627611 -0.661126    Babar
5 -0.514568  1.890647    Babar
6 -1.188436  0.294792  Rataxes
7  1.471766 -0.267807    Babar
8 -1.730745  1.358165  Rataxes

Configure Log4Net in web application

I also had the similar issue. Logs were not creating.

Please check logger attribute name should match with your LogManager.GetLogger("name")

<logger name="Mylog">
      <level value="All"></level>
      <appender-ref ref="RollingLogFileAppender" />
    </logger>



private static readonly ILog Log = LogManager.GetLogger("Mylog");

How to Compare a long value is equal to Long value

First your code is not compiled. Line Long b = 1113;

is wrong. You have to say

Long b = 1113L;

Second when I fixed this compilation problem the code printed "not equals".

Pandas percentage of total with groupby

One-line solution:

df.join(
    df.groupby('state').agg(state_total=('sales', 'sum')),
    on='state'
).eval('sales / state_total')

This returns a Series of per-office ratios -- can be used on it's own or assigned to the original Dataframe.

Generating a WSDL from an XSD file

Personally (and given what I know, i.e., Java and axis), I'd generate a Java data model from the .xsd files (Axis 2 can do this), and then add an interface to describe my web service that uses that model, and then generate a WSDL from that interface.

Because .NET has all these features as well, it must be possible to do all this in that ecosystem as well.

SQL UPDATE with sub-query that references the same table in MySQL

Some reference for you http://dev.mysql.com/doc/refman/5.0/en/update.html

UPDATE user_account student 
INNER JOIN user_account teacher ON
   teacher.user_account_id = student.teacher_id 
   AND teacher.user_type = 'ROLE_TEACHER'
SET student.student_education_facility_id = teacher.education_facility_id

fetch from origin with deleted remote branches?

You need to do the following

git fetch -p

This will update the local database of remote branches.

Function to Calculate Median in SQL Server

For a continuous variable/measure 'col1' from 'table1'

select col1  
from
    (select top 50 percent col1, 
    ROW_NUMBER() OVER(ORDER BY col1 ASC) AS Rowa,
    ROW_NUMBER() OVER(ORDER BY col1 DESC) AS Rowd
    from table1 ) tmp
where tmp.Rowa = tmp.Rowd

initializing a boolean array in java

I just need to initialize all the array elements to Boolean false.

Either use boolean[] instead so that all values defaults to false:

boolean[] array = new boolean[size];

Or use Arrays#fill() to fill the entire array with Boolean.FALSE:

Boolean[] array = new Boolean[size];
Arrays.fill(array, Boolean.FALSE);

Also note that the array index is zero based. The freq[Global.iParameter[2]] = false; line as you've there would cause ArrayIndexOutOfBoundsException. To learn more about arrays in Java, consult this basic Oracle tutorial.

Verify External Script Is Loaded

Another way to check an external script is loaded or not, you can use data function of jquery and store a validation flag. Example as :

if(!$("body").data("google-map"))
    {
        console.log("no js");

        $.getScript("https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initilize",function(){
            $("body").data("google-map",true);

            },function(){
                alert("error while loading script");
            });
        }
    }
    else
    {
        console.log("js already loaded");
    }

How to assert greater than using JUnit Assert?

As I recognize, at the moment, in JUnit, the syntax is like this:

AssertTrue(Long.parseLong(previousTokenValues[1]) > Long.parseLong(currentTokenValues[1]), "your fail message ");

Means that, the condition is in front of the message.

How to create id with AUTO_INCREMENT on Oracle?

it is called Identity Columns and it is available only from oracle Oracle 12c

CREATE TABLE identity_test_tab
(
   id            NUMBER GENERATED ALWAYS AS IDENTITY,
   description   VARCHAR2 (30)
);

example of insert into Identity Columns as below

INSERT INTO identity_test_tab (description) VALUES ('Just DESCRIPTION');

1 row created.

you can NOT do insert like below

INSERT INTO identity_test_tab (id, description) VALUES (NULL, 'ID=NULL and DESCRIPTION');

ERROR at line 1: ORA-32795: cannot insert into a generated always identity column

INSERT INTO identity_test_tab (id, description) VALUES (999, 'ID=999 and DESCRIPTION');

ERROR at line 1: ORA-32795: cannot insert into a generated always identity column

useful link

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

I have faced the same issue and I was unable to start the postgresql server and was unable to access my db even after giving password, and I have been doing all the possible ways.

This solution worked for me,

For the Ubuntu users: Through command line, type the following commands:

1.service --status-all (which gives list of all services and their status. where "+" refers to running and "-" refers that the service is no longer running)

check for postgresql status, if its "-" then type the following command

2.systemctl start postgresql (starts the server again)

refresh the postgresql page in browser, and it works

For the Windows users:

Search for services, where we can see list of services and the right click on postgresql, click on start and server works perfectly fine.

Merge or combine by rownames

Using merge and renaming your t vector as tt (see the PS of Andrie) :

merge(tt,z,by="row.names",all.x=TRUE)[,-(5:8)]

Now if you would work with dataframes instead of matrices, this would even become a whole lot easier :

z <- as.data.frame(z)
tt <- as.data.frame(tt)
merge(tt,z["symbol"],by="row.names",all.x=TRUE)

Batch command date and time in file name

As others have already pointed out, the date and time formats of %DATE% and %TIME% (as well as date /T and time /T) are locale-dependent, so extracting the current date and time is always a nightmare, and it is impossible to get a solution that works with all possible formats since there are hardly any format limitations.


But there is another problem with a code like the following one (let us assume a date format like MM/DD/YYYY and a 12 h time format like h:mm:ss.ff ap where ap is either AM or PM and ff are fractional seconds):

rem // Resolve AM/PM time:
set "HOUR=%TIME:~,2%"
if "%TIME:~-2%" == "PM" if %HOUR% lss 12 set /A "HOUR+=12"
if "%TIME:~-2%" == "AM" if %HOUR% equ 12 set /A "HOUR-=12"
rem // Left-zero-pad hour:
set "HOUR=0%HOUR%"
rem // Build and display date/time string:
echo %DATE:~-4,4%%DATE:~0,2%%DATE:~3,2%_%HOUR:~-2%%TIME:~3,2%%TIME:~6,2%

Each instance of %DATE% and %TIME% returns the date or time value present at the time of its expansion, therefore the first %DATE% or %TIME% expression might return a different value than the following ones (you can prove that when echoing a long string containing a huge amount of such, preferrably %TIME%, expressions).

You could improve the aforementioned code to hold a single instance of %DATE% and %TIME% like this:

rem // Store current date and time once in the same line:
set "CURRDATE=%DATE%" & set "CURRTIME=%TIME%"
rem // Resolve AM/PM time:
set "HOUR=%CURRTIME:~,2%"
if "%CURRTIME:~-2%" == "PM" if %HOUR% lss 12 set /A "HOUR+=12"
if "%CURRTIME:~-2%" == "AM" if %HOUR% equ 12 set /A "HOUR-=12"
rem // Left-zero-pad hour:
set "HOUR=0%HOUR%"
rem // Build and display date/time string:
echo %CURRDATE:~-4,4%%CURRDATE:~0,2%%CURRDATE:~3,2%_%HOUR:~-2%%CURRTIME:~3,2%%CURRTIME:~6,2%

But still, the returned values in %DATE% and %TIME% could reflect different days when executed at midnight.

The only way to have the same day in %CURRDATE% and %CURRTIME% is this:

rem // Store current date and time once in the same line:
set "CURRDATE=%DATE%" & set "CURRTIME=%TIME%"
rem // Resolve AM/PM time:
set "HOUR=%CURRTIME:~,2%"
if "%CURRTIME:~-2%" == "PM" if %HOUR% lss 12 set /A "HOUR+=12"
if "%CURRTIME:~-2%" == "AM" if %HOUR% equ 12 set /A "HOUR-=12"
rem // Fix date/time midnight discrepancy:
if not "%CURRDATE%" == "%DATE%" if %CURRTIME:~0,2% equ 0 set "CURRDATE=%DATE%"
rem // Left-zero-pad hour:
set "HOUR=0%HOUR%"
rem // Build and display date/time string:
echo %CURRDATE:~-4,4%%CURRDATE:~0,2%%CURRDATE:~3,2%_%HOUR:~-2%%CURRTIME:~3,2%%CURRTIME:~6,2%

Of course the occurrence of the described problem is quite improbable, but at one point it will happen and cause strange unexplainable failures.


The described problem cannot occur with the approaches based on the wmic command as described in the answer by user Stephan and in the answer by user PA., so I strongly recommend to go for one of them. The only disadvantage of wmic is that it is way slower.

Using CRON jobs to visit url?

you can use this for url with parameters:

lynx -dump "http://vps-managed.com/tasks.php?code=23456"

lynx is available on all systems by default.

Setting default values for columns in JPA

@Column(columnDefinition="tinyint(1) default 1")

I just tested the issue. It works just fine. Thanks for the hint.


About the comments:

@Column(name="price") 
private double price = 0.0;

This one doesn't set the default column value in the database (of course).

How do I format a Microsoft JSON date?

In jQuery 1.5, as long as you have json2.js to cover for older browsers, you can deserialize all dates coming from Ajax as follows:

(function () {
    var DATE_START = "/Date(";
    var DATE_START_LENGTH = DATE_START.length;

    function isDateString(x) {
        return typeof x === "string" && x.startsWith(DATE_START);
    }

    function deserializeDateString(dateString) {
        var dateOffsetByLocalTime = new Date(parseInt(dateString.substr(DATE_START_LENGTH)));
        var utcDate = new Date(dateOffsetByLocalTime.getTime() - dateOffsetByLocalTime.getTimezoneOffset() * 60 * 1000);
        return utcDate;
    }

    function convertJSONDates(key, value) {
      if (isDateString(value)) {
        return deserializeDateString(value);
      }
      return value;
    }

    window.jQuery.ajaxSetup({
      converters: {
        "text json": function(data) {
          return window.JSON.parse(data, convertJSONDates);
        }
      }
    });
}());

I included logic that assumes you send all dates from the server as UTC (which you should); the consumer then gets a JavaScript Date object that has the proper ticks value to reflect this. That is, calling getUTCHours(), etc. on the date will return the same value as it did on the server, and calling getHours() will return the value in the user's local timezone as determined by their browser.

This does not take into account WCF format with timezone offsets, though that would be relatively easy to add.

Most efficient way to prepend a value to an array

If you would like to prepend array (a1 with an array a2) you could use the following:

var a1 = [1, 2];
var a2 = [3, 4];
Array.prototype.unshift.apply(a1, a2);
console.log(a1);
// => [3, 4, 1, 2]

Using Linq to get the last N elements of a collection?

Here's my solution:

public static class EnumerationExtensions
{
    public static IEnumerable<T> TakeLast<T>(this IEnumerable<T> input, int count)
    {
        if (count <= 0)
            yield break;

        var inputList = input as IList<T>;

        if (inputList != null)
        {
            int last = inputList.Count;
            int first = last - count;

            if (first < 0)
                first = 0;

            for (int i = first; i < last; i++)
                yield return inputList[i];
        }
        else
        {
            // Use a ring buffer. We have to enumerate the input, and we don't know in advance how many elements it will contain.
            T[] buffer = new T[count];

            int index = 0;

            count = 0;

            foreach (T item in input)
            {
                buffer[index] = item;

                index = (index + 1) % buffer.Length;
                count++;
            }

            // The index variable now points at the next buffer entry that would be filled. If the buffer isn't completely
            // full, then there are 'count' elements preceding index. If the buffer *is* full, then index is pointing at
            // the oldest entry, which is the first one to return.
            //
            // If the buffer isn't full, which means that the enumeration has fewer than 'count' elements, we'll fix up
            // 'index' to point at the first entry to return. That's easy to do; if the buffer isn't full, then the oldest
            // entry is the first one. :-)
            //
            // We'll also set 'count' to the number of elements to be returned. It only needs adjustment if we've wrapped
            // past the end of the buffer and have enumerated more than the original count value.

            if (count < buffer.Length)
                index = 0;
            else
                count = buffer.Length;

            // Return the values in the correct order.
            while (count > 0)
            {
                yield return buffer[index];

                index = (index + 1) % buffer.Length;
                count--;
            }
        }
    }

    public static IEnumerable<T> SkipLast<T>(this IEnumerable<T> input, int count)
    {
        if (count <= 0)
            return input;
        else
            return input.SkipLastIter(count);
    }

    private static IEnumerable<T> SkipLastIter<T>(this IEnumerable<T> input, int count)
    {
        var inputList = input as IList<T>;

        if (inputList != null)
        {
            int first = 0;
            int last = inputList.Count - count;

            if (last < 0)
                last = 0;

            for (int i = first; i < last; i++)
                yield return inputList[i];
        }
        else
        {
            // Aim to leave 'count' items in the queue. If the input has fewer than 'count'
            // items, then the queue won't ever fill and we return nothing.

            Queue<T> elements = new Queue<T>();

            foreach (T item in input)
            {
                elements.Enqueue(item);

                if (elements.Count > count)
                    yield return elements.Dequeue();
            }
        }
    }
}

The code is a bit chunky, but as a drop-in reusable component, it should perform as well as it can in most scenarios, and it'll keep the code that's using it nice and concise. :-)

My TakeLast for non-IList`1 is based on the same ring buffer algorithm as that in the answers by @Mark Byers and @MackieChan further up. It's interesting how similar they are -- I wrote mine completely independently. Guess there's really just one way to do a ring buffer properly. :-)

Looking at @kbrimington's answer, an additional check could be added to this for IQuerable<T> to fall back to the approach that works well with Entity Framework -- assuming that what I have at this point does not.

Loading a properties file from Java package

The following two cases relate to loading a properties file from an example class named TestLoadProperties.

Case 1: Loading the properties file using ClassLoader

InputStream inputStream = TestLoadProperties.class.getClassLoader()
                          .getResourceAsStream("A.config");
properties.load(inputStream);

In this case the properties file must be in the root/src directory for successful loading.

Case 2: Loading the properties file without using ClassLoader

InputStream inputStream = getClass().getResourceAsStream("A.config");
properties.load(inputStream);

In this case the properties file must be in the same directory as the TestLoadProperties.class file for successful loading.

Note: TestLoadProperties.java and TestLoadProperties.class are two different files. The former, .java file, is usually found in a project's src/ directory, while the latter, .class file, is usually found in its bin/ directory.

How do I rename the android package name?

Solution 1: I changed src subfolder names, manifest file, activity headers and run/debug configuration. And still got building errors. If your project is not so big, just create a new project, copy-paste old files and change package names in headers of .java files and android manifest.

Solution 2: Inside IntelliJ 12, goto someFile.java and find your old package name

package com.myself.project2

click to which word that you want to change. Press Shift+F6.
Dialog comes, type new name.

Then goto Run/Edit configurations. Inside Launch radio button change package name to new one. It should work.

Other renaming options of IntelliJ are: http://www.jetbrains.com/idea/webhelp/rename-refactorings.html

Script for rebuilding and reindexing the fragmented index?

Two solutions: One simple and one more advanced.

Introduction

There are two solutions available to you depending on the severity of your issue

Replace with your own values, as follows:

  • Replace XXXMYINDEXXXX with the name of an index.
  • Replace XXXMYTABLEXXX with the name of a table.
  • Replace XXXDATABASENAMEXXX with the name of a database.

Solution 1. Indexing

Rebuild all indexes for a table in offline mode

ALTER INDEX ALL ON XXXMYTABLEXXX REBUILD

Rebuild one specified index for a table in offline mode

ALTER INDEX XXXMYINDEXXXX ON XXXMYTABLEXXX REBUILD

Solution 2. Fragmentation

Fragmentation is an issue in tables that regularly have entries both added and removed.

Check fragmentation percentage

SELECT  
    ips.[index_id] ,
    idx.[name] ,
    ips.[avg_fragmentation_in_percent]
FROM    
    sys.dm_db_index_physical_stats(DB_ID(N'XXXMYDATABASEXXX'), OBJECT_ID(N'XXXMYTABLEXXX'), NULL, NULL, NULL) AS [ips]
    INNER JOIN sys.indexes AS [idx] ON [ips].[object_id] = [idx].[object_id] AND [ips].[index_id] = [idx].[index_id]

Fragmentation 5..30%

If the fragmentation value is greater than 5%, but less than 30% then it is worth reorganising indexes.

Reorganise all indexes for a table

ALTER INDEX ALL ON XXXMYTABLEXXX REORGANIZE

Reorganise one specified index for a table

ALTER INDEX XXXMYINDEXXXX ON XXXMYTABLEXXX REORGANIZE

Fragmentation 30%+

If the fragmentation value is 30% or greater then it is worth rebuilding then indexes in online mode.

Rebuild all indexes in online mode for a table

ALTER INDEX ALL ON XXXMYTABLEXXX REBUILD WITH (ONLINE = ON)

Rebuild one specified index in online mode for a table

ALTER INDEX XXXMYINDEXXXX ON XXXMYTABLEXXX REBUILD WITH (ONLINE = ON)

What happens to C# Dictionary<int, int> lookup if the key does not exist?

You should probably use:

if(myDictionary.ContainsKey(someInt))
{
  // do something
}

The reason why you can't check for null is that the key here is a value type.

How to get Toolbar from fragment?

For Kotlin users (activity as AppCompatActivity).supportActionBar?.show()

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

Regarding the Hibernate validator documentation page, you have to define a dependency to a JSR-341 implementation:

<dependency>
   <groupId>org.glassfish</groupId>
   <artifactId>javax.el</artifactId>
   <version>3.0.1-b11</version>
</dependency>

HTML form action and onsubmit issues

You should stop the submit procedure by returning false on the onsubmit callback.

<script>
    function checkRegistration(){
        if(!form_valid){
            alert('Given data is not correct');
            return false;
        }
        return true;
    }
</script>

<form onsubmit="return checkRegistration()"...

Here you have a fully working example. The form will submit only when you write google into input, otherwise it will return an error:

<script>
    function checkRegistration(){
        var form_valid = (document.getElementById('some_input').value == 'google');
        if(!form_valid){
            alert('Given data is incorrect');
            return false;
        }
        return true;
    }
</script>

<form onsubmit="return checkRegistration()" method="get" action="http://google.com">
    Write google to go to google...<br/>
    <input type="text" id="some_input" value=""/>
    <input type="submit" value="google it"/>
</form>

Entity Framework code first unique column

From your code it becomes apparent that you use POCO. Having another key is unnecessary: you can add an index as suggested by juFo.
If you use Fluent API instead of attributing UserName property your column annotation should look like this:

this.Property(p => p.UserName)
    .HasColumnAnnotation("Index", new IndexAnnotation(new[] { 
        new IndexAttribute("Index") { IsUnique = true } 
    }
));

This will create the following SQL script:

CREATE UNIQUE NONCLUSTERED INDEX [Index] ON [dbo].[Users]
(
    [UserName] ASC
)
WITH (
    PAD_INDEX = OFF, 
    STATISTICS_NORECOMPUTE = OFF, 
    SORT_IN_TEMPDB = OFF, 
    IGNORE_DUP_KEY = OFF, 
    DROP_EXISTING = OFF, 
    ONLINE = OFF, 
    ALLOW_ROW_LOCKS = ON, 
    ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]

If you attempt to insert multiple Users having the same UserName you'll get a DbUpdateException with the following message:

Cannot insert duplicate key row in object 'dbo.Users' with unique index 'Index'. 
The duplicate key value is (...).
The statement has been terminated.

Again, column annotations are not available in Entity Framework prior to version 6.1.

Check if an array contains duplicate values

An easy solution, if you've got ES6, uses Set:

_x000D_
_x000D_
function checkIfArrayIsUnique(myArray) {_x000D_
  return myArray.length === new Set(myArray).size;_x000D_
}_x000D_
_x000D_
let uniqueArray = [1, 2, 3, 4, 5];_x000D_
console.log(`${uniqueArray} is unique : ${checkIfArrayIsUnique(uniqueArray)}`);_x000D_
_x000D_
let nonUniqueArray = [1, 1, 2, 3, 4, 5];_x000D_
console.log(`${nonUniqueArray} is unique : ${checkIfArrayIsUnique(nonUniqueArray)}`);
_x000D_
_x000D_
_x000D_

How do I create a singleton service in Angular 2?

Syntax has been changed. Check this link

Dependencies are singletons within the scope of an injector. In below example, a single HeroService instance is shared among the HeroesComponent and its HeroListComponent children.

Step 1. Create singleton class with @Injectable decorator

@Injectable()
export class HeroService {
  getHeroes() { return HEROES;  }
}

Step 2. Inject in constructor

export class HeroListComponent { 
  constructor(heroService: HeroService) {
    this.heroes = heroService.getHeroes();
  }

Step 3. Register provider

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    routing,
    HttpModule,
    JsonpModule
  ],
  declarations: [
    AppComponent,
    HeroesComponent,
    routedComponents
  ],
  providers: [
    HeroService
  ],
  bootstrap: [
    AppComponent
  ]
})
export class AppModule { }

How to set a reminder in Android?

Nope, it is more complicated than just calling a method, if you want to transparently add it into the user's calendar.

You've got a couple of choices;

  1. Calling the intent to add an event on the calendar
    This will pop up the Calendar application and let the user add the event. You can pass some parameters to prepopulate fields:

    Calendar cal = Calendar.getInstance();              
    Intent intent = new Intent(Intent.ACTION_EDIT);
    intent.setType("vnd.android.cursor.item/event");
    intent.putExtra("beginTime", cal.getTimeInMillis());
    intent.putExtra("allDay", false);
    intent.putExtra("rrule", "FREQ=DAILY");
    intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
    intent.putExtra("title", "A Test Event from android app");
    startActivity(intent);
    

    Or the more complicated one:

  2. Get a reference to the calendar with this method
    (It is highly recommended not to use this method, because it could break on newer Android versions):

    private String getCalendarUriBase(Activity act) {
    
        String calendarUriBase = null;
        Uri calendars = Uri.parse("content://calendar/calendars");
        Cursor managedCursor = null;
        try {
            managedCursor = act.managedQuery(calendars, null, null, null, null);
        } catch (Exception e) {
        }
        if (managedCursor != null) {
            calendarUriBase = "content://calendar/";
        } else {
            calendars = Uri.parse("content://com.android.calendar/calendars");
            try {
                managedCursor = act.managedQuery(calendars, null, null, null, null);
            } catch (Exception e) {
            }
            if (managedCursor != null) {
                calendarUriBase = "content://com.android.calendar/";
            }
        }
        return calendarUriBase;
    }
    

    and add an event and a reminder this way:

    // get calendar
    Calendar cal = Calendar.getInstance();     
    Uri EVENTS_URI = Uri.parse(getCalendarUriBase(this) + "events");
    ContentResolver cr = getContentResolver();
    
    // event insert
    ContentValues values = new ContentValues();
    values.put("calendar_id", 1);
    values.put("title", "Reminder Title");
    values.put("allDay", 0);
    values.put("dtstart", cal.getTimeInMillis() + 11*60*1000); // event starts at 11 minutes from now
    values.put("dtend", cal.getTimeInMillis()+60*60*1000); // ends 60 minutes from now
    values.put("description", "Reminder description");
    values.put("visibility", 0);
    values.put("hasAlarm", 1);
    Uri event = cr.insert(EVENTS_URI, values);
    
    // reminder insert
    Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(this) + "reminders");
    values = new ContentValues();
    values.put( "event_id", Long.parseLong(event.getLastPathSegment()));
    values.put( "method", 1 );
    values.put( "minutes", 10 );
    cr.insert( REMINDERS_URI, values );
    

    You'll also need to add these permissions to your manifest for this method:

    <uses-permission android:name="android.permission.READ_CALENDAR" />
    <uses-permission android:name="android.permission.WRITE_CALENDAR" />
    

Update: ICS Issues

The above examples use the undocumented Calendar APIs, new public Calendar APIs have been released for ICS, so for this reason, to target new android versions you should use CalendarContract.

More infos about this can be found at this blog post.

Display / print all rows of a tibble (tbl_df)

you can print it in Rstudio with View() more convenient:

df %>% View()

View(df)

Find an element in a list of tuples

if you want to search tuple for any number which is present in tuple then you can use

a= [(1,2),(1,4),(3,5),(5,7)]
i=1
result=[]
for j in a:
    if i in j:
        result.append(j)

print(result)

You can also use if i==j[0] or i==j[index] if you want to search a number in particular index

Find length (size) of an array in jquery

If length is undefined you can use:

function count(array){

    var c = 0;
    for(i in array) // in returns key, not object
        if(array[i] != undefined)
            c++;

    return c;
}

var total = count(array);

How to include a quote in a raw Python string

Python has more than one way to do strings. The following string syntax would allow you to use double quotes:

'''what"ever'''

Cannot get OpenCV to compile because of undefined references?

For me, this type of error:

mingw-w64-x86_64/lib/gcc/x86_64-w64-mingw32/8.2.0/../../../../x86_64-w64-mingw32/bin/ld: mingw-w64-x86_64/x86_64-w64-mingw32/lib/libTransform360.a(VideoFrameTransform.cpp.obj):VideoFrameTransform.cpp:(.text+0xc7c):
undefined reference to `cv::Mat::Mat(cv::Mat const&, cv::Rect_<int> const&)'

meant load order, I had to do -lTransform360 -lopencv_dnn345 -lopencv... just like that, that order. And putting them right next to each other helped too, don't put -lTransform360 all the way at the beginning...or you'll get, for some freaky reason:

undefined reference to `VideoFrameTransform_new'
undefined reference to `VideoFrameTransform_generateMapForPlane'

...

Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error

To those would prefer to keep it simple, stupid; If you rather get rid of the notices instead of installing a helper or downgrading, simply disable the error in your settings.json by adding this:

"intelephense.diagnostics.undefinedTypes": false

java: use StringBuilder to insert at the beginning

you can use strbuilder.insert(0,i);

SQL Query to fetch data from the last 30 days?

Try this : Using this you can select data from last 30 days

SELECT
    *
FROM
    product
WHERE
    purchase_date > DATE_SUB(CURDATE(), INTERVAL 1 MONTH)

Search in lists of lists by given index

I was searching for a deep find for dictionaries and didn't find one. Based on this article I was able to create the following. Thanks and Enjoy!!

def deapFind( theList, key, value ):
    result = False
    for x in theList:
        if( value == x[key] ):
            return True
    return result

theList = [{ "n": "aaa", "d": "bbb" }, { "n": "ccc", "d": "ddd" }]
print 'Result: ' + str (deapFind( theList, 'n', 'aaa'))

I'm using == instead of the in operator since in returns true for partial matches. IOW: searching aa on the n key returns true. I don't think that would be desired.

HTH

Executing <script> elements inserted with .innerHTML

Try function eval().

data.newScript = '<script type="text/javascript">//my script...</script>'
var element = document.getElementById('elementToRefresh');
element.innerHTML = data.newScript;
eval(element.firstChild.innerHTML);

This is a real example from a project that i am developing. Thanks to this post

How to stop creating .DS_Store on Mac?

Its is possible by using mach_inject. Take a look at Death to .DS_Store

I found that overriding HFSPlusPropertyStore::FlushChanges() with a function that simply did nothing, successfully prevented the creation of .DS_Store files on both Snow Leopard and Lion.

DeathToDSStore source code

NOTE: On 10.11 you can not inject code into system apps.

Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found

If anyone else stuck on same point, following solved my problem.

In web.xml

 <listener>
            <listener-class>
                    org.springframework.web.context.request.RequestContextListener 
            </listener-class>
  </listener>

In Session component

@Component
@Scope(value = "session",  proxyMode = ScopedProxyMode.TARGET_CLASS)

In pom.xml

    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>3.1</version>
    </dependency>

Reorder HTML table rows using drag-and-drop

Apparently the question poorly describes the OP's problem, but this question is the top search result for dragging to reorder table rows, so that is what I will answer. I wasn't interested in bringing in jQuery UI for something so simple, so here is a jQuery only solution:

_x000D_
_x000D_
$(".grab").mousedown(function(e) {
  var tr = $(e.target).closest("TR"),
    si = tr.index(),
    sy = e.pageY,
    b = $(document.body),
    drag;
  if (si == 0) return;
  b.addClass("grabCursor").css("userSelect", "none");
  tr.addClass("grabbed");

  function move(e) {
    if (!drag && Math.abs(e.pageY - sy) < 10) return;
    drag = true;
    tr.siblings().each(function() {
      var s = $(this),
        i = s.index(),
        y = s.offset().top;
      if (i > 0 && e.pageY >= y && e.pageY < y + s.outerHeight()) {
        if (i < tr.index())
          tr.insertAfter(s);
        else
          tr.insertBefore(s);
        return false;
      }
    });
  }

  function up(e) {
    if (drag && si != tr.index()) {
      drag = false;
      alert("moved!");
    }
    $(document).unbind("mousemove", move).unbind("mouseup", up);
    b.removeClass("grabCursor").css("userSelect", "none");
    tr.removeClass("grabbed");
  }
  $(document).mousemove(move).mouseup(up);
});
_x000D_
.grab {
  cursor: grab;
}

.grabbed {
  box-shadow: 0 0 13px #000;
}

.grabCursor,
.grabCursor * {
  cursor: grabbing !important;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <th></th>
    <th>Table Header</th>
  </tr>
  <tr>
    <td class="grab">&#9776;</td>
    <td>Table Cell 1</td>
  </tr>
  <tr>
    <td class="grab">&#9776;</td>
    <td>Table Cell 2</td>
  </tr>
  <tr>
    <td class="grab">&#9776;</td>
    <td>Table Cell 3</td>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

Note si == 0 and i > 0 ignores the first row, which for me contains TH tags. Replace the alert with your "drag finished" logic.

Laravel Fluent Query Builder Join with subquery

I can't comment because my reputation is not high enough. @Franklin Rivero if you are using Laravel 5.2 you can set the bindings on the main query instead of the join using the setBindings method.

So the main query in @ph4r05's answer would look something like this:

$q = DnsResult::query()
    ->from($dnsTable . ' AS s')
    ->join(
        DB::raw('(' . $qqSql. ') AS ss'),
        function(JoinClause $join) {
            $join->on('s.watch_id', '=', 'ss.watch_id')
                 ->on('s.last_scan_at', '=', 'ss.last_scan');
        })
    ->setBindings($subq->getBindings());

Proper way to exit iPhone application?

Go to your info.plist and check the key "Application does not run in background". This time when the user clicks the home button, the application exits completely.

How to pass a type as a method parameter in Java

If you want to pass the type, than the equivalent in Java would be

java.lang.Class

If you want to use a weakly typed method, then you would simply use

java.lang.Object

and the corresponding operator

instanceof

e.g.

private void foo(Object o) {

  if(o instanceof String) {

  }

}//foo

However, in Java there are primitive types, which are not classes (i.e. int from your example), so you need to be careful.

The real question is what you actually want to achieve here, otherwise it is difficult to answer:

Or is there a better way?

Flutter command not found

Add Path in this way in .bashrc for Linux and for Mac .bash_profile of android sdk and tools with flutter

export PATH=$PATH:/user/Android/Sdk/platform-tools:/user/Android/Sdk/build-tools/27.0.1:/user/Android/Sdk/tools:/user/Android/Sdk/tools/bin:/user/Documents/fluterdev/flutter/bin:$PATH

Then run this command

On Linux

source ~/.profile

On Mac

source ~/.bash_profile or open -a TextEdit ~/.bash_profile

enter image description here

Then you can user any of flutter command like to build fluter apk

flutter build apk

Java error: Comparison method violates its general contract

I got the same error with a class like the following StockPickBean. Called from this code:

List<StockPickBean> beansListcatMap.getValue();
beansList.sort(StockPickBean.Comparators.VALUE);

public class StockPickBean implements Comparable<StockPickBean> {
    private double value;
    public double getValue() { return value; }
    public void setValue(double value) { this.value = value; }

    @Override
    public int compareTo(StockPickBean view) {
        return Comparators.VALUE.compare(this,view); //return 
        Comparators.SYMBOL.compare(this,view);
    }

    public static class Comparators {
        public static Comparator<StockPickBean> VALUE = (val1, val2) -> 
(int) 
         (val1.value - val2.value);
    }
}

After getting the same error:

java.lang.IllegalArgumentException: Comparison method violates its general contract!

I changed this line:

public static Comparator<StockPickBean> VALUE = (val1, val2) -> (int) 
         (val1.value - val2.value);

to:

public static Comparator<StockPickBean> VALUE = (StockPickBean spb1, 
StockPickBean spb2) -> Double.compare(spb2.value,spb1.value);

That fixes the error.

How to find the day, month and year with moment.js

Just try with:

var check = moment(n.entry.date_entered, 'YYYY/MM/DD');

var month = check.format('M');
var day   = check.format('D');
var year  = check.format('YYYY');

JSFiddle

Rails formatting date

Create an initializer for it:

# config/initializers/time_formats.rb

Add something like this to it:

Time::DATE_FORMATS[:custom_datetime] = "%d.%m.%Y"

And then use it the following way:

post.updated_at.to_s(:custom_datetime)

?? Your have to restart rails server for this to work.

Check the documentation for more information: http://api.rubyonrails.org/v5.1/classes/DateTime.html#method-i-to_formatted_s

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

Since the question was "display" :

@Html.ValueFor(model => model.RegistrationDate, "{0:dd/MM/yyyy}")

python request with authentication (access_token)

The requests package has a very nice API for HTTP requests, adding a custom header works like this (source: official docs):

>>> import requests
>>> response = requests.get(
... 'https://website.com/id', headers={'Authorization': 'access_token myToken'})

If you don't want to use an external dependency, the same thing using urllib2 of the standard library looks like this (source: the missing manual):

>>> import urllib2
>>> response = urllib2.urlopen(
... urllib2.Request('https://website.com/id', headers={'Authorization': 'access_token myToken'})

How to select multiple files with <input type="file">?

There is also HTML5 <input type="file[]" multiple /> (specification).

Browser support is quite good on desktop (just not supported by IE 9 and prior), less good on mobile, I guess because it's harder to implement correctly depending on the platform and version.

Resizing SVG in html?

Use the following code:

<g transform="scale(0.1)">
...
</g>

How to set default values in Go structs

One possible idea is to write separate constructor function

//Something is the structure we work with
type Something struct {
     Text string 
     DefaultText string 
} 
// NewSomething create new instance of Something
func NewSomething(text string) Something {
   something := Something{}
   something.Text = text
   something.DefaultText = "default text"
   return something
}

Matplotlib tight_layout() doesn't take into account figure suptitle

Tight layout doesn't work with suptitle, but constrained_layout does. See this question Improve subplot size/spacing with many subplots in matplotlib

I found adding the subplots at once looked better, i.e.

fig, axs = plt.subplots(rows, cols, constrained_layout=True)

# then iterating over the axes to fill in the plots

But it can also be added at the point the figure is created:

fig = plt.figure(constrained_layout=True)

ax1 = fig.add_subplot(cols, rows, 1)
# etc

Note: To make my subplots closer together, I was also using

fig.subplots_adjust(wspace=0.05)

and constrained_layout doesn't work with this :(

Get a list of distinct values in List

public class KeyNote
{
    public long KeyNoteId { get; set; }
    public long CourseId { get; set; }
    public string CourseName { get; set; }
    public string Note { get; set; }
    public DateTime CreatedDate { get; set; }
}

public List<KeyNote> KeyNotes { get; set; }
public List<RefCourse> GetCourses { get; set; }    

List<RefCourse> courses = KeyNotes.Select(x => new RefCourse { CourseId = x.CourseId, Name = x.CourseName }).Distinct().ToList();

By using the above logic, we can get the unique Courses.

Why doesn't git recognize that my file has been changed, therefore git add not working

I had a similar issue when I created a patch file in server with vi editor. It seems the issue was with spacing. When I pushed the patch from local, deployment was proper.

what's the correct way to send a file from REST web service to client?

I don't recommend encoding binary data in base64 and wrapping it in JSON. It will just needlessly increase the size of the response and slow things down.

Simply serve your file data using GET and application/octect-streamusing one of the factory methods of javax.ws.rs.core.Response (part of the JAX-RS API, so you're not locked into Jersey):

@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFile() {
  File file = ... // Initialize this to the File path you want to serve.
  return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM)
      .header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"" ) //optional
      .build();
}

If you don't have an actual File object, but an InputStream, Response.ok(entity, mediaType) should be able to handle that as well.

Pass array to MySQL stored routine

This helps for me to do IN condition Hope this will help you..

CREATE  PROCEDURE `test`(IN Array_String VARCHAR(100))
BEGIN
    SELECT * FROM Table_Name
    WHERE FIND_IN_SET(field_name_to_search, Array_String);

END//;

Calling:

 call test('3,2,1');