Programs & Examples On #Static media

Difference between OpenJDK and Adoptium/AdoptOpenJDK

In short:

  • OpenJDK has multiple meanings and can refer to:
    • free and open source implementation of the Java Platform, Standard Edition (Java SE)
    • open source repository — the Java source code aka OpenJDK project
    • prebuilt OpenJDK binaries maintained by Oracle
    • prebuilt OpenJDK binaries maintained by the OpenJDK community
  • AdoptOpenJDK — prebuilt OpenJDK binaries maintained by community (open source licensed)

Explanation:

Prebuilt OpenJDK (or distribution) — binaries, built from http://hg.openjdk.java.net/, provided as an archive or installer, offered for various platforms, with a possible support contract.

OpenJDK, the source repository (also called OpenJDK project) - is a Mercurial-based open source repository, hosted at http://hg.openjdk.java.net. The Java source code. The vast majority of Java features (from the VM and the core libraries to the compiler) are based solely on this source repository. Oracle have an alternate fork of this.

OpenJDK, the distribution (see the list of providers below) - is free as in beer and kind of free as in speech, but, you do not get to call Oracle if you have problems with it. There is no support contract. Furthermore, Oracle will only release updates to any OpenJDK (the distribution) version if that release is the most recent Java release, including LTS (long-term support) releases. The day Oracle releases OpenJDK (the distribution) version 12.0, even if there's a security issue with OpenJDK (the distribution) version 11.0, Oracle will not release an update for 11.0. Maintained solely by Oracle.

Some OpenJDK projects - such as OpenJDK 8 and OpenJDK 11 - are maintained by the OpenJDK community and provide releases for some OpenJDK versions for some platforms. The community members have taken responsibility for releasing fixes for security vulnerabilities in these OpenJDK versions.

AdoptOpenJDK, the distribution is very similar to Oracle's OpenJDK distribution (in that it is free, and it is a build produced by compiling the sources from the OpenJDK source repository). AdoptOpenJDK as an entity will not be backporting patches, i.e. there won't be an AdoptOpenJDK 'fork/version' that is materially different from upstream (except for some build script patches for things like Win32 support). Meaning, if members of the community (Oracle or others, but not AdoptOpenJDK as an entity) backport security fixes to updates of OpenJDK LTS versions, then AdoptOpenJDK will provide builds for those. Maintained by OpenJDK community.

OracleJDK - is yet another distribution. Starting with JDK12 there will be no free version of OracleJDK. Oracle's JDK distribution offering is intended for commercial support. You pay for this, but then you get to rely on Oracle for support. Unlike Oracle's OpenJDK offering, OracleJDK comes with longer support for LTS versions. As a developer you can get a free license for personal/development use only of this particular JDK, but that's mostly a red herring, as 'just the binary' is basically the same as the OpenJDK binary. I guess it means you can download security-patched versions of LTS JDKs from Oracle's websites as long as you promise not to use them commercially.

Note. It may be best to call the OpenJDK builds by Oracle the "Oracle OpenJDK builds".

Donald Smith, Java product manager at Oracle writes:

Ideally, we would simply refer to all Oracle JDK builds as the "Oracle JDK", either under the GPL or the commercial license, depending on your situation. However, for historical reasons, while the small remaining differences exist, we will refer to them separately as Oracle’s OpenJDK builds and the Oracle JDK.


OpenJDK Providers and Comparison

----------------------------------------------------------------------------------------
|     Provider      | Free Builds | Free Binary   | Extended | Commercial | Permissive |
|                   | from Source | Distributions | Updates  | Support    | License    |
|--------------------------------------------------------------------------------------|
| AdoptOpenJDK      |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Amazon – Corretto |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Azul Zulu         |    No       |    Yes        |   Yes    |   Yes      |   Yes      |
| BellSoft Liberica |    No       |    Yes        |   Yes    |   Yes      |   Yes      |
| IBM               |    No       |    No         |   Yes    |   Yes      |   Yes      |
| jClarity          |    No       |    No         |   Yes    |   Yes      |   Yes      |
| OpenJDK           |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Oracle JDK        |    No       |    Yes        |   No**   |   Yes      |   No       |
| Oracle OpenJDK    |    Yes      |    Yes        |   No     |   No       |   Yes      |
| ojdkbuild         |    Yes      |    Yes        |   No     |   No       |   Yes      |
| RedHat            |    Yes      |    Yes        |   Yes    |   Yes      |   Yes      |
| SapMachine        |    Yes      |    Yes        |   Yes    |   Yes      |   Yes      |
----------------------------------------------------------------------------------------

Free Builds from Source - the distribution source code is publicly available and one can assemble its own build

Free Binary Distributions - the distribution binaries are publicly available for download and usage

Extended Updates - aka LTS (long-term support) - Public Updates beyond the 6-month release lifecycle

Commercial Support - some providers offer extended updates and customer support to paying customers, e.g. Oracle JDK (support details)

Permissive License - the distribution license is non-protective, e.g. Apache 2.0


Which Java Distribution Should I Use?

In the Sun/Oracle days, it was usually Sun/Oracle producing the proprietary downstream JDK distributions based on OpenJDK sources. Recently, Oracle had decided to do their own proprietary builds only with the commercial support attached. They graciously publish the OpenJDK builds as well on their https://jdk.java.net/ site.

What is happening starting JDK 11 is the shift from single-vendor (Oracle) mindset to the mindset where you select a provider that gives you a distribution for the product, under the conditions you like: platforms they build for, frequency and promptness of releases, how support is structured, etc. If you don't trust any of existing vendors, you can even build OpenJDK yourself.

Each build of OpenJDK is usually made from the same original upstream source repository (OpenJDK “the project”). However each build is quite unique - $free or commercial, branded or unbranded, pure or bundled (e.g., BellSoft Liberica JDK offers bundled JavaFX, which was removed from Oracle builds starting JDK 11).

If no environment (e.g., Linux) and/or license requirement defines specific distribution and if you want the most standard JDK build, then probably the best option is to use OpenJDK by Oracle or AdoptOpenJDK.


Additional information

Time to look beyond Oracle's JDK by Stephen Colebourne

Java Is Still Free by Java Champions community (published on September 17, 2018)

Java is Still Free 2.0.0 by Java Champions community (published on March 3, 2019)

Aleksey Shipilev about JDK updates interview by Opsian (published on June 27, 2019)

Can Mysql Split a column?

It seems to work:

substring_index ( substring_index ( context,',',1 ), ',', -1) 
substring_index ( substring_index ( context,',',2 ), ',', -1)
substring_index ( substring_index ( context,',',3 ), ',', -1)
substring_index ( substring_index ( context,',',4 ), ',', -1)

it means 1st value, 2nd, 3rd, etc.

Explanation:

The inner substring_index returns the first n values that are comma separated. So if your original string is "34,7,23,89", substring_index( context,',', 3) returns "34,7,23".
The outer substring_index takes the value returned by the inner substring_index and the -1 allows you to take the last value. So you get "23" from the "34,7,23".
Instead of -1 if you specify -2, you'll get "7,23", because it took the last two values.

Example:

select * from MyTable where substring_index(substring_index(prices,',',1),',',-1)=3382;

Here, prices is the name of a column in MyTable.

Slide right to left?

If your div is absolutely positioned and you know the width, you can just use:

#myDiv{
position:absolute;
left: 0;
width: 200px;
}

$('#myDiv').animate({left:'-200'},1000);

Which will slide it off screen.

Alternatively, you could wrap it a container div

#myContainer{
position:relative;
width: 200px;
overflow: hidden;
}

#myDiv{
position:absolute;
top: 0;
left: 0;
width: 200px;
}

<div id="myContainer">

<div id="myDiv">Wheee!</div>

</div>

$('#myDiv').animate({left:'-200'},1000);

How to return the current timestamp with Moment.js?

I would like to add that you can have the whole data information in an object with:

const today = moment().toObject();

You should obtain an object with this properties:

today: {
    date: 15,
    hours: 1,
    milliseconds: 927,
    minutes: 59,
    months: 4,
    seconds: 43,
    years: 2019
    }

It is very useful when you have to calculate dates.

Using awk to print all columns from the nth to the last

Printing out columns starting from #2 (the output will have no trailing space in the beginning):

ls -l | awk '{sub(/[^ ]+ /, ""); print $0}'

Java: Unresolved compilation problem

I had this error when I used a launch configuration that had an invalid classpath. In my case, I had a project that initially used Maven and thus a launch configuration had a Maven classpath element in it. I had later changed the project to use Gradle and removed the Maven classpath from the project's classpath, but the launch configuration still used it. I got this error trying to run it. Cleaning and rebuilding the project did not resolve this error. Instead, edit the launch configuration, remove the project classpath element, then add the project back to the User Entries in the classpath.

Eclipse - java.lang.ClassNotFoundException

Please point to correct JDK from Windows > Preferences > Java > Installed JRE.

Do not point to jre, point to a proper JDK. I pointed to JDK 1.6U29 and refreshed the project.

Hereafter, the issue is gone and jUnit Tests are working fine.

Thanks,
-Tapas

How to install XCODE in windows 7 platform?

X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!

There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.

Source: classroomm.com

How to rename a directory/folder on GitHub website?

I changed the 'Untitlted Folder' name by going upward one directory where the untitled folder and other docs are listed.

Tick the little white box in front of the 'Untitled Folder', a 'rename' button will show up at the top. Then click and change the folder name into whatever kinky name you want.

See the 'Rename' button?

See the 'Rename' button?

How to check if a string contains an element from a list in Python

Use list comprehensions if you want a single line solution. The following code returns a list containing the url_string when it has the extensions .doc, .pdf and .xls or returns empty list when it doesn't contain the extension.

print [url_string for extension in extensionsToCheck if(extension in url_string)]

NOTE: This is only to check if it contains or not and is not useful when one wants to extract the exact word matching the extensions.

How to install toolbox for MATLAB

Use ver it will list all the installed toolboxes and versions of the toolbox.

Open and write data to text file using Bash?

I like this answer:

cat > FILE.txt <<EOF

info code info 
...
EOF

but would suggest cat >> FILE.txt << EOF if you want just add something to the end of the file without wiping out what is already exists

Like this:

cat >> FILE.txt <<EOF

info code info 
...
EOF

How to make clang compile to llvm IR

If you have multiple files and you don't want to have to type each file, I would recommend that you follow these simple steps (I am using clang-3.8 but you can use any other version):

  1. generate all .ll files

    clang-3.8 -S -emit-llvm *.c
    
  2. link them into a single one

    llvm-link-3.8 -S -v -o single.ll *.ll
    
  3. (Optional) Optimise your code (maybe some alias analysis)

    opt-3.8 -S -O3 -aa -basicaaa -tbaa -licm single.ll -o optimised.ll
    
  4. Generate assembly (generates a optimised.s file)

    llc-3.8 optimised.ll
    
  5. Create executable (named a.out)

    clang-3.8 optimised.s
    

How do I update a model value in JavaScript in a Razor view?

This should work

function updatePostID(val)
{
    document.getElementById('PostID').value = val;

    //and probably call document.forms[0].submit();
}

Then have a hidden field or other control for the PostID

@Html.Hidden("PostID", Model.addcomment.PostID)
//OR
@Html.HiddenFor(model => model.addcomment.PostID)

Converting unix time into date-time via excel

  • To convert the epoch(Unix-Time) to regular time like for the below timestamp

    Ex: 1517577336206

  • First convert the value with the following function like below

    =LEFT(A1,10) & "." & RIGHT(A1,3)

  • The output will be like below

    Ex: 1517577336.206

  • Now Add the formula like below

    =(((B1/60)/60)/24)+DATE(1970,1,1)

  • Now format the cell like below or required format(Custom format)

    m/d/yyyy h:mm:ss.000

Now example time comes like

2/2/2018 13:15:36.206

The three zeros are for milliseconds

Convert INT to VARCHAR SQL

CONVERT(DATA_TYPE , Your_Column) is the syntax for CONVERT method in SQL. From this convert function we can convert the data of the Column which is on the right side of the comma (,) to the data type in the left side of the comma (,) Please see below example.

SELECT CONVERT (VARCHAR(10), ColumnName) FROM TableName

How display only years in input Bootstrap Datepicker?

$("#year").datepicker( {
    format: "yyyy",
    viewMode: "years", 
    minViewMode: "years"
}).on('changeDate', function(e){
    $(this).datepicker('hide');
});

find difference between two text files with one item per line

If you want to use loops You can try like this: (diff and cmp are much more efficient. )

while read line
do
    flag = 0
    while read line2
    do
       if ( "$line" = "$line2" )
        then
            flag = 1
        fi
     done < file1 
     if ( flag -eq 0 )
     then
         echo $line > file3
     fi
done < file2

Note: The program is only to provide a basic insight into what can be done if u dont want to use system calls such as diff n comm..

How do I hide the bullets on my list for the sidebar?

You have a selector ul on line 252 which is setting list-style: square outside none (a square bullet). You'll have to change it to list-style: none or just remove the line.

If you only want to remove the bullets from that specific instance, you can use the specific selector for that list and its items as follows:

ul#groups-list.items-list { list-style: none }

Is there a program to decompile Delphi?

I don't think there are any machine code decompilers that produce Pascal code. Most "Delphi decompilers" parse form and RTTI data, but do not actually decompile the machine code. I can only recommend using something like DeDe (or similar software) to extract symbol information in combination with a C decompiler, then translate the decompiled C code to Delphi (there are many source code converters out there).

How to use ArgumentCaptor for stubbing?

The line

when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);

would do the same as

when(someObject.doSomething(Matchers.any())).thenReturn(true);

So, using argumentCaptor.capture() when stubbing has no added value. Using Matchers.any() shows better what really happens and therefor is better for readability. With argumentCaptor.capture(), you can't read what arguments are really matched. And instead of using any(), you can use more specific matchers when you have more information (class of the expected argument), to improve your test.

And another problem: If using argumentCaptor.capture() when stubbing it becomes unclear how many values you should expect to be captured after verification. We want to capture a value during verification, not during stubbing because at that point there is no value to capture yet. So what does the argument captors capture method capture during stubbing? It capture anything because there is nothing to be captured yet. I consider it to be undefined behavior and I don't want to use undefined behavior.

Dynamic Height Issue for UITableView Cells (Swift)

I use these

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return 100
}

Set variable with multiple values and use IN

Use a Temp Table or a Table variable, e.g.

select 'A' as [value]
into #tmp
union
select 'B'
union 
select 'C'

and then

SELECT   
blah 
FROM    foo 
WHERE   myField IN (select [value] from #tmp) 

or

SELECT   
f.blah 
FROM foo f INNER JOIN #tmp t ON f.myField = t.[value]

Titlecase all entries into a form_for text field

You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:

class Place < ActiveRecord::Base   before_save do |place|     place.city = place.city.downcase.titleize     place.country = place.country.downcase.titleize   end end 

You can also check out the Ruby on Rails guide for more info.


To answer you question more directly, something like this would work:

<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>   

This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.

Create a batch file to copy and rename file

type C:\temp\test.bat>C:\temp\test.log

CKEditor instance already exists

If you know the name of the editor then it is pretty simple to do this..

For example if the name of the editor is editor1 (this is the id of div or textarea) then you simply check like this

if(CKEDITOR.instances['editor1']){
   // Instance present
}else{
   // Instance not present 
} 

If you want to get the number of initialized editor's then do like the below

for(let inst of CKEDITOR.instances){
   // inst is an Obj of editor instance
   // inst.name will give the name of the editor instance
}

How do I declare a model class in my Angular 2 component using TypeScript?

create model.ts in your component directory as below

export module DataModel {
       export interface DataObjectName {
         propertyName: type;
        }
       export interface DataObjectAnother {
         propertyName: type;
        }
    }

then in your component import above as, import {DataModel} from './model';

export class YourComponent {
   public DataObject: DataModel.DataObjectName;
}

your DataObject should have all the properties from DataObjectName.

Store output of subprocess.Popen call in a string

The following captures stdout and stderr of the process in a single variable. It is Python 2 and 3 compatible:

from subprocess import check_output, CalledProcessError, STDOUT

command = ["ls", "-l"]
try:
    output = check_output(command, stderr=STDOUT).decode()
    success = True 
except CalledProcessError as e:
    output = e.output.decode()
    success = False

If your command is a string rather than an array, prefix this with:

import shlex
command = shlex.split(command)

Redefining the Index in a Pandas DataFrame object

If you don't want 'a' in the index

In :

col = ['a','b','c']

data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)

data

Out:

    a   b   c
0   1   2   3
1  10  11  12
2  20  21  22

In :

data2 = data.set_index('a')

Out:

     b   c
a
1    2   3
10  11  12
20  21  22

In :

data2.index.name = None

Out:

     b   c
 1   2   3
10  11  12
20  21  22

Check if a Postgres JSON array contains a string

A small variation but nothing new infact. It's really missing a feature...

select info->>'name' from rabbits 
where '"carrots"' = ANY (ARRAY(
    select * from json_array_elements(info->'food'))::text[]);

How to auto resize and adjust Form controls with change in resolution

Use combinations of these to get the desired result:

  1. Set Anchor property to None, the controls will not be resized, they only shift their position.

  2. Set Anchor property to Top+Bottom+Left+Right, the controls will be resized but they don't change their position.

  3. Set the Minimum Size of the form to a proper value.

  4. Set Dock property.

  5. Use Form Resize event to change whatever you want

I don't know how font size (label, textbox, combobox, etc.) will be affected in (1) - (4), but it can be controlled in (5).

How to return a complex JSON response with Node.js?

On express 3 you can use directly res.json({foo:bar})

res.json({ msgId: msg.fileName })

See the documentation

How to use Fiddler to monitor WCF service

You can use the Free version of HTTP Debugger.

It is not a proxy and you needn't make any changes in web.config.

Also, it can show both; incoming and outgoing HTTP requests. HTTP Debugger Free

How to set layout_gravity programmatically?

In case you need to set Gravity for a View use the following

Button b=new Button(Context);
b.setGravity(Gravity.CENTER);

For setting layout_gravity for the Button use gravity field for the layoutparams as

LayoutParams lp=new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
lp.gravity=Gravity.CENTER;

try this hope this clears thanks

Usage of sys.stdout.flush() method

As per my understanding, When ever we execute print statements output will be written to buffer. And we will see the output on screen when buffer get flushed(cleared). By default buffer will be flushed when program exits. BUT WE CAN ALSO FLUSH THE BUFFER MANUALLY by using "sys.stdout.flush()" statement in the program. In the below code buffer will be flushed when value of i reaches 5.

You can understand by executing the below code.

chiru@online:~$ cat flush.py
import time
import sys

for i in range(10):
    print i
    if i == 5:
        print "Flushing buffer"
        sys.stdout.flush()
    time.sleep(1)

for i in range(10):
    print i,
    if i == 5:
        print "Flushing buffer"
        sys.stdout.flush()
chiru@online:~$ python flush.py 
0 1 2 3 4 5 Flushing buffer
6 7 8 9 0 1 2 3 4 5 Flushing buffer
6 7 8 9

Sort ObservableCollection<string> through C#

I looked at these, I was getting it sorted, and then it broke the binding, as above. Came up with this solution, though simpler than most of yours, it appears to do what I want to,,,

public static ObservableCollection<string> OrderThoseGroups( ObservableCollection<string> orderThoseGroups)
    {
        ObservableCollection<string> temp;
        temp =  new ObservableCollection<string>(orderThoseGroups.OrderBy(p => p));
        orderThoseGroups.Clear();
        foreach (string j in temp) orderThoseGroups.Add(j);
        return orderThoseGroups;



    }

How to join two sets in one line without using "|"

You can just unpack both sets into one like this:

>>> set_1 = {1, 2, 3, 4}
>>> set_2 = {3, 4, 5, 6}
>>> union = {*set_1, *set_2}
>>> union
{1, 2, 3, 4, 5, 6}

The * unpacks the set. Unpacking is where an iterable (e.g. a set or list) is represented as every item it yields. This means the above example simplifies to {1, 2, 3, 4, 3, 4, 5, 6} which then simplifies to {1, 2, 3, 4, 5, 6} because the set can only contain unique items.

Service Reference Error: Failed to generate code for the service reference

face same issue, resolved by running Visual Studio in Admin mode

How to export library to Jar in Android Studio?

We can export a jar file for Android library project without resource files by Android studio. It is also requirement what I met recently.

1. Config your build.gradle file

    // Task to delete old jar

    task clearJar(type: Delete){
       delete 'release/lunademo.jar'
    }

    // task to export contents as jar
    task makeJar(type: Copy) {
       from ('build/intermediates/bundles/release/')
       into ('build/libs/')
       include ('classes.jar')
       rename('classes.jar', 'lunademo.jar')
    }
    makeJar.dependsOn(clearJar, build)

2. Run gradlew makeJar under your project root

You will see your libs under dir as build/libs/ if you are luckily.

============================================================

If you met issue as "Socket timeout exception" on command line as below,

enter image description here

You can follow this steps to open Gradle window in the right part and click "makeJar" on Android studio like this,

enter image description here

enter image description here

Then go to build/libs dir, you will see your jar file.

Hope that it is helpful for u.

Good Luck @.@

Luna

Store JSON object in data attribute in HTML jQuery

For the record, I found the following code works. It enables you to retrieve the array from the data tag, push a new element on, and store it back in the data tag in the correct JSON format. The same code can therefore be used again to add further elements to the array if desired. I found that $('#my-data-div').attr('data-namesarray', names_string); correctly stores the array, but $('#my-data-div').data('namesarray', names_string); doesn't work.

<div id="my-data-div" data-namesarray='[]'></div>

var names_array = $('#my-data-div').data('namesarray');
names_array.push("Baz Smith");
var names_string = JSON.stringify(names_array);
$('#my-data-div').attr('data-namesarray', names_string);

How to use a Bootstrap 3 glyphicon in an html select

I don't think the standard HTML select will display HTML content. I'd suggest checking out Bootstrap select: http://silviomoreto.github.io/bootstrap-select/

It has several options for displaying icons or other HTML markup in the select.

<select id="mySelect" data-show-icon="true">
  <option data-content="<i class='glyphicon glyphicon-cutlery'></i>">-</option>
  <option data-subtext="<i class='glyphicon glyphicon-eye-open'></i>"></option>
  <option data-subtext="<i class='glyphicon glyphicon-heart-empty'></i>"></option>
  <option data-subtext="<i class='glyphicon glyphicon-leaf'></i>"></option>
  <option data-subtext="<i class='glyphicon glyphicon-music'></i>"></option>
  <option data-subtext="<i class='glyphicon glyphicon-send'></i>"></option>
  <option data-subtext="<i class='glyphicon glyphicon-star'></i>"></option>
</select>

Here is a demo: https://www.codeply.com/go/l6ClKGBmLS

Postgres FOR LOOP

Procedural elements like loops are not part of the SQL language and can only be used inside the body of a procedural language function, procedure (Postgres 11 or later) or a DO statement, where such additional elements are defined by the respective procedural language. The default is PL/pgSQL, but there are others.

Example with plpgsql:

DO
$do$
BEGIN 
   FOR i IN 1..25 LOOP
      INSERT INTO playtime.meta_random_sample
         (col_i, col_id)                       -- declare target columns!
      SELECT  i,     id
      FROM   tbl
      ORDER  BY random()
      LIMIT  15000;
   END LOOP;
END
$do$;

For many tasks that can be solved with a loop, there is a shorter and faster set-based solution around the corner. Pure SQL equivalent for your example:

INSERT INTO playtime.meta_random_sample (col_i, col_id)
SELECT t.*
FROM   generate_series(1,25) i
CROSS  JOIN LATERAL (
   SELECT i, id
   FROM   tbl
   ORDER  BY random()
   LIMIT  15000
   ) t;

About generate_series():

About optimizing performance of random selections:

Can someone explain how to implement the jQuery File Upload plugin?

This is good Angular plugin for uploading files, and its free!

angular file upload

What exactly is "exit" in PowerShell?

It's a reserved keyword (like return, filter, function, break).

Reference

Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:

But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.

Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:

PS C:\> function ex{exit}
PS C:\> new-alias ^D ex

Hyper-V: Create shared folder between host and guest with internal network

  • Open Hyper-V Manager
  • Create a new internal virtual switch (e.g. "Internal Network Connection")
  • Go to your Virtual Machine and create a new Network Adapter -> choose "Internal Network Connection" as virtual switch
  • Start the VM
  • Assign both your host as well as guest an IP address as well as a Subnet mask (IP4, e.g. 192.168.1.1 (host) / 192.168.1.2 (guest) and 255.255.255.0)
  • Open cmd both on host and guest and check via "ping" if host and guest can reach each other (if this does not work disable/enable the network adapter via the network settings in the control panel, restart...)
  • If successfull create a folder in the VM (e.g. "VMShare"), right-click on it -> Properties -> Sharing -> Advanced Sharing -> checkmark "Share this folder" -> Permissions -> Allow "Full Control" -> Apply
  • Now you should be able to reach the folder via the host -> to do so: open Windows Explorer -> enter the path to the guest (\192.168.1.xx...) in the address line -> enter the credentials of the guest (Choose "Other User" - it can be necessary to change the domain therefore enter ".\"[username] and [password])

There is also an easy way for copying via the clipboard:

  • If you start your VM and go to "View" you can enable "Enhanced Session". If you do it is not possible to drag and drop but to copy and paste.

Enhanced Session

Set language for syntax highlighting in Visual Studio Code

Note that for "Untitled" editor ("Untitled-1", "Untitled-2"), you now can set the language in the settings.

The previous setting was:

"files.associations": {
        "untitled-*": "javascript"
 }

This will not always work anymore, because with VSCode 1.42 (Q1 2020) will change the title of those untitled editors.
The title will now be the first line of the document for the editor title, along the generic name as part of the description.
It won't start anymore with "untitled-"

See "Untitled editor improvements"

Regarding the associated language for those "Untitled" editors:

By default, untitled files do not have a specific language mode configured.

VS Code has a setting, files.defaultLanguage, to configure a default language for untitled files.

With this release, the setting can take a new value {activeEditorLanguage} that will dynamically use the language mode of the currently active editor instead of a fixed default.

In addition, when you copy and paste text into an untitled editor, VS Code will now automatically change the language mode of the untitled editor if the text was copied from a VS Code editor:

https://media.githubusercontent.com/media/microsoft/vscode-docs/vnext/release-notes/images/1_42/untitled-copy2.gif

And see workbench.editor.untitled.labelFormat in VSCode 1.43.

Calculate distance between two points in google maps V3

//JAVA
    public Double getDistanceBetweenTwoPoints(Double latitude1, Double longitude1, Double latitude2, Double longitude2) {
    final int RADIUS_EARTH = 6371;

    double dLat = getRad(latitude2 - latitude1);
    double dLong = getRad(longitude2 - longitude1);

    double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(getRad(latitude1)) * Math.cos(getRad(latitude2)) * Math.sin(dLong / 2) * Math.sin(dLong / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return (RADIUS_EARTH * c) * 1000;
    }

    private Double getRad(Double x) {
    return x * Math.PI / 180;
    }

.net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible

The package is not fully compatible with dotnetcore 2.0 for now.

eg, for 'Microsoft.AspNet.WebApi.Client' it maybe supported in version (5.2.4). See Consume new Microsoft.AspNet.WebApi.Client.5.2.4 package for details.

You could try the standard Client package as Federico mentioned.

If that still not work, then as a workaround you can only create a Console App (.Net Framework) instead of the .net core 2.0 console app.

Reference this thread: Microsoft.AspNet.WebApi.Client supported in .NET Core or not?

How to name and retrieve a stash by name in git?

For everything besides the stash creation, I'd propose another solution by introducing fzf as a dependency. I recommend taking 5 minutes of your time and get introduced to it, as it is over-all great productivity booster.

Anyway, a related excerpt from their examples page offering stash searching. It's very easy to change the scriptlet to add additional functionality (like stash application or dropping):

fstash() {
    local out q k sha
    while out=$(
            git stash list --pretty="%C(yellow)%h %>(14)%Cgreen%cr %C(blue)%gs" |
            fzf --ansi --no-sort --query="$q" --print-query \
                --expect=ctrl-d,ctrl-b); do
        mapfile -t out <<< "$out"
        q="${out[0]}"
        k="${out[1]}"
        sha="${out[-1]}"
        sha="${sha%% *}"
        [[ -z "$sha" ]] && continue
        if [[ "$k" == 'ctrl-d' ]]; then
            git diff $sha
        elif [[ "$k" == 'ctrl-b' ]]; then
            git stash branch "stash-$sha" $sha
            break;
        else
            git stash show -p $sha
        fi
    done
}

angularjs: allows only numbers to be typed into a text box

Use ng-only-number to allow only numbers, for example:

<input type="text" ng-only-number data-max-length=5>

MySQL Query - Records between Today and Last 30 Days

Here's a solution without using curdate() function, this is a solution for those who use TSQL I guess

SELECT myDate
FROM myTable
WHERE myDate BETWEEN DATEADD(DAY, -30, GETDATE()) AND GETDATE()

Get url parameters from a string in .NET

Looks like you should loop over the values of myUri.Query and parse it from there.

 string desiredValue;
 foreach(string item in myUri.Query.Split('&'))
 {
     string[] parts = item.Replace("?", "").Split('=');
     if(parts[0] == "desiredKey")
     {
         desiredValue = parts[1];
         break;
     }
 }

I wouldn't use this code without testing it on a bunch of malformed URLs however. It might break on some/all of these:

  • hello.html?
  • hello.html?valuelesskey
  • hello.html?key=value=hi
  • hello.html?hi=value?&b=c
  • etc

How to split() a delimited string to a List<String>

This will read a csv file and it includes a csv line splitter that handles double quotes and it can read even if excel has it open.

    public List<Dictionary<string, string>> LoadCsvAsDictionary(string path)
    {
        var result = new List<Dictionary<string, string>>();

        var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        System.IO.StreamReader file = new System.IO.StreamReader(fs);

        string line;

        int n = 0;
        List<string> columns = null;
        while ((line = file.ReadLine()) != null)
        {
            var values = SplitCsv(line);
            if (n == 0)
            {
                columns = values;
            }
            else
            {
                var dict = new Dictionary<string, string>();
                for (int i = 0; i < columns.Count; i++)
                    if (i < values.Count)
                        dict.Add(columns[i], values[i]);
                result.Add(dict);
            }
            n++;
        }

        file.Close();
        return result;
    }

    private List<string> SplitCsv(string csv)
    {
        var values = new List<string>();

        int last = -1;
        bool inQuotes = false;

        int n = 0;
        while (n < csv.Length)
        {
            switch (csv[n])
            {
                case '"':
                    inQuotes = !inQuotes;
                    break;
                case ',':
                    if (!inQuotes)
                    {
                        values.Add(csv.Substring(last + 1, (n - last)).Trim(' ', ','));
                        last = n;
                    }
                    break;
            }
            n++;
        }

        if (last != csv.Length - 1)
            values.Add(csv.Substring(last + 1).Trim());

        return values;
    }

How to create and use resources in .NET

The above method works good.

Another method (I am assuming web here) is to create your page. Add controls to the page. Then while in design mode go to: Tools > Generate Local Resource. A resource file will automatically appear in the solution with all the controls in the page mapped in the resource file.

To create resources for other languages, append the 4 character language to the end of the file name, before the extension (Account.aspx.en-US.resx, Account.aspx.es-ES.resx...etc).

To retrieve specific entries in the code-behind, simply call this method: GetLocalResourceObject([resource entry key/name]).

How to show all privileges from a user in oracle?

You can use below code to get all the privileges list from all users.

select * from dba_sys_privs 

How to change the color of a CheckBox?

buttonTint worked for me try

android:buttonTint="@color/white"

<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:id="@+id/agreeCheckBox"
    android:text="@string/i_agree_to_terms_s"
    android:buttonTint="@color/white"
    android:layout_below="@+id/avoid_spam_text"/>

JUnit Testing private variables?

If you create your test classes in a seperate folder which you then add to your build path,

Then you could make the test class an inner class of the class under test by using package correctly to set the namespace. This gives it access to private fields and methods.

But dont forget to remove the folder from the build path for your release build.

Precision String Format Specifier In Swift

use below method

let output = String.localizedStringWithFormat(" %.02f %.02f %.02f", r, g, b)

println(output)

POST unchecked HTML checkboxes

I've tried Sam's version first. Good idea, but it causes there to be multiple elements in the form with the same name. If you use any javascript that finds elements based on name, it will now return an array of elements.

I've worked out Shailesh's idea in PHP, it works for me. Here's my code:

/* Delete '.hidden' fields if the original is present, use '.hidden' value if not. */
foreach ($_POST['frmmain'] as $field_name => $value)
{
    // Only look at elements ending with '.hidden'
    if ( !substr($field_name, -strlen('.hidden')) ) {
        break;
    }

    // get the name without '.hidden'
    $real_name = substr($key, strlen($field_name) - strlen('.hidden'));

    // Create a 'fake' original field with the value in '.hidden' if an original does not exist
    if ( !array_key_exists( $real_name, $POST_copy ) ) {
        $_POST[$real_name] = $value;
    }

    // Delete the '.hidden' element
    unset($_POST[$field_name]);
}

How to drop rows of Pandas DataFrame whose value in a certain column is NaN

This question is already resolved, but...

...also consider the solution suggested by Wouter in his original comment. The ability to handle missing data, including dropna(), is built into pandas explicitly. Aside from potentially improved performance over doing it manually, these functions also come with a variety of options which may be useful.

In [24]: df = pd.DataFrame(np.random.randn(10,3))

In [25]: df.iloc[::2,0] = np.nan; df.iloc[::4,1] = np.nan; df.iloc[::3,2] = np.nan;

In [26]: df
Out[26]:
          0         1         2
0       NaN       NaN       NaN
1  2.677677 -1.466923 -0.750366
2       NaN  0.798002 -0.906038
3  0.672201  0.964789       NaN
4       NaN       NaN  0.050742
5 -1.250970  0.030561 -2.678622
6       NaN  1.036043       NaN
7  0.049896 -0.308003  0.823295
8       NaN       NaN  0.637482
9 -0.310130  0.078891       NaN

In [27]: df.dropna()     #drop all rows that have any NaN values
Out[27]:
          0         1         2
1  2.677677 -1.466923 -0.750366
5 -1.250970  0.030561 -2.678622
7  0.049896 -0.308003  0.823295

In [28]: df.dropna(how='all')     #drop only if ALL columns are NaN
Out[28]:
          0         1         2
1  2.677677 -1.466923 -0.750366
2       NaN  0.798002 -0.906038
3  0.672201  0.964789       NaN
4       NaN       NaN  0.050742
5 -1.250970  0.030561 -2.678622
6       NaN  1.036043       NaN
7  0.049896 -0.308003  0.823295
8       NaN       NaN  0.637482
9 -0.310130  0.078891       NaN

In [29]: df.dropna(thresh=2)   #Drop row if it does not have at least two values that are **not** NaN
Out[29]:
          0         1         2
1  2.677677 -1.466923 -0.750366
2       NaN  0.798002 -0.906038
3  0.672201  0.964789       NaN
5 -1.250970  0.030561 -2.678622
7  0.049896 -0.308003  0.823295
9 -0.310130  0.078891       NaN

In [30]: df.dropna(subset=[1])   #Drop only if NaN in specific column (as asked in the question)
Out[30]:
          0         1         2
1  2.677677 -1.466923 -0.750366
2       NaN  0.798002 -0.906038
3  0.672201  0.964789       NaN
5 -1.250970  0.030561 -2.678622
6       NaN  1.036043       NaN
7  0.049896 -0.308003  0.823295
9 -0.310130  0.078891       NaN

There are also other options (See docs at http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html), including dropping columns instead of rows.

Pretty handy!

How to set or change the default Java (JDK) version on OS X?

It is a little bit tricky, but try to follow the steps described in Installing Java on OS X 10.9 (Mavericks). Basically, you gonna have to update your alias to java.

Step by step:

After installing JDK 1.7, you will need to do the sudo ln -snf in order to change the link to current java. To do so, open Terminal and issue the command:

sudo ln -nsf /Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents \
/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK

Note that the directory jdk1.7.0_51.jdk may change depending on the SDK version you have installed.

Now, you need to set JAVA_HOME to point to where jdk_1.7.0_xx.jdk was installed. Open again the Terminal and type:

export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home"

You can add the export JAVA_HOME line above in your .bashrc file to have java permanently in your Terminal

JavaScript get window X/Y position for scroll

function FastScrollUp()
{
     window.scroll(0,0)
};

function FastScrollDown()
{
     $i = document.documentElement.scrollHeight ; 
     window.scroll(0,$i)
};
 var step = 20;
 var h,t;
 var y = 0;
function SmoothScrollUp()
{
     h = document.documentElement.scrollHeight;
     y += step;
     window.scrollBy(0, -step)
     if(y >= h )
       {clearTimeout(t); y = 0; return;}
     t = setTimeout(function(){SmoothScrollUp()},20);

};


function SmoothScrollDown()
{
     h = document.documentElement.scrollHeight;
     y += step;
     window.scrollBy(0, step)
     if(y >= h )
       {clearTimeout(t); y = 0; return;}
     t = setTimeout(function(){SmoothScrollDown()},20);

}

Access host database from a docker container

Other answers did not work well for me. My container could not resolve host ip using host.docker.internal. There are two ways

  1. Sharing host network --net=host:

    docker run -it --net=host  myimage
    
  2. Using docker's ip address, which is usually 172.17.0.1. You can check it by calling ifconfig command and grabbing inet addr of docker interface

    user@ubuntu:~$ ifconfig
    docker0   Link encap:Ethernet  HWaddr 02:42:a4:a2:b2:f1  
      inet addr:172.17.0.1  Bcast:0.0.0.0  Mask:255.255.0.0
      inet6 addr: fe80::42:a4ff:fea2:b2f1/64 Scope:Link
    

Once you have this ip address, you can pass it as an argument to docker run and then to application or as I do it, map the location of jdbc.properties via volume to the directory on host machine, so you can manage the file externally.

  docker run -it -v /host_dir/docker_jdbc_config:${jetty_base}/var/config myimage

NOTE: Your database might not allow external connections. In case of postgresql, you need to edit 2 files, as described here and here:

  1. Edit postgresql.conf to listen on all addresses. By default it will point to localhost.

    listen_addresses = '*'
    
  2. Edit pg_hba.conf to allow connections from all addresses. Add on the last line:

    host     all             all             0.0.0.0/0               md5
    

IMPORTANT: Last step updating database access is not recommended for production use unless you are really sure what you are doing.

Check if a file exists in jenkins pipeline

You need to use brackets when using the fileExists step in an if condition or assign the returned value to a variable

Using variable:

def exists = fileExists 'file'

if (exists) {
    echo 'Yes'
} else {
    echo 'No'
}

Using brackets:

if (fileExists('file')) {
    echo 'Yes'
} else {
    echo 'No'
}

Is try-catch like error handling possible in ASP Classic?

For anytone who has worked in ASP as well as more modern languages, the question will provoke a chuckle. In my experience using a custom error handler (set up in IIS to handle the 500;100 errors) is the best option for ASP error handling. This article describes the approach and even gives you some sample code / database table definition.

http://www.15seconds.com/issue/020821.htm

Here is a link to Archive.org's version

Attribute Error: 'list' object has no attribute 'split'

I think you've actually got a wider confusion here.

The initial error is that you're trying to call split on the whole list of lines, and you can't split a list of strings, only a string. So, you need to split each line, not the whole thing.

And then you're doing for points in Type, and expecting each such points to give you a new x and y. But that isn't going to happen. Types is just two values, x and y, so first points will be x, and then points will be y, and then you'll be done. So, again, you need to loop over each line and get the x and y values from each line, not loop over a single Types from a single line.

So, everything has to go inside a loop over every line in the file, and do the split into x and y once for each line. Like this:

def getQuakeData():
    filename = input("Please enter the quake file: ")
    readfile = open(filename, "r")

    for line in readfile:
        Type = line.split(",")
        x = Type[1]
        y = Type[2]
        print(x,y)

getQuakeData()

As a side note, you really should close the file, ideally with a with statement, but I'll get to that at the end.


Interestingly, the problem here isn't that you're being too much of a newbie, but that you're trying to solve the problem in the same abstract way an expert would, and just don't know the details yet. This is completely doable; you just have to be explicit about mapping the functionality, rather than just doing it implicitly. Something like this:

def getQuakeData():
    filename = input("Please enter the quake file: ")
    readfile = open(filename, "r")
    readlines = readfile.readlines()
    Types = [line.split(",") for line in readlines]
    xs = [Type[1] for Type in Types]
    ys = [Type[2] for Type in Types]
    for x, y in zip(xs, ys):
        print(x,y)

getQuakeData()

Or, a better way to write that might be:

def getQuakeData():
    filename = input("Please enter the quake file: ")
    # Use with to make sure the file gets closed
    with open(filename, "r") as readfile:
        # no need for readlines; the file is already an iterable of lines
        # also, using generator expressions means no extra copies
        types = (line.split(",") for line in readfile)
        # iterate tuples, instead of two separate iterables, so no need for zip
        xys = ((type[1], type[2]) for type in types)
        for x, y in xys:
            print(x,y)

getQuakeData()

Finally, you may want to take a look at NumPy and Pandas, libraries which do give you a way to implicitly map functionality over a whole array or frame of data almost the same way you were trying to.

I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error

Scripts are raw java embedded in the page code, and if you declare variables in your scripts, then they become local variables embedded in the page.

In contrast, JSTL works entirely with scoped attributes, either at page, request or session scope. You need to rework your scriptlet to fish test out as an attribute:

<c:set var="test" value="test1"/>
<%
  String resp = "abc";
  String test = pageContext.getAttribute("test");
  resp = resp + test;
  pageContext.setAttribute("resp", resp);
%>
<c:out value="${resp}"/>

If you look at the docs for <c:set>, you'll see you can specify scope as page, request or session, and it defaults to page.

Better yet, don't use scriptlets at all: they make the baby jesus cry.

How are cookies passed in the HTTP protocol?

Apart from what it's written in other answers, other details related to path of cookie, maximum age of cookie, whether it's secured or not also passed in Set-Cookie response header. For instance:

Set-Cookie:name=value[; expires=date][; domain=domain][; path=path][; secure]


However, not all of these details are passed back to the server by the client when making next HTTP request.

You can also set HttpOnly flag at the end of your cookie, to indicate that your cookie is httponly and must not allowed to be accessed, in scripts by javascript code. This helps to prevent attacks such as session-hijacking.

For more information, see RFC 2109. Also have a look at Nicholas C. Zakas's article, HTTP cookies explained.

Change the row color in DataGridView based on the quantity of a cell value

Try this (Note: I don't have right now Visual Studio ,so code is copy paste from my archive(I haven't test it) :

Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
    Dim drv As DataRowView
    If e.RowIndex >= 0 Then
        If e.RowIndex <= ds.Tables("Products").Rows.Count - 1 Then
            drv = ds.Tables("Products").DefaultView.Item(e.RowIndex)
            Dim c As Color
            If drv.Item("Quantity").Value < 5  Then
                c = Color.LightBlue
            Else
                c = Color.Pink
            End If
            e.CellStyle.BackColor = c
        End If
    End If
End Sub

Merge r brings error "'by' must specify uniquely valid columns"

Rather give names of the column on which you want to merge:

exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)

Google maps API V3 - multiple markers on exact same spot

Expanding on the answers given above, just ensure you set maxZoom option when initializing the map object.

Controlling Spacing Between Table Cells

To get the job done, use

<table cellspacing=12>

If you’d rather “be right” than get things done, you can instead use the CSS property border-spacing, which is supported by some browsers.

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

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

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

    // Some other properties

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

You can always set the FK relation explicitly:

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

    // Some other properties

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

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

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

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

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

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

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

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

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

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

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

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

public int ParentID { get; set; }

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

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

public virtual Patient Patient { get; set; }

Add one day to date in javascript

var datatoday = new Date();
var datatodays = datatoday.setDate(new Date(datatoday).getDate() + 1);
todate = new Date(datatodays);
console.log(todate);

This will help you...

JQuery datepicker not working

For me.. the problem was that the anchor needs a title, and that was missing!

Free easy way to draw graphs and charts in C++?

Cern's ROOT produces some pretty nice stuff, I use it to display Neural Network data a lot.

How to split data into 3 sets (train, validation and test)?

It is very convenient to use train_test_split without performing reindexing after dividing to several sets and not writing some additional code. Best answer above does not mention that by separating two times using train_test_split not changing partition sizes won`t give initially intended partition:

x_train, x_remain = train_test_split(x, test_size=(val_size + test_size))

Then the portion of validation and test sets in the x_remain change and could be counted as

new_test_size = np.around(test_size / (val_size + test_size), 2)
# To preserve (new_test_size + new_val_size) = 1.0 
new_val_size = 1.0 - new_test_size

x_val, x_test = train_test_split(x_remain, test_size=new_test_size)

In this occasion all initial partitions are saved.

How to declare a variable in SQL Server and use it in the same Stored Procedure

CREATE PROCEDURE AddBrand
@BrandName nvarchar(50) = null,
@CategoryID int = null
AS    
BEGIN

DECLARE @BrandID int = null
SELECT @BrandID = BrandID FROM tblBrand 
WHERE BrandName = @BrandName

INSERT INTO tblBrandinCategory (CategoryID, BrandID) 
       VALUES (@CategoryID, @BrandID)

END

EXEC AddBrand @BrandName = 'BMW', @CategoryId = 1

how to make twitter bootstrap submenu to open on the left side?

The simplest way would be to add the pull-left class to your dropdown-submenu

<li class="dropdown-submenu pull-left">

jsfiddle: DEMO

Concrete Javascript Regex for Accented Characters (Diacritics)

from this wiki : https://en.wikipedia.org/wiki/List_of_Unicode_characters#Basic_Latin

for latin letters, I use

/^[A-zÀ-ÖØ-öø-ÿ]+$/ 

it avoids hyphens and specials chars

Click through div to underlying elements

Yes, you CAN do this.

Using pointer-events: none along with CSS conditional statements for IE11 (does not work in IE10 or below), you can get a cross browser compatible solution for this problem.

Using AlphaImageLoader, you can even put transparent .PNG/.GIFs in the overlay div and have clicks flow through to elements underneath.

CSS:

pointer-events: none;
background: url('your_transparent.png');

IE11 conditional:

filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='your_transparent.png', sizingMethod='scale');
background: none !important;

Here is a basic example page with all the code.

Check if a temporary table exists and delete if it exists before creating a temporary table

I think the problem is you need to add GO statement in between to separate the execution into batches. As the second drop script i.e. IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results did not drop the temp table being part of single batch. Can you please try the below script.

IF OBJECT_ID('tempdb..#Results') IS NOT NULL
    DROP TABLE #Results

CREATE TABLE #Results
(
    Company                CHAR(3),
    StepId                TINYINT,
    FieldId                TINYINT,
)

GO

select company, stepid, fieldid from #Results

IF OBJECT_ID('tempdb..#Results') IS NOT NULL
DROP TABLE #Results

CREATE TABLE #Results
(
    Company                CHAR(3),
    StepId                TINYINT,
    FieldId                TINYINT,
    NewColumn            NVARCHAR(50)
)

GO

select company, stepid, fieldid, NewColumn from #Results

React Checkbox not sending onChange

In material ui, state of checkbox can be fetched as

this.refs.complete.state.switched

How do I get an object's unqualified (short) class name?

Here is simple solution for PHP 5.4+

namespace {
    trait Names {
        public static function getNamespace() {
            return implode('\\', array_slice(explode('\\', get_called_class()), 0, -1));
        }

        public static function getBaseClassName() {
            return basename(str_replace('\\', '/', get_called_class()));
        }
    }
}

What will be return?

namespace x\y\z {
    class SomeClass {
        use \Names;
    }

    echo \x\y\z\SomeClass::getNamespace() . PHP_EOL; // x\y\z
    echo \x\y\z\SomeClass::getBaseClassName() . PHP_EOL; // SomeClass
}

Extended class name and namespace works well to:

namespace d\e\f {

    class DifferentClass extends \x\y\z\SomeClass {

    }

    echo \d\e\f\DifferentClass::getNamespace() . PHP_EOL; // d\e\f
    echo \d\e\f\DifferentClass::getBaseClassName() . PHP_EOL; // DifferentClass
}

What about class in global namespace?

namespace {

    class ClassWithoutNamespace {
        use \Names;
    }

    echo ClassWithoutNamespace::getNamespace() . PHP_EOL; // empty string
    echo ClassWithoutNamespace::getBaseClassName() . PHP_EOL; // ClassWithoutNamespace
}

What is the difference between visibility:hidden and display:none?

visibility:hidden preserves the space; display:none doesn't.

How to wrap text of HTML button with fixed width?

You can force it (browser permitting, I imagine) by inserting line breaks in the HTML source, like this:

<INPUT value="Line 1
Line 2">

Of course working out where to place the line breaks is not necessarily trivial...

If you can use an HTML <BUTTON> instead of an <INPUT>, such that the button label is the element's content rather than its value attribute, placing that content inside a <SPAN> with a width attribute that is a few pixels narrower than that of the button seems to do the trick (even in IE6 :-).

Closing Excel Application using VBA

Sub TestSave()
Application.Quit
ThisWorkBook.Close SaveChanges = False
End Sub

This seems to work for me, Even though looks like am quitting app before saving, but it saves...

Compiling dynamic HTML strings from database

You can use

ng-bind-html https://docs.angularjs.org/api/ng/service/$sce

directive to bind html dynamically. However you have to get the data via $sce service.

Please see the live demo at http://plnkr.co/edit/k4s3Bx

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,$sce) {
    $scope.getHtml=function(){
   return $sce.trustAsHtml("<b>Hi Rupesh hi <u>dfdfdfdf</u>!</b>sdafsdfsdf<button>dfdfasdf</button>");
   }
});

  <body ng-controller="MainCtrl">
<span ng-bind-html="getHtml()"></span>
  </body>

Moving from one activity to another Activity in Android

First you have to declare the activity in Manifest. It is important. You can add this inside application like this.

How to getText on an input in protractor

This is answered in the Protractor FAQ: https://github.com/angular/protractor/blob/master/docs/faq.md#the-result-of-gettext-from-an-input-element-is-always-empty

The result of getText from an input element is always empty

This is a webdriver quirk. and elements always have empty getText values. Instead, try:

element.getAttribute('value')

As for question 2, yes, you should be able to use a fully qualified name for by.binding. I suspect that your template does not actually having an element that is bound to risk.name via {{}} or ng-bind.

Can ordered list produce result that looks like 1.1, 1.2, 1.3 (instead of just 1, 2, 3, ...) with css?

I needed to add this to the solution posted in 12 as I was using a list with a mixture of ordered list and unordered lists components. content: no-close-quote seems like an odd thing to add I know, but it works...

ol ul li:before {
    content: no-close-quote;
    counter-increment: none;
    display: list-item;
    margin-right: 100%;
    position: absolute;
    right: 10px;
}

java.lang.UnsupportedClassVersionError Unsupported major.minor version 51.0

Use Maven and use the maven-compiler-plugin to explicitly call the actual correct version JDK javac.exe command, because Maven could be running any version; this also catches the really stupid long standing bug in javac that does not spot runtime breaking class version jars and missing classes/methods/properties when compiling for earlier java versions! This later part could have easily been fixed in Java 1.5+ by adding versioning attributes to new classes, methods, and properties, or separate compiler versioning data, so is a quite stupid oversight by Sun and Oracle.

Is it possible to send a variable number of arguments to a JavaScript function?

You can actually pass as many values as you want to any javascript function. The explicitly named parameters will get the first few values, but ALL parameters will be stored in the arguments array.

To pass the arguments array in "unpacked" form, you can use apply, like so (c.f. Functional Javascript):

var otherFunc = function() {
   alert(arguments.length); // Outputs: 10
}

var myFunc = function() {
  alert(arguments.length); // Outputs: 10
  otherFunc.apply(this, arguments);
}
myFunc(1,2,3,4,5,6,7,8,9,10);

'mat-form-field' is not a known element - Angular 5 & Material2

When using the 'mat-form-field' MatInputModule needs to be imported also

import { 
    MatToolbarModule, 
    MatButtonModule,
    MatSidenavModule,
    MatIconModule,
    MatListModule ,
    MatStepperModule,
    MatInputModule
} from '@angular/material';

The point of test %eax %eax

test is a non-destructive and, it doesn't return the result of the operation but it sets the flags register accordingly. To know what it really tests for you need to check the following instruction(s). Often out is used to check a register against 0, possibly coupled with a jz conditional jump.

Pandas - 'Series' object has no attribute 'colNames' when using apply()

When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].

So this should work:

df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1)) 

Getting the "real" Facebook profile picture URL from graph API

For Android:

According to latest Facebook SDK,

First you need to call GraphRequest API for getting all the details of user in which API also gives URL of current Profile Picture.

Bundle params = new Bundle();
params.putString("fields", "id,email,gender,cover,picture.type(large)");
new GraphRequest(token, "me", params, HttpMethod.GET,
        new GraphRequest.Callback() {
            @Override
            public void onCompleted(GraphResponse response) {
                if (response != null) {
                    try {
                        JSONObject data = response.getJSONObject();
                        if (data.has("picture")) {
                            String profilePicUrl = data.getJSONObject("picture").getJSONObject("data").getString("url");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
}).executeAsync();

java.sql.SQLException: Missing IN or OUT parameter at index:: 1

In your INSERT statements:

INSERT INTO employee(hans,germany) values(?,?)

You've got your values where your field names belong. Change it to be:

INSERT INTO employee(emp_name,emp_address) values(?,?)

If you were to run that statement from a SQL prompt, it would look like this:

INSERT INTO employee(emp_name,emp_address) values('hans','germany');

Note that you'd need to put single quotes around the string/varchar values.

Additionally, you are also not adding any parameters to your prepared statement. That is what's actually causing the error you're seeing. Try this:

PreparedStatement ps = con.prepareStatement(inserting); 
ps.setString(1, "hans");
ps.setString(2, "germany");
ps.execute();

Also (according to Oracle), you can use "execute" for any SQL statement. Using "executeUpdate" would also be valid in this situation, which would return an integer to indicate the number of rows affected.

Insert null/empty value in sql datetime column by default

if there is no value inserted, the default value should be null,empty

In the table definition, make this datetime column allows null, be not defining NOT NULL:

...
DateTimeColumn DateTime,
...

I HAVE ALLOWED NULL VARIABLES THOUGH.

Then , just insert NULL in this column:

INSERT INTO Table(name, datetimeColumn, ...)
VALUES('foo bar', NULL, ..);

Or, you can make use of the DEFAULT constaints:

...
DateTimeColumn DateTime DEFAULT NULL,
...

Then you can ignore it completely in the INSERT statement and it will be inserted withe the NULL value:

INSERT INTO Table(name, ...)
VALUES('foo bar', ..);

Why does SSL handshake give 'Could not generate DH keypair' exception?

I have the same problem with Yandex Maps server, JDK 1.6 and Apache HttpClient 4.2.1. The error was

javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

with enabled debug by -Djavax.net.debug=all there was a message in a log

Could not generate DH keypair

I have fixed this problem by adding BouncyCastle library bcprov-jdk16-1.46.jar and registering a provider in a map service class

public class MapService {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public GeocodeResult geocode() {

    }

}

A provider is registered at the first usage of MapService.

How to refresh Android listview?

The easiest is to just make a new Adaper and drop the old one:

myListView.setAdapter(new MyListAdapter(...));

merge one local branch into another local branch

  1. git checkout [branchYouWantToReceiveBranch] - checkout branch you want to receive branch
  2. git merge [branchYouWantToMergeIntoBranch]

Passing enum or object through an intent (the best solution)

If you just want to send an enum you can do something like:

First declare an enum containing some value(which can be passed through intent):

 public enum MyEnum {
    ENUM_ZERO(0),
    ENUM_ONE(1),
    ENUM_TWO(2),
    ENUM_THREE(3);
    private int intValue;

    MyEnum(int intValue) {
        this.intValue = intValue;
    }

    public int getIntValue() {
        return intValue;
    }

    public static MyEnum getEnumByValue(int intValue) {
        switch (intValue) {
            case 0:
                return ENUM_ZERO;
            case 1:
                return ENUM_ONE;
            case 2:
                return ENUM_TWO;
            case 3:
                return ENUM_THREE;
            default:
                return null;
        }
    }
}

Then:

  intent.putExtra("EnumValue", MyEnum.ENUM_THREE.getIntValue());

And when you want to get it:

  NotificationController.MyEnum myEnum = NotificationController.MyEnum.getEnumByValue(intent.getIntExtra("EnumValue",-1);

Piece of cake!

Correct way to use Modernizr to detect IE?

CSS tricks have a good solution to target IE 11:

http://css-tricks.com/ie-10-specific-styles/

The .NET and Trident/7.0 are unique to IE so can be used to detect IE version 11.

The code then adds the User Agent string to the html tag with the attribute 'data-useragent', so IE 11 can be targeted specifically...

What is the difference between an int and a long in C++?

The only guarantee you have are:

sizeof(char) == 1
sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) <= sizeof(long long)

// FROM @KTC. The C++ standard also has:
sizeof(signed char)   == 1
sizeof(unsigned char) == 1

// NOTE: These size are not specified explicitly in the standard.
//       They are implied by the minimum/maximum values that MUST be supported
//       for the type. These limits are defined in limits.h
sizeof(short)     * CHAR_BIT >= 16
sizeof(int)       * CHAR_BIT >= 16
sizeof(long)      * CHAR_BIT >= 32
sizeof(long long) * CHAR_BIT >= 64
CHAR_BIT         >= 8   // Number of bits in a byte

Also see: Is long guaranteed to be at least 32 bits?

Difference between static and shared libraries?

Static libraries are compiled as part of an application, whereas shared libraries are not. When you distribute an application that depends on shared libaries, the libraries, eg. dll's on MS Windows need to be installed.

The advantage of static libraries is that there are no dependencies required for the user running the application - e.g. they don't have to upgrade their DLL of whatever. The disadvantage is that your application is larger in size because you are shipping it with all the libraries it needs.

As well as leading to smaller applications, shared libraries offer the user the ability to use their own, perhaps better version of the libraries rather than relying on one that's part of the application

C++ Boost: undefined reference to boost::system::generic_category()

This answer actually helped when using Boost and cmake.

Adding add_definitions(-DBOOST_ERROR_CODE_HEADER_ONLY) for cmake file.

My CMakeLists.txt looks like this:

cmake_minimum_required(VERSION 3.12)
project(proj)

set(CMAKE_CXX_STANDARD 17)


set(SHARED_DIR "${CMAKE_SOURCE_DIR}/../shared")

set(BOOST_LATEST_DIR            "${SHARED_DIR}/boost_1_68_0")
set(BOOST_LATEST_BIN_DIR        "${BOOST_LATEST_DIR}/stage/lib")
set(BOOST_LATEST_INCLUDE_DIR    "${BOOST_LATEST_DIR}/boost")
set(BOOST_SYSTEM                "${BOOST_LATEST_BIN_DIR}/libboost_system.so")
set(BOOST_FS                    "${BOOST_LATEST_BIN_DIR}/libboost_filesystem.so")
set(BOOST_THREAD                "${BOOST_LATEST_BIN_DIR}/libboost_thread.so")

set(HYRISE_SQL_PARSER_DIR           "${SHARED_DIR}/hyrise_sql_parser")
set(HYRISE_SQL_PARSER_BIN_DIR       "${HYRISE_SQL_PARSER_DIR}")
set(HYRISE_SQL_PARSER_INCLUDE_DIR   "${HYRISE_SQL_PARSER_DIR}/src")
set(HYRISE_SQLPARSER                "${HYRISE_SQL_PARSER_BIN_DIR}/libsqlparser.so")


include_directories(${CMAKE_SOURCE_DIR} ${BOOST_LATEST_INCLUDE_DIR} ${HYRISE_SQL_PARSER_INCLUDE_DIR})

set(BOOST_LIBRARYDIR "/usr/lib/x86_64-linux-gnu/")
set(Boost_USE_STATIC_LIBS OFF)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)

add_definitions(-DBOOST_ERROR_CODE_HEADER_ONLY)

find_package(Boost 1.68.0 REQUIRED COMPONENTS system thread filesystem)

add_executable(proj main.cpp row/row.cpp row/row.h table/table.cpp table/table.h page/page.cpp page/page.h
        processor/processor.cpp processor/processor.h engine_instance.cpp engine_instance.h utils.h
        meta_command.h terminal/terminal.cpp terminal/terminal.h)


if(Boost_FOUND)
    include_directories(${Boost_INCLUDE_DIRS})
    target_link_libraries(proj PUBLIC Boost::system Boost::filesystem Boost::thread ${HYRISE_SQLPARSER})
endif()

AngularJS $http, CORS and http authentication

For making a CORS request one must add headers to the request along with the same he needs to check of mode_header is enabled in Apache.

For enabling headers in Ubuntu:

sudo a2enmod headers

For php server to accept request from different origin use:

Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

Change the background color in a twitter bootstrap modal?

I used couple of hours trying to figure how to remove background from launched modal, so far tried

.modal-backdrop {    background: none; }

Didn't work even I have tried to work with javascript like

 <script type="text/javascript">   
 $('#modal-id').on('shown.bs.modal',  function () {
       $(".modal-backdrop.in").hide();     })
</script>

Also didn't work either. I just added

data-backdrop="false"

to

<div class="modal fade" id="myModal" data-backdrop="false">......</div>

And Applying css CLASS

.modal {     background-color: transparent !important;  }

Now its working like a charm This worked with Bootstrap 3

How to view unallocated free space on a hard disk through terminal

This is an old question, but I wanted to give my answer as well.

Since we're talking about free available space, we should talk about sectors, since no partitioning or sizing of sectors is done.

For us human beings this doesn't make much sense. To have human-readable information we must translate this number into bytes. So, we have a disk already partitioned and we want to know how much space we may use. I personally don't like the parted solution because my brain-memory for commands is already taken. There is also cfdisk, which gives you free space. But I think fdisk is the quickest solution: it's plain and simple, with nothing to install: execute fdisk /dev/sdx and then enter v into the interactive shell. It will gives you the number of sectors still free.

2004-54-0 [17:03:33][root@minimac:~]$> fdisk /dev/sda
Welcome to fdisk (util-linux 2.23.2).
..
Command (m for help): v
Remaining 1713 unallocated 512-byte sectors

We still have 1713 sectors at 512 bytes each. So, because you love terminal (in 2012, who knows now?) we do echo $(((1713*512)/1024))k, which is 1713 sectors multiplied for 512 bytes (divided by 1024 to have KB), which gives 856k.. not even 900 KB.. and I need another disk..

What exactly is nullptr?

From nullptr: A Type-safe and Clear-Cut Null Pointer:

The new C++09 nullptr keyword designates an rvalue constant that serves as a universal null pointer literal, replacing the buggy and weakly-typed literal 0 and the infamous NULL macro. nullptr thus puts an end to more than 30 years of embarrassment, ambiguity, and bugs. The following sections present the nullptr facility and show how it can remedy the ailments of NULL and 0.

Other references:

Send file via cURL from form POST in PHP

For my the @ symbol did not work, so I do some research and found this way and it work for me, I hope this help you.

    $target_url = "http://server:port/xxxxx.php";           
    $fname = 'file.txt';   
    $cfile = new CURLFile(realpath($fname));

        $post = array (
                  'file' => $cfile
                  );    

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $target_url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");   
    curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: multipart/form-data'));
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);   
    curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);  
    curl_setopt($ch, CURLOPT_TIMEOUT, 100);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

    $result = curl_exec ($ch);

    if ($result === FALSE) {
        echo "Error sending" . $fname .  " " . curl_error($ch);
        curl_close ($ch);
    }else{
        curl_close ($ch);
        echo  "Result: " . $result;
    }   

How do I combine the first character of a cell with another cell in Excel?

Use following formula:

=CONCATENATE(LOWER(MID(A1,1,1)),LOWER( B1))

for

Josh Smith = jsmith

note that A1 contains name and B1 contains surname

How can I see the specific value of the sql_mode?

You can also try this to determine the current global sql_mode value:

SELECT @@GLOBAL.sql_mode;

or session sql_mode value:

SELECT @@SESSION.sql_mode;

I also had the feeling that the SQL mode was indeed empty.

How to read a large file line by line?

The correct, fully Pythonic way to read a file is the following:

with open(...) as f:
    for line in f:
        # Do something with 'line'

The with statement handles opening and closing the file, including if an exception is raised in the inner block. The for line in f treats the file object f as an iterable, which automatically uses buffered I/O and memory management so you don't have to worry about large files.

There should be one -- and preferably only one -- obvious way to do it.

How to copy data to clipboard in C#

Clip.exe is an executable in Windows to set the clipboard. Note that this does not work for other operating systems other than Windows, which still sucks.

        /// <summary>
        /// Sets clipboard to value.
        /// </summary>
        /// <param name="value">String to set the clipboard to.</param>
        public static void SetClipboard(string value)
        {
            if (value == null)
                throw new ArgumentNullException("Attempt to set clipboard with null");

            Process clipboardExecutable = new Process(); 
            clipboardExecutable.StartInfo = new ProcessStartInfo // Creates the process
            {
                RedirectStandardInput = true,
                FileName = @"clip", 
            };
            clipboardExecutable.Start();

            clipboardExecutable.StandardInput.Write(value); // CLIP uses STDIN as input.
            // When we are done writing all the string, close it so clip doesn't wait and get stuck
            clipboardExecutable.StandardInput.Close(); 

            return;
        }

Serializing an object as UTF-8 XML in .NET

I found this blog post which explains the problem very well, and defines a few different solutions:

(dead link removed)

I've settled for the idea that the best way to do it is to completely omit the XML declaration when in memory. It actually is UTF-16 at that point anyway, but the XML declaration doesn't seem meaningful until it has been written to a file with a particular encoding; and even then the declaration is not required. It doesn't seem to break deserialization, at least.

As @Jon Hanna mentions, this can be done with an XmlWriter created like this:

XmlWriter writer = XmlWriter.Create (output, new XmlWriterSettings() { OmitXmlDeclaration = true });

How to completely remove node.js from Windows

I had the same problem with me yesterday and my solution is: 1. uninstall from controlpanel not from your cli 2. download and install the latest or desired version of node from its website 3. if by mistake you tried uninstalling through cli (it will not remove completely most often) then you do not get uninstall option in cpanel in this case install the same version of node and then follow my 1. step

Hope it helps someone.

Wordpress - Images not showing up in the Media Library

I had this problem with wordpress 3.8.1 and it turned out that my functions.php wasn't saved as utf-8. Re-saved it and it

Alphabet range in Python

Here is a simple letter-range implementation:

Code

def letter_range(start, stop="{", step=1):
    """Yield a range of lowercase letters.""" 
    for ord_ in range(ord(start.lower()), ord(stop.lower()), step):
        yield chr(ord_)

Demo

list(letter_range("a", "f"))
# ['a', 'b', 'c', 'd', 'e']

list(letter_range("a", "f", step=2))
# ['a', 'c', 'e']

JavaScript OOP in NodeJS: how?

In the Javascript community, lots of people argue that OOP should not be used because the prototype model does not allow to do a strict and robust OOP natively. However, I don't think that OOP is a matter of langage but rather a matter of architecture.

If you want to use a real strong OOP in Javascript/Node, you can have a look at the full-stack open source framework Danf. It provides all needed features for a strong OOP code (classes, interfaces, inheritance, dependency-injection, ...). It also allows you to use the same classes on both the server (node) and client (browser) sides. Moreover, you can code your own danf modules and share them with anybody thanks to Npm.

Error: unmappable character for encoding UTF8 during maven compilation

Configure the maven-compiler-plugin to use the same character encoding that your source files are encoded in (e.g):

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
        <source>1.6</source>
        <target>1.6</target>
        <encoding>UTF-8</encoding>
    </configuration>
</plugin>

Many maven plugins will by default use the "project.build.sourceEncoding" property so setting this in your pom will cover most plugins.

<project>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
...

However, I prefer setting the encoding in each plugin's configuration that supports it as I like to be explicit.

When your source code is compiled by the maven-compiler-plugin your source code files are read in by the compiler plugin using whatever encoding the compiler plugin is configured with. If your source files have a different encoding than the compiler plugin is using then it is possible that some characters may not exist in both encodings.

Many people prefer to set the encoding on their source files to UTF-8 so as to avoid this problem. To do this in Eclipse you can right click on a project and select Properties->Resource->Text File Encoding and change it to UTF-8. This will encode all your source files in UTF-8. (You should also explicitly configure the maven-compiler-plugin as mentioned above to use UTF-8 encoding.) With your source files and the compiler plugin both using the same encoding you shouldn't have any more unmappable characters during compilation.

Note, You can also set the file encoding globally in eclipse through Window->Preferences->General->Workspace->Text File Encoding. You can also set the encoding per file type through Window->Preferences->General->Content Types.

How to execute only one test spec with angular-cli

This is working for me in Angular 7. It is based on the --main option of the ng command. I am not sure if this option is undocumented and possibly subject to change, but it works for me. I put a line in my package.json file in scripts section. There using the --main option of with the ng test command, I specify the path to the .spec.ts file I want to execute. For example

"test 1": "ng test --main E:/WebRxAngularClient/src/app/test/shared/my-date-utils.spec.ts",

You can run the script as you run any such script. I run it in Webstorm by clicking on "test 1" in the npm section.

Good tool for testing socket connections?

Another tool is tcpmon. This is a java open-source tool to monitor a TCP connection. It's not directly a test server. It is placed in-between a client and a server but allow to see what is going through the "tube" and also to change what is going through.

If my interface must return Task what is the best way to have a no-operation implementation?

return Task.CompletedTask; // this will make the compiler happy

Change Select List Option background colour on hover

The problem is that even JavaScript does not see the option element being hovered. This is just to put emphasis on how it's not going to be solved (any time soon at least) by using just CSS:

window.onmouseover = function(e)
{
 console.log(e.target.nodeName);
}

The only way to resolve this issue (besides waiting a millennia for browser vendors to fix bugs, let alone one that afflicts what you're trying to do) is to replace the drop-down menu with your own HTML/XML using JavaScript. This would likely involve the use of replacing the select element with a ul element and the use of a radio input element per li element.

How to merge remote master to local branch

git rebase didn't seem to work for me. After git rebase, when I try to push changes to my local branch, I kept getting an error ("hint: Updates were rejected because the tip of your current branch is behind its remote counterpart. Integrate the remote changes (e.g. 'git pull ...') before pushing again.") even after git pull. What finally worked for me was git merge.

git checkout <local_branch>
git merge <master> 

If you are a beginner like me, here is a good article on git merge vs git rebase. https://www.atlassian.com/git/tutorials/merging-vs-rebasing

jQuery Datepicker onchange event issue

T.J. Crowder's answer (https://stackoverflow.com/a/6471992/481154) is very good and still remains accurate. Triggering the change event within the onSelect function is as close as you're going to get.

However, there is a nice property on the datepicker object (lastVal) that will allow you to conditionally trigger the change event only on actual changes without having to store the value(s) yourself:

$('#dateInput').datepicker({
     onSelect: function(d,i){
          if(d !== i.lastVal){
              $(this).change();
          }
     }
});

Then just handle change events like normal:

$('#dateInput').change(function(){
     //Change code!
});

How to add leading zeros for for-loop in shell?

I'm not interested in outputting it to the screen (that's what printf is mainly used for, right?) The variable $num is going to be used as a parameter for another program but let me see what I can do with this.

You can still use printf:

for num in {1..5}
do
   value=$(printf "%02d" $num)
   ... Use $value for your purposes
done

How to deserialize a JObject to .NET object

According to this post, it's much better now:

// pick out one album
JObject jalbum = albums[0] as JObject;

// Copy to a static Album instance
Album album = jalbum.ToObject<Album>();

Documentation: Convert JSON to a Type

Print page numbers on pages when printing html

Can you try this, you can use content: counter(page);

     @page {
       @bottom-left {
            content: counter(page) "/" counter(pages);
        }
     }

Ref: http://www.w3.org/TR/CSS21/generate.html#counters

http://www.princexml.com/doc/9.0/page-numbers/

Git - Undo pushed commits

A solution that keeps no traces of the "undo".

NOTE: don't do this if someone allready pulled your change (I would use this only on my personal repo)

do:

git reset <previous label or sha1>

this will re-checkout all the updates locally (so git status will list all updated files)

then you "do your work" and re-commit your changes (Note: this step is optional)

git commit -am "blabla"

At this moment your local tree differs from the remote

git push -f <remote-name> <branch-name>

will push and force remote to consider this push and remove the previous one (specifying remote-name and branch-name is not mandatory but is recommended to avoid updating all branches with update flag).

!! watch-out some tags may still be pointing removed commit !! how-to-delete-a-remote-tag

Validation of file extension before uploading file

we can check it on submit or we can make change event of that control

var fileInput = document.getElementById('file');
    var filePath = fileInput.value;
    var allowedExtensions = /(\.jpeg|\.JPEG|\.gif|\.GIF|\.png|\.PNG)$/;
    if (filePath != "" && !allowedExtensions.exec(filePath)) {
    alert('Invalid file extention pleasse select another file');
    fileInput.value = '';
    return false;
    }

How to get the CUDA version?

One can get the cuda version by typing the following in the terminal:

$ nvcc -V

# below is the result
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2017 NVIDIA Corporation
Built on Fri_Nov__3_21:07:56_CDT_2017
Cuda compilation tools, release 9.1, V9.1.85

Alternatively, one can manually check for the version by first finding out the installation directory using:

$ whereis -b cuda         
cuda: /usr/local/cuda

And then cd into that directory and check for the CUDA version.

ImportError: No module named 'bottle' - PyCharm

I am using Ubuntu 16.04. For me it was the incorrect interpretor, which was by default using the virtual interpretor from project.

So, make sure you select the correct one, as the pip install will install the package to system python interpretor.

enter image description here

How to instantiate a File object in JavaScript?

According to the W3C File API specification, the File constructor requires 2 (or 3) parameters.

So to create a empty file do:

var f = new File([""], "filename");
  • The first argument is the data provided as an array of lines of text;
  • The second argument is the filename ;
  • The third argument looks like:

    var f = new File([""], "filename.txt", {type: "text/plain", lastModified: date})
    

It works in FireFox, Chrome and Opera, but not in Safari or IE/Edge.

How do I convert between big-endian and little-endian values in C++?

If you're using Visual C++ do the following: You include intrin.h and call the following functions:

For 16 bit numbers:

unsigned short _byteswap_ushort(unsigned short value);

For 32 bit numbers:

unsigned long _byteswap_ulong(unsigned long value);

For 64 bit numbers:

unsigned __int64 _byteswap_uint64(unsigned __int64 value);

8 bit numbers (chars) don't need to be converted.

Also these are only defined for unsigned values they work for signed integers as well.

For floats and doubles it's more difficult as with plain integers as these may or not may be in the host machines byte-order. You can get little-endian floats on big-endian machines and vice versa.

Other compilers have similar intrinsics as well.

In GCC for example you can directly call some builtins as documented here:

uint32_t __builtin_bswap32 (uint32_t x)
uint64_t __builtin_bswap64 (uint64_t x)

(no need to include something). Afaik bits.h declares the same function in a non gcc-centric way as well.

16 bit swap it's just a bit-rotate.

Calling the intrinsics instead of rolling your own gives you the best performance and code density btw..

Can't create handler inside thread that has not called Looper.prepare()

UPDATE - 2016

The best alternative is to use RxAndroid (specific bindings for RxJava) for the P in MVP to take charge fo data.

Start by returning Observable from your existing method.

private Observable<PojoObject> getObservableItems() {
    return Observable.create(subscriber -> {

        for (PojoObject pojoObject: pojoObjects) {
            subscriber.onNext(pojoObject);
        }
        subscriber.onCompleted();
    });
}

Use this Observable like this -

getObservableItems().
subscribeOn(Schedulers.io()).
observeOn(AndroidSchedulers.mainThread()).
subscribe(new Observer<PojoObject> () {
    @Override
    public void onCompleted() {
        // Print Toast on completion
    }

    @Override
    public void onError(Throwable e) {}

    @Override
    public void onNext(PojoObject pojoObject) {
        // Show Progress
    }
});
}

----------------------------------------------------------------------------------------------------------------------------------

I know I am a little late but here goes. Android basically works on two thread types namely UI thread and background thread. According to android documentation -

Do not access the Android UI toolkit from outside the UI thread to fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help:

Activity.runOnUiThread(Runnable)  
View.post(Runnable)  
View.postDelayed(Runnable, long)

Now there are various methods to solve this problem.

I will explain it by code sample:

runOnUiThread

new Thread()
{
    public void run()
    {
        myactivity.this.runOnUiThread(new Runnable()
        {
            public void run()
            {
                //Do your UI operations like dialog opening or Toast here
            }
        });
    }
}.start();

LOOPER

Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.

class LooperThread extends Thread {
    public Handler mHandler;

    public void run() {
        Looper.prepare();

        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                // process incoming messages here
            }
        };

        Looper.loop();
    }
}

AsyncTask

AsyncTask allows you to perform asynchronous work on your user interface. It performs the blocking operations in a worker thread and then publishes the results on the UI thread, without requiring you to handle threads and/or handlers yourself.

public void onClick(View v) {
    new CustomTask().execute((Void[])null);
}


private class CustomTask extends AsyncTask<Void, Void, Void> {

    protected Void doInBackground(Void... param) {
        //Do some work
        return null;
    }

    protected void onPostExecute(Void param) {
        //Print Toast or open dialog
    }
}

Handler

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.

Message msg = new Message();


new Thread()
{
    public void run()
    {
        msg.arg1=1;
        handler.sendMessage(msg);
    }
}.start();



Handler handler = new Handler(new Handler.Callback() {

    @Override
    public boolean handleMessage(Message msg) {
        if(msg.arg1==1)
        {
            //Print Toast or open dialog        
        }
        return false;
    }
});

java.util.NoSuchElementException - Scanner reading user input

the reason of the exception has been explained already, however the suggested solution isn't really the best.

You should create a class that keeps a Scanner as private using Singleton Pattern, that makes that scanner unique on your code.

Then you can implement the methods you need or you can create a getScanner ( not recommended ) and you can control it with a private boolean, something like alreadyClosed.

If you are not aware how to use Singleton Pattern, here's a example:

public class Reader {
    
    
    private Scanner reader;
    private static Reader singleton = null;
    private boolean alreadyClosed;
    
    private Reader() {
        alreadyClosed = false;
        reader = new Scanner(System.in);
    }
    
    public static Reader getInstance() {
        if(singleton == null) {
            singleton = new Reader();
        }
        return singleton;
    }
    
    public int nextInt() throws AlreadyClosedException {
        if(!alreadyClosed) {
            return reader.nextInt();
        }
        throw new AlreadyClosedException(); //Custom exception
    }
    
    public double nextDouble() throws AlreadyClosedException {
        if(!alreadyClosed) {
            return reader.nextDouble();
        }
        throw new AlreadyClosedException();
    }
    
    public String nextLine() throws AlreadyClosedException {
        if(!alreadyClosed) {
            return reader.nextLine();
        }
        throw new AlreadyClosedException();
    }
    
    public void close() {
        alreadyClosed = true;
        reader.close();
    }   
}

Handling NULL values in Hive

I use below sql to exclude the null string and empty string lines.

select * from table where length(nvl(column1,0))>0

Because, the length of empty string is 0.

select length('');
+-----------+--+
| length()  |
+-----------+--+
| 0         |
+-----------+--+

Write variable to a file in Ansible

An important comment from tmoschou:

As of Ansible 2.10, The documentation for ansible.builtin.copy says:
If you need variable interpolation in copied files, use the
ansible.builtin.template module. Using a variable in the content
field will result in unpredictable output.

For more details see this and an explanation


Original answer:

You could use the copy module, with the content parameter:

- copy: content="{{ your_json_feed }}" dest=/path/to/destination/file

The docs here: copy module

How do I escape reserved words used as column names? MySQL/Create Table

You should use back tick character (`) eg:

create table if not exists misc_info (
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
`key` TEXT UNIQUE NOT NULL,
value TEXT NOT NULL)ENGINE=INNODB;

What can MATLAB do that R cannot do?

I have used both R and MATLAB to solve problems and construct models related to Environmental Engineering and there is a lot of overlap between the two systems. In my opinion, the advantages of MATLAB lie in specialized domain-specific applications. Some examples are:

  • Functions such as streamline that aid in fluid dynamics investigations.

  • Toolboxes such as the image processing toolset. I have not found a R package that provides an equivalent implementation of tools like the watershed algorithm.

In my opinion MATLAB provides far better interactive graphics capabilities. However, I think R produces better static print-quality graphics, depending on the application. MATLAB's symbolic math toolbox is also better integrated and more capable than R equivalents such as Ryacas or rSymPy. The existence of the MATLAB compiler also allows systems based on MATLAB code to be deployed independently of the MATLAB environment-- although it's availability will depend on how much money you have to throw around.

Another thing I should note is that the MATLAB debugger is one of the best I have worked with.

The principle advantage I see with R is the openness of the system and the ease with which it can be extended. This has resulted in an incredible diversity of packages on CRAN. I know Mathworks also maintains a repository of user-contributed toolboxes and I can't make a fair comparison as I have not used it that much.

The openness of R also extends to linking in compiled code. A while back I had a model written in Fortran and I was trying to decide between using R or MATLAB as a front-end to help prepare input and process results. I spent an hour reading about the MEX interface to compiled code. When I found that I would have to write and maintain a separate Fortran routine that did some intricate pointer juggling in order to manage the interface, I shelved MATLAB.

The R interface consists of calling .Fortran( [subroutine name], [argument list]) and is simply quicker and cleaner.

How can I reverse a list in Python?

Here's a way to lazily evaluate the reverse using a generator:

def reverse(seq):
    for x in range(len(seq), -1, -1): #Iterate through a sequence starting from -1 and increasing by -1.
        yield seq[x] #Yield a value to the generator

Now iterate through like this:

for x in reverse([1, 2, 3]):
    print(x)

If you need a list:

l = list(reverse([1, 2, 3]))

Copy multiple files from one directory to another from Linux shell

Try this simpler one,

cp /home/ankur/folder/file{1,2} /home/ankur/dest

If you want to copy all the 10 files then run this command,

 cp ~/Desktop/{xyz,file{1,2},next,files,which,are,not,similer} foo-bar

Stateless vs Stateful

Just to add on others' contributions....Another way is look at it from a web server and concurrency's point of view...

HTTP is stateless in nature for a reason...In the case of a web server, being stateful means that it would have to remember a user's 'state' for their last connection, and /or keep an open connection to a requester. That would be very expensive and 'stressful' in an application with thousands of concurrent connections...

Being stateless in this case has obvious efficient usage of resources...i.e support a connection in in a single instance of request and response...No overhead of keeping connections open and/or remember anything from the last request...

Spring RestTemplate GET with parameters

To easily manipulate URLs / path / params / etc., you can use Spring's UriComponentsBuilder class. It's cleaner than manually concatenating strings and it takes care of the URL encoding for you:

HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
        .queryParam("msisdn", msisdn)
        .queryParam("email", email)
        .queryParam("clientVersion", clientVersion)
        .queryParam("clientType", clientType)
        .queryParam("issuerName", issuerName)
        .queryParam("applicationName", applicationName);

HttpEntity<?> entity = new HttpEntity<>(headers);

HttpEntity<String> response = restTemplate.exchange(
        builder.toUriString(), 
        HttpMethod.GET, 
        entity, 
        String.class);

How to get next/previous record in MySQL?

CREATE PROCEDURE `pobierz_posty`(IN iduser bigint(20), IN size int, IN page int)
BEGIN
 DECLARE start_element int DEFAULT 0;
 SET start_element:= size * page;
 SELECT DISTINCT * FROM post WHERE id_users .... 
 ORDER BY data_postu DESC LIMIT size OFFSET start_element
END

Set div height to fit to the browser using CSS

I do not think you need float.

_x000D_
_x000D_
html,_x000D_
body,_x000D_
.container {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.div1, .div2 {_x000D_
  display: inline-block;_x000D_
  margin: 0;_x000D_
  min-height: 100%;_x000D_
}_x000D_
_x000D_
.div1 {_x000D_
  width: 25%;_x000D_
  background-color: green;_x000D_
}_x000D_
_x000D_
.div2 {_x000D_
  width: 75%;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="div1"></div><!--_x000D_
  --><div class="div2"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

display: inline-block; is used to display blocks as inline (just like spans but keeping the block effect)

Comments in the html is used because you have 75% + 25% = 100%. The space in-between the divs counts (so you have 75% + 1%? + 25% = 101%, meaning line break)

Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

Minimum eight characters, at least one letter and one number:

"^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$"

Minimum eight characters, at least one letter, one number and one special character:

"^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$"

Minimum eight characters, at least one uppercase letter, one lowercase letter and one number:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$"

Minimum eight characters, at least one uppercase letter, one lowercase letter, one number and one special character:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"

Minimum eight and maximum 10 characters, at least one uppercase letter, one lowercase letter, one number and one special character:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,10}$"

How to open html file?

import codecs
f=codecs.open("test.html", 'r')
print f.read()

Try something like this.

How can I initialise a static Map?

Here is the code by AbacusUtil

Map<Integer, String> map = N.asMap(1, "one", 2, "two");
// Or for Immutable map 
ImmutableMap<Integer, String> = ImmutableMap.of(1, "one", 2, "two");

Declaration: I'm the developer of AbacusUtil.

Asynchronous method call in Python?

You can use process. If you want to run it forever use while (like networking) in you function:

from multiprocessing import Process
def foo():
    while 1:
        # Do something

p = Process(target = foo)
p.start()

if you just want to run it one time, do like that:

from multiprocessing import Process
def foo():
    # Do something

p = Process(target = foo)
p.start()
p.join()

How is VIP swapping + CNAMEs better than IP swapping + A records?

A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.

How do I center an SVG in a div?

Answers above look incomplete as they are talking from css point of view only.

positioning of svg within viewport is affected by two svg attributes

  1. viewBox: defines the rectangle area for svg to cover.
  2. preserveAspectRatio: defined where to place the viewBox wrt viewport and how to strech it if viewport changes.

Follow this link from codepen for detailed description

<svg viewBox="70 160 800 190" preserveAspectRatio="xMaxYMax meet">

Best way to encode text data for XML in Java?

I have created my wrapper here, hope it will helps a lot, Click here You can modify depends on your requirements

Error: "an object reference is required for the non-static field, method or property..."

Create a class and put all your code in there and call an instance of this class from the Main :

static void Main(string[] args)
{

    MyClass cls  = new MyClass();
    Console.Write("Write a number: ");
    long a= Convert.ToInt64(Console.ReadLine()); // a is the number given by the user
    long av = cls.volteado(a);
    bool isTrue = cls.siprimo(a);
    ......etc

}

Convert Decimal to Varchar

If you are using SQL Server 2012, 2014 or newer, use the Format Function instead:

select Format( decimalColumnName ,'FormatString','en-US' )

Review the Microsoft topic and .NET format syntax for how to define the format string.

An example for this question would be:

select Format( MyDecimalColumn ,'N','en-US' )

Monitor network activity in Android Phones

Preconditions: adb and wireshark are installed on your computer and you have a rooted android device.

  1. Download tcpdump to ~/Downloads
  2. adb push ~/Downloads/tcpdump /sdcard/
  3. adb shell
  4. su root
  5. mv /sdcard/tcpdump /data/local/
  6. cd /data/local/
  7. chmod +x tcpdump
  8. ./tcpdump -vv -i any -s 0 -w /sdcard/dump.pcap
  9. Ctrl+C once you've captured enough data.
  10. exit
  11. exit
  12. adb pull /sdcard/dump.pcap ~/Downloads/

Now you can open the pcap file using Wireshark.

As for your question about monitoring specific processes, find the bundle id of your app, let's call it com.android.myapp

  1. ps | grep com.android.myapp
  2. copy the first number you see from the output. Let's call it 1234. If you see no output, you need to start the app.
  3. Download strace to ~/Downloads and put into /data/local using the same way you did for tcpdump above.
  4. cd /data/local
  5. ./strace -p 1234 -f -e trace=network -o /sdcard/strace.txt

Now you can look at strace.txt for ip addresses, and filter your wireshark log for those IPs.

Why java.security.NoSuchProviderException No such provider: BC?

Im not very familiar with the Android sdk, but it seems that the android-sdk comes with the BouncyCastle provider already added to the security.

What you will have to do in the PC environment is just add it manually,

Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

if you have access to the policy file, just add an entry like:

security.provider.5=org.bouncycastle.jce.provider.BouncyCastleProvider 

Notice the .5 it is equal to a sequential number of the already added providers.

Create a HTML table where each TR is a FORM

You can use the form attribute id to span a form over multiple elements each using the form attribute with the name of the form as follows:

<table>
     <tr>
          <td>
               <form method="POST" id="form-1" action="/submit/form-1"></form>
               <input name="a" form="form-1">
          </td>
          <td><input name="b" form="form-1"></td>
          <td><input name="c" form="form-1"></td>
          <td><input type="submit" form="form-1"></td>
     </tr>
</table>

How do I capture the output of a script if it is being ran by the task scheduler?

Use the cmd.exe command processor to build a timestamped file name to log your scheduled task's output

To build upon answers by others here, it may be that you want to create an output file that has the date and/or time embedded in the name of the file. You can use the cmd.exe command processor to do this for you.

Note: This technique takes the string output of internal Windows environment variables and slices them up based on character position. Because of this, the exact values supplied in the examples below may not be correct for the region of Windows you use. Also, with some regional settings, some components of the date or time may introduce a space into the constructed file name when their value is less than 10. To mitigate this issue, surround your file name with quotes so that any unintended spaces in the file name won't break the command-line you're constructing. Experiment and find what works best for your situation.

Be aware that PowerShell is more powerful than cmd.exe. One way it is more powerful is that it can deal with different Windows regions. But this answer is about solving this issue using cmd.exe, not PowerShell, so we continue.

Using cmd.exe

You can access different components of the date and time by slicing the internal environment variables %date% and %time%, as follows (again, the exact slicing values are dependent on the region configured in Windows):

  • Year (4 digits): %date:~10,4%
  • Month (2 digits): %date:~4,2%
  • Day (2 digits): %date:~7,2%
  • Hour (2 digits): %time:~0,2%
  • Minute (2 digits): %time:~3,2%
  • Second (2 digits): %time:~6,2%

Suppose you want your log file to be named using this date/time format: "Log_[yyyyMMdd]_[hhmmss].txt". You'd use the following:

Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt

To test this, run the following command line:

cmd.exe /c echo "Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt"

Putting it all together, to redirect both stdout and stderr from your script to a log file named with the current date and time, use might use the following as your command line:

cmd /c YourProgram.cmd > "Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt" 2>&1

Note the use of quotes around the file name to handle instances a date or time component may introduce a space character.

In my case, if the current date/time were 10/05/2017 9:05:34 AM, the above command-line would produce the following:

cmd /c YourProgram.cmd > "Log_20171005_ 90534.txt" 2>&1

How to change the Title of the window in Qt?

system("title WhateverYouWantToNameIt");

How to read from a file or STDIN in Bash?

I combined all of the above answers and created a shell function that would suit my needs. This is from a cygwin terminal of my 2 Windows10 machines where I had a shared folder between them. I need to be able to handle the following:

  • cat file.cpp | tx
  • tx < file.cpp
  • tx file.cpp

Where a specific filename is specified, I need to used the same filename during copy. Where input data stream has been piped thru, then i need to generate a temporary filename having the hour minute and seconds. The shared mainfolder has subfolders of the days of the week. This is for organizational purposes.

Behold, the ultimate script for my needs:

tx ()
{
  if [ $# -eq 0 ]; then
    local TMP=/tmp/tx.$(date +'%H%M%S')
    while IFS= read -r line; do
        echo "$line"
    done < /dev/stdin > $TMP
    cp $TMP //$OTHER/stargate/$(date +'%a')/
    rm -f $TMP
  else
    [ -r $1 ] && cp $1 //$OTHER/stargate/$(date +'%a')/ || echo "cannot read file"
  fi
}

If there is any way that you can see to further optimize this, I would like to know.

how to read a text file using scanner in Java?

I would recommend loading the file as Resource and converting the input stream into string. This would give you the flexibility to load the file anywhere relative to the classpath

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

When should the xlsm or xlsb formats be used?

Just for posterity, here's the text from several external sources regarding the Excel file formats. Some of these have been mentioned in other answers to this question but without reproducing the essential content.

1. From Doug Mahugh, August 22, 2006:

...the new XLSB binary format. Like Open XML, it’s a full-fidelity file format that can store anything you can create in Excel, but the XLSB format is optimized for performance in ways that aren’t possible with a pure XML format.

The XLSB format (also sometimes referred to as BIFF12, as in “binary file format for Office 12”) uses the same Open Packaging Convention used by the Open XML formats and XPS. So it’s basically a ZIP container, and you can open it with any ZIP tool to see what’s inside. But instead of .XML parts within the package, you’ll find .BIN parts...

This article also refers to documentation about the BIN format, too lengthy to reproduce here.

2. From MSDN Archive, August 29, 2006 which in turn cites an already-missing blog post regarding the XLSB format:

Even though we’ve done a lot of work to make sure that our XML formats open quickly and efficiently, this binary format is still more efficient for Excel to open and save, and can lead to some performance improvements for workbooks that contain a lot of data, or that would require a lot of XML parsing during the Open process. (In fact, we’ve found that the new binary format is faster than the old XLS format in many cases.) Also, there is no macro-free version of this file format – all XLSB files can contain macros (VBA and XLM). In all other respects, it is functionally equivalent to the XML file format above:

File size – file size of both formats is approximately the same, since both formats are saved to disk using zip compression Architecture – both formats use the same packaging structure, and both have the same part-level structures. Feature support – both formats support exactly the same feature set Runtime performance – once loaded into memory, the file format has no effect on application/calculation speed Converters – both formats will have identical converter support

Formatting code in Notepad++

For JavaScript Formatting I use Notepad ++ JSMin Plugin.Quite Handy

Can you have multiple $(document).ready(function(){ ... }); sections?

Yes you can easily have multiple blocks. Just be careful with dependencies between them as the evaluation order might not be what you expect.

Can I pass parameters by reference in Java?

Java is confusing because everything is passed by value. However for a parameter of reference type (i.e. not a parameter of primitive type) it is the reference itself which is passed by value, hence it appears to be pass-by-reference (and people often claim that it is). This is not the case, as shown by the following:

Object o = "Hello";
mutate(o)
System.out.println(o);

private void mutate(Object o) { o = "Goodbye"; } //NOT THE SAME o!

Will print Hello to the console. The options if you wanted the above code to print Goodbye are to use an explicit reference as follows:

AtomicReference<Object> ref = new AtomicReference<Object>("Hello");
mutate(ref);
System.out.println(ref.get()); //Goodbye!

private void mutate(AtomicReference<Object> ref) { ref.set("Goodbye"); }

Using SUMIFS with multiple AND OR conditions

You can use SUMIFS like this

=SUM(SUMIFS(Quote_Value,Salesman,"JBloggs",Days_To_Close,"<=90",Quote_Month,{"Oct-13","Nov-13","Dec-13"}))

The SUMIFS function will return an "array" of 3 values (one total each for "Oct-13", "Nov-13" and "Dec-13"), so you need SUM to sum that array and give you the final result.

Be careful with this syntax, you can only have at most two criteria within the formula with "OR" conditions...and if there are two then in one you must separate the criteria with commas, in the other with semi-colons.

If you need more you might use SUMPRODUCT with MATCH, e.g. in your case

=SUMPRODUCT(Quote_Value,(Salesman="JBloggs")*(Days_To_Close<=90)*ISNUMBER(MATCH(Quote_Month,{"Oct-13","Nov-13","Dec-13"},0)))

In that version you can add any number of "OR" criteria using ISNUMBER/MATCH

How can I insert into a BLOB column from an insert statement in sqldeveloper?

  1. insert into mytable(id, myblob) values (1,EMPTY_BLOB);
  2. SELECT * FROM mytable mt where mt.id=1 for update
  3. Click on the Lock icon to unlock for editing
  4. Click on the ... next to the BLOB to edit
  5. Select the appropriate tab and click open on the top left.
  6. Click OK and commit the changes.

Difference between res.send and res.json in Express.js

Looking in the headers sent...
res.send uses content-type:text/html
res.json uses content-type:application/json

edit: send actually changes what is sent based on what it's given, so strings are sent as text/html, but it you pass it an object it emits application/json.

mysqli::query(): Couldn't fetch mysqli

I had the same problem. I changed the localhost parameter in the mysqli object to '127.0.0.1' instead of writing 'localhost'. It worked; I’m not sure how or why.

$db_connection = new mysqli("127.0.0.1","root","","db_name");

Hope it helps.

How to add a "sleep" or "wait" to my Lua Script?

function wait(time)
    local duration = os.time() + time
    while os.time() < duration do end
end

This is probably one of the easiest ways to add a wait/sleep function to your script

How to make layout with rounded corners..?

With the Material Components Library you can use the MaterialShapeDrawable to draw custom shapes.

Just put the LinearLayout in your xml layout:

<LinearLayout
    android:id="@+id/linear_rounded"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    ..>

    <!-- content ..... -->

</LinearLayout>

Then in your code you can apply a ShapeAppearanceModel. Something like:

float radius = getResources().getDimension(R.dimen.default_corner_radius);

LinearLayout linearLayout= findViewById(R.id.linear_rounded);
ShapeAppearanceModel shapeAppearanceModel = new ShapeAppearanceModel()
    .toBuilder()
    .setAllCorners(CornerFamily.ROUNDED,radius)
    .build();

MaterialShapeDrawable shapeDrawable = new MaterialShapeDrawable(shapeAppearanceModel);
//Fill the LinearLayout with your color
shapeDrawable.setFillColor(ContextCompat.getColorStateList(this,R.color.secondaryLightColor));


ViewCompat.setBackground(linearLayout,shapeDrawable);

enter image description here

Note:: it requires the version 1.1.0 of the material components library.

Convert a PHP object to an associative array

Type cast your object to an array.

$arr =  (array) $Obj;

It will solve your problem.

How to convert Varchar to Int in sql server 2008?

That is how you would do it, is it throwing an error? Are you sure the value you are trying to convert is convertible? For obvious reasons you cannot convert abc123 to an int.

UPDATE

Based on your comments I would remove any spaces that are in the values you are trying to convert.

"Unable to acquire application service" error while launching Eclipse

I got this problem with Mac OS Lion, after transfer OS/Data from an older machine to a new one.

Solved deleting the old eclipse folder (which I have in Applications folder) and copy eclipse folder again (same version, same unpacked zip file, no changes).

Case statement with multiple values in each 'when' block

You might take advantage of ruby's "splat" or flattening syntax.

This makes overgrown when clauses — you have about 10 values to test per branch if I understand correctly — a little more readable in my opinion. Additionally, you can modify the values to test at runtime. For example:

honda  = ['honda', 'acura', 'civic', 'element', 'fit', ...]
toyota = ['toyota', 'lexus', 'tercel', 'rx', 'yaris', ...]
...

if include_concept_cars
  honda += ['ev-ster', 'concept c', 'concept s', ...]
  ...
end

case car
when *toyota
  # Do something for Toyota cars
when *honda
  # Do something for Honda cars
...
end

Another common approach would be to use a hash as a dispatch table, with keys for each value of car and values that are some callable object encapsulating the code you wish to execute.

Is there a way to remove unused imports and declarations from Angular 2+?

If you're a heavy visual studio user, you can simply open your preference settings and add the following to your settings.json:

...
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
  "source.organizeImports": true
}
....

Hopefully this can be helpful!

Running JAR file on Windows

Actually, I faced this problem too, I got around with it by making a .bat runner for my jar file

here is the code:

class FileHandler{
   public static File create_CMD_Rnner(){
      int exitCode = -1625348952;
      try{
           File runner = new File(Main.batName);
           PrintWriter printer = new PrintWriter(runner);
           printer.println("@echo off");
           printer.println("title " + Main.applicationTitle);
           printer.println("java -jar " + Main.jarName + " " + Main.startCode );
           printer.println("PAUSE");
           printer.flush();
           printer.close();
           return runner;
       }catch(Exception e){
           System.err.println("Coudln't create a runner bat \n exit code: " + exitCode);
           System.exit(exitCode);
           return null;
       }
   }
}



Then in Your Main application class do this:

public class Main{
    static String jarName = "application.jar";
    static String applicationTitle = "java Application";
    static String startCode = "javaIsTheBest";
    static String batName = "_.bat";


    public static void main(String args[]) throws Exception{
        if(args.length == 0 || !args[0].equals(startCode)) {
            Desktop.getDesktop().open(FilesHandler.create_CMD_Rnner());
            System.exit(0);
        }else{
            //just in case you wanted to hide the bat
            deleteRunner();
            // Congratulations now you are running in a cmd window ... do whatever you want
            //......
            System.out.println("i Am Running in CMD");
            //......
            Thread.sleep(84600);
        }
    }


    public static void deleteRunner(){
        File batRunner = new File(batName);
        if(batRunner.exists()) batRunner.delete();
    }
}


Please Note that

  1. this code (my code) works only with a jar file, not a class file.

  2. the jar file must have the same name as the String "jarName" is the Main class

pip: no module named _internal

Its probably due to a version conflict, try to run this, it will remove the older pip somehow.

sudo apt remove python pip

How to set the Default Page in ASP.NET?

If you are using forms authentication you could try the code below:

<authentication mode="Forms">
<forms name=".FORM" loginUrl="Login.aspx" defaultUrl="CreateThings.aspx" protection="All" timeout="30" path="/"> 
</forms>
</authentication>

How can you float: right in React Native?

For me setting alignItems to a parent did the trick, like:

var styles = StyleSheet.create({
  container: {
    alignItems: 'flex-end'
  }
});

.aspx vs .ashx MAIN difference

.aspx uses a full lifecycle (Init, Load, PreRender) and can respond to button clicks etc.
An .ashx has just a single ProcessRequest method.

How to hide Android soft keyboard on EditText

The following line is exactly what is being looked for. This method has been included with API 21, therefore it works for API 21 and above.

edittext.setShowSoftInputOnFocus(false);

if-else statement inside jsx: ReactJS

In two ways we can solve this problem:

  1. Write a else condition by adding just empty <div> element.
  2. or else return null.
render() {
    return (   
        <View style={styles.container}>
            if (this.state == 'news'){
                return (
                    <Text>data</Text>
                );
            }
            else {
                 <div> </div>
            }

        </View>
    )
}

Chrome refuses to execute an AJAX script due to wrong MIME type

In my case, I use

$.getJSON(url, function(json) { ... });

to make the request (to Flickr's API), and I got the same MIME error. Like the answer above suggested, adding the following code:

$.ajaxSetup({ dataType: "jsonp" });

Fixed the issue and I no longer see the MIME type error in Chrome's console.

Format date and Subtract days using Moment.js

startdate = moment().subtract(1, 'days').startOf('day')

CustomErrors mode="Off"

I have just dealt with similar issue. In my case the default site asp.net version was 1.1 while i was trying to start up a 2.0 web app. The error was pretty trivial, but it was not immediately clear why the custom errors would not go away, and runtime never wrote to event log. Obvious fix was to match the version in Asp.Net tab of IIS.

htaccess redirect to https://www

I used the below code from this website, it works great https://www.freecodecamp.org/news/how-to-redirect-http-to-https-using-htaccess/

_x000D_
_x000D_
RewriteEngine On_x000D_
RewriteCond %{SERVER_PORT} 80_x000D_
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R,L]
_x000D_
_x000D_
_x000D_

Hope it helps

npm - how to show the latest version of a package

If you're looking for the current and the latest versions of all your installed packages, you can also use:

npm outdated

How do I check if a PowerShell module is installed?

The current version of Powershell has a Get-InstalledModule function that suits this purpose well (or at least it did in my case).

Get-InstalledModule

Description

The Get-InstalledModule cmdlet gets PowerShell modules that are installed on a computer.

The only issue with it is that it throws an exception if the module that is being requested doesn't exist, so we need to set ErrorAction appropriately to suppress that case.

if ((Get-InstalledModule `
    -Name "AzureRm.Profile" `
    -MinimumVersion 5.0 ` # Optionally specify minimum version to have
    -ErrorAction SilentlyContinue) -eq $null) {

    # Install it...
}

How do I use FileSystemObject in VBA?

In excel 2013 the object creation string is:

Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")

instead of the code in the answer above:

Dim fs,fname
Set fs=Server.CreateObject("Scripting.FileSystemObject")

How to create a Date in SQL Server given the Day, Month and Year as Integers

The following code should work on all versions of sql server I believe:

SELECT CAST(CONCAT(CAST(@Year AS VARCHAR(4)), '-',CAST(@Month AS VARCHAR(2)), '-',CAST(@Day AS VARCHAR(2))) AS DATE)

How do I set a Windows scheduled task to run in the background?

Assuming the application you are attempting to run in the background is CLI based, you can try calling the scheduled jobs using Hidden Start

Also see: http://www.howtogeek.com/howto/windows/hide-flashing-command-line-and-batch-file-windows-on-startup/

SVN Repository Search

If you're really desperate, do a dump of the repo (look at "svnadmin dump") and then grep through it. It's not pretty, but you can look around the search results to find the metadata that indicates the file and revision, then check it out for a better look.

Not a good solution, to be sure, but it is free :) SVN provides no feature for searching past checkins (or even past log files, AFAIK).

How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

If you want to filter rows by a certain number of columns with null values, you may use this:

df.iloc[df[(df.isnull().sum(axis=1) >= qty_of_nuls)].index]

So, here is the example:

Your dataframe:

>>> df = pd.DataFrame([range(4), [0, np.NaN, 0, np.NaN], [0, 0, np.NaN, 0], range(4), [np.NaN, 0, np.NaN, np.NaN]])
>>> df
     0    1    2    3
0  0.0  1.0  2.0  3.0
1  0.0  NaN  0.0  NaN
2  0.0  0.0  NaN  0.0
3  0.0  1.0  2.0  3.0
4  NaN  0.0  NaN  NaN

If you want to select the rows that have two or more columns with null value, you run the following:

>>> qty_of_nuls = 2
>>> df.iloc[df[(df.isnull().sum(axis=1) >=qty_of_nuls)].index]
     0    1    2   3
1  0.0  NaN  0.0 NaN
4  NaN  0.0  NaN NaN

How to make an ng-click event conditional?

Basically ng-click first checks the isDisabled and based on its value it will decide whether the function should be called or not.

<span ng-click="(isDisabled) || clicked()">Do something</span>

OR read it as

<span ng-click="(if this value is true function clicked won't be called. and if it's false the clicked will be called) || clicked()">Do something</span>